roamwright 0.61.15 → 0.61.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Generic HUD frame controller: periodic whereabouts readout refresh, auto-expiring inspection card
3
+ * and toast banner timers, and 24-hour day-clock formatting. Zero per-frame allocations.
4
+ * Worker-safe: DOM elements enter via parameters.
5
+ * @module
6
+ */
7
+
8
+ /**
9
+ * Formats a normalised time of day (`0..1`, where 0 is midnight and 0.5 is noon) as `HH:MM`.
10
+ *
11
+ * @param {number} timeOfDay Fraction of the day in `[0, 1)`.
12
+ * @returns {string} Zero-padded 24-hour clock string (e.g. `'09:30'`).
13
+ */
14
+ export function formatDayClock(timeOfDay) {
15
+ const m = Math.round(timeOfDay * 1440) % 1440;
16
+ const h = (m / 60) | 0;
17
+ const mm = m % 60;
18
+ return `${h < 10 ? '0' : ''}${h}:${mm < 10 ? '0' : ''}${mm}`;
19
+ }
20
+
21
+ /**
22
+ * Creates a HUD timer and whereabouts frame controller.
23
+ *
24
+ * @param {object} options
25
+ * @param {() => HTMLElement} options.getLocName Returns the element showing the current place name.
26
+ * @param {() => HTMLElement} options.getLocWay Returns the element showing distance and direction.
27
+ * @param {() => HTMLElement} options.getCard Returns the inspection card container.
28
+ * @param {() => HTMLElement} options.getToast Returns the toast notification element.
29
+ * @param {(dt: number) => void} [options.updateCompass] Per-frame compass updater.
30
+ * @param {() => { name: string, way: string } | null} options.readWhereabouts Returns updated `{ name, way }` when changed, or null.
31
+ * @param {number} [options.lineEvery=0.5] Seconds between whereabouts recalculations.
32
+ * @returns {{ state: { locT: number, toastT: number, cardT: number, cardOf: any }, update: (dt: number) => void,
33
+ * toast: (msg: string, secs?: number) => void, resetLocation: () => void }}
34
+ */
35
+ export function createHudFrame({ getLocName, getLocWay, getCard, getToast, updateCompass = () => {}, readWhereabouts, lineEvery = 0.5 }) {
36
+ const state = { locT: 0, toastT: 0, cardT: 0, cardOf: null };
37
+
38
+ function update(dt) {
39
+ updateCompass(dt);
40
+ state.locT -= dt;
41
+ if (state.locT <= 0) {
42
+ state.locT = lineEvery;
43
+ const next = readWhereabouts();
44
+ if (next) {
45
+ getLocName().textContent = next.name;
46
+ getLocWay().textContent = next.way;
47
+ }
48
+ }
49
+ if (state.cardT > 0) {
50
+ state.cardT -= dt;
51
+ if (state.cardT <= 0) {
52
+ getCard().hidden = true;
53
+ state.cardOf = null;
54
+ }
55
+ }
56
+ if (state.toastT > 0) {
57
+ state.toastT -= dt;
58
+ if (state.toastT <= 0) getToast().classList.remove('show');
59
+ }
60
+ }
61
+
62
+ function toast(msg, secs = 3.2) {
63
+ const el = getToast();
64
+ el.textContent = msg;
65
+ el.classList.add('show');
66
+ state.toastT = secs;
67
+ }
68
+
69
+ function resetLocation() {
70
+ state.locT = 0;
71
+ }
72
+
73
+ return { state, update, toast, resetLocation };
74
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Pure cartographic relief generation and terrain-sheet pixel shading: coastline fractalisation,
3
+ * mountain-range peak placement, forest/dune scatter, route midpoints, and hillshaded or parchment
4
+ * terrain-grid colours. Worker-safe: imports nothing of Three.js or the DOM.
5
+ * @module
6
+ */
7
+ import { mulberry32 } from '../math/random.js';
8
+ import { clamp, lerp, sstep } from '../math/scalar.js';
9
+
10
+ const DEFAULT_PEAK_SIZE = 4.6;
11
+ const DEFAULT_TREE_GAP = 4.4;
12
+ const DEFAULT_DUNE_GAP = 9;
13
+ const DEFAULT_PARCHMENT = Object.freeze([206, 192, 154]);
14
+ const DEFAULT_WATER = Object.freeze([46, 92, 122]);
15
+ const DEFAULT_WATER_PLAIN = Object.freeze([96, 138, 160]);
16
+ const _normal = [0, 0, 0];
17
+
18
+ /**
19
+ * Breaks each straight run of a land polygon into wavy bays and headlands using `random`.
20
+ *
21
+ * @param {{ poly: ReadonlyArray<[number, number]> }} land Polygon specification.
22
+ * @param {() => number} random Deterministic PRNG in `[0, 1)`.
23
+ * @returns {Array<[number, number]>} Subdivided coastline points in sheet units.
24
+ */
25
+ export function brokenCoast(land, random) {
26
+ const out = [];
27
+ const big = land.poly.length > 12;
28
+ for (let i = 0; i < land.poly.length; i++) {
29
+ const a = land.poly[i];
30
+ const b = land.poly[(i + 1) % land.poly.length];
31
+ const dx = b[0] - a[0];
32
+ const dy = b[1] - a[1];
33
+ const len = Math.hypot(dx, dy);
34
+ const n = Math.max(1, Math.round(len / 9));
35
+ const amp = Math.min(len * 0.16, big ? 9 : 4);
36
+ const phase = random() * 9;
37
+ const waves = 1 + random() * 2;
38
+ for (let j = 0; j < n; j++) {
39
+ const t = j / n;
40
+ const o = (Math.sin(t * Math.PI * waves * 2 + phase) * 0.6 + (random() - 0.5) * 0.9) * amp * Math.sin(Math.PI * t);
41
+ out.push([a[0] + dx * t - (dy / len) * o, a[1] + dy * t + (dx / len) * o]);
42
+ }
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /**
48
+ * Distributes mountain peaks in rows along a range polyline, tapering slightly toward its edges.
49
+ *
50
+ * @param {() => number} random Deterministic PRNG in `[0, 1)`.
51
+ * @param {{ pts: ReadonlyArray<[number, number]>, w: number, size?: number }} range Range definition.
52
+ * @param {Array<{ x: number, y: number, s: number }>} out Output array appended in place.
53
+ */
54
+ export function rangePeaks(random, { pts, w, size = DEFAULT_PEAK_SIZE }, out) {
55
+ const rows = Math.max(1, Math.round(w / (size * 0.75)));
56
+ for (let i = 0; i < pts.length - 1; i++) {
57
+ const [ax, ay] = pts[i];
58
+ const [bx, by] = pts[i + 1];
59
+ const len = Math.hypot(bx - ax, by - ay);
60
+ const n = Math.max(1, Math.round(len / (size * 1.25)));
61
+ for (let j = 0; j < n; j++) {
62
+ for (let r = 0; r < rows; r++) {
63
+ const t = (j + random()) / n;
64
+ const off = (((r + 0.2 + 0.6 * random()) / rows) * 2 - 1) * w;
65
+ out.push({
66
+ x: ax + (bx - ax) * t - ((by - ay) / len) * off,
67
+ y: ay + (by - ay) * t + ((bx - ax) / len) * off,
68
+ s: size * (0.65 + 0.6 * random()) * (1 - (0.35 * Math.abs(off)) / w),
69
+ });
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Scatters cartographic marks (trees, dunes) on a jittered grid inside a rotated ellipse.
77
+ *
78
+ * @param {() => number} random Deterministic PRNG in `[0, 1)`.
79
+ * @param {{ at: [number, number], r: [number, number], turn?: number }} patch Ellipse patch.
80
+ * @param {number} gap Nominal grid spacing in sheet units.
81
+ * @param {number} size Base mark size in sheet units.
82
+ * @param {Array<{ x: number, y: number, s: number }>} out Output array appended in place.
83
+ */
84
+ export function scatterReliefMarks(random, { at, r, turn = 0 }, gap, size, out) {
85
+ const c = Math.cos(turn);
86
+ const s = Math.sin(turn);
87
+ for (let v = -r[1]; v <= r[1]; v += gap) {
88
+ for (let q = -r[0]; q <= r[0]; q += gap) {
89
+ const px = q + (random() - 0.5) * gap;
90
+ const py = v + (random() - 0.5) * gap;
91
+ if ((px / r[0]) ** 2 + (py / r[1]) ** 2 < 1) {
92
+ out.push({
93
+ x: at[0] + px * c - py * s,
94
+ y: at[1] + px * s + py * c,
95
+ s: size * (0.75 + 0.5 * random()),
96
+ });
97
+ }
98
+ }
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Computes the midpoint of a voyage route curve where its ship icon sits.
104
+ *
105
+ * @param {ReadonlyArray<[number, number]>} pts Route control points.
106
+ * @returns {[number, number]} Midpoint `[x, y]` in sheet units.
107
+ */
108
+ export function routeMidpoint(pts) {
109
+ const j = (pts.length - 1) >> 1;
110
+ const a = pts[j - 1] ?? pts[j];
111
+ const b = pts[j];
112
+ const c = pts[j + 1];
113
+ return pts.length === 3 ? [a[0] / 4 + b[0] / 2 + c[0] / 4, a[1] / 4 + b[1] / 2 + c[1] / 4] : [(b[0] + c[0]) / 2, (b[1] + c[1]) / 2];
114
+ }
115
+
116
+ /**
117
+ * Total straight-segment length of a polyline in sheet units.
118
+ *
119
+ * @param {ReadonlyArray<[number, number]>} pts
120
+ * @returns {number}
121
+ */
122
+ export function routeLength(pts) {
123
+ let sum = 0;
124
+ for (let i = 1; i < pts.length; i++) sum += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
125
+ return sum;
126
+ }
127
+
128
+ /**
129
+ * Generates all deterministic cartographic atlas marks (broken coasts, land mottle, mountain peaks,
130
+ * forest trees, desert dunes, and route midpoints/lengths) without touching Canvas or Path2D.
131
+ *
132
+ * @param {object} options
133
+ * @param {ReadonlyArray<{ poly: ReadonlyArray<[number, number]>, fade?: number[] }>} options.lands Continent/island polygons.
134
+ * @param {ReadonlyArray<object>} [options.relief=[]] Relief entries (`range`, `forest`, `desert`, `plateau`, `water`).
135
+ * @param {ReadonlyArray<ReadonlyArray<[number, number]>>} [options.rivers=[]] River polylines in sheet units.
136
+ * @param {ReadonlyArray<{ pts: ReadonlyArray<[number, number]> }>} [options.routes=[]] Sea/trade routes.
137
+ * @param {number} [options.seed=4411] PRNG seed used when `random` is omitted.
138
+ * @param {() => number} [options.random] Optional seeded PRNG function.
139
+ * @param {number} [options.treeGap=4.4] Tree scatter spacing in sheet units.
140
+ * @param {number} [options.duneGap=9] Dune scatter spacing in sheet units.
141
+ * @returns {{ coasts: Array<{ fine: Array<[number, number]>, fade?: number[] }>, relief: Array<object>,
142
+ * peaks: Array<{ x: number, y: number, s: number }>, trees: Array<{ x: number, y: number, s: number }>,
143
+ * dunes: Array<{ x: number, y: number, s: number }>, mottle: Array<{ x: number, y: number, r: number, turn: number, dark: boolean }>,
144
+ * rivers: Array<ReadonlyArray<[number, number]>>, routes: Array<object> }}
145
+ */
146
+ export function buildAtlasMarks({
147
+ lands,
148
+ relief = [],
149
+ rivers = [],
150
+ routes = [],
151
+ seed = 4411,
152
+ random = mulberry32(seed),
153
+ treeGap = DEFAULT_TREE_GAP,
154
+ duneGap = DEFAULT_DUNE_GAP,
155
+ }) {
156
+ const coasts = lands.map(land => ({ fine: brokenCoast(land, random), fade: land.fade }));
157
+ const marks = {
158
+ coasts,
159
+ relief: [...relief],
160
+ peaks: [],
161
+ trees: [],
162
+ dunes: [],
163
+ mottle: [],
164
+ rivers: [...rivers],
165
+ routes: [],
166
+ };
167
+ for (let c = 0; c < coasts.length; c++) {
168
+ const fine = coasts[c].fine;
169
+ for (let i = 0; i < fine.length / 2; i++) {
170
+ const q = fine[(random() * fine.length) | 0];
171
+ marks.mottle.push({
172
+ x: q[0] + (random() - 0.5) * 420,
173
+ y: q[1] + (random() - 0.5) * 420,
174
+ r: 8 + random() * 30,
175
+ turn: random() * 3,
176
+ dark: random() < 0.5,
177
+ });
178
+ }
179
+ }
180
+ for (let i = 0; i < marks.relief.length; i++) {
181
+ const m = marks.relief[i];
182
+ if (m.k === 'range') rangePeaks(random, m, marks.peaks);
183
+ else if (m.k === 'forest') scatterReliefMarks(random, m, treeGap, 2, marks.trees);
184
+ else if (m.k === 'desert') scatterReliefMarks(random, m, duneGap, 3.4, marks.dunes);
185
+ }
186
+ marks.peaks.sort((p, q) => p.y - q.y);
187
+ marks.trees.sort((p, q) => p.y - q.y);
188
+ marks.routes = routes.map(r => ({
189
+ ...r,
190
+ mid: routeMidpoint(r.pts),
191
+ len: routeLength(r.pts),
192
+ }));
193
+ return marks;
194
+ }
195
+
196
+ /**
197
+ * Computes one pixel's RGB colour on a land's baked terrain map sheet: either hillshaded from the
198
+ * land's terrain colours and surface normals, or flat parchment tinted with value noise, blended
199
+ * with water wherever `land.depth(index) > 0`.
200
+ *
201
+ * @param {{ colors: ArrayLike<number>, stride: number, normal: (index: number, out: number[]) => number[], depth: (index: number) => number }} land
202
+ * @param {number} index Flat grid cell index (`j * stride + i`).
203
+ * @param {boolean} shaded True for hillshaded terrain colours, false for parchment mode.
204
+ * @param {number[]} out 3-element output RGB array (0..255) written in place.
205
+ * @param {object} [options]
206
+ * @param {(x: number, y: number, salt: number) => number} [options.noise] 2D value noise in `[0, 1]` for parchment mottling.
207
+ * @param {ReadonlyArray<number>} [options.parchment=[206, 192, 154]] Base parchment RGB.
208
+ * @param {ReadonlyArray<number>} [options.water=[46, 92, 122]] Water RGB on shaded sheets.
209
+ * @param {ReadonlyArray<number>} [options.waterPlain=[96, 138, 160]] Water RGB on parchment sheets.
210
+ * @returns {number[]} The `out` RGB array.
211
+ */
212
+ export function shadeTerrainPixel(
213
+ land,
214
+ index,
215
+ shaded,
216
+ out,
217
+ { noise = () => 0.5, parchment = DEFAULT_PARCHMENT, water = DEFAULT_WATER, waterPlain = DEFAULT_WATER_PLAIN } = {},
218
+ ) {
219
+ const colors = land.colors;
220
+ const stride = land.stride;
221
+ if (shaded) {
222
+ const N = land.normal(index, _normal);
223
+ const shade = clamp(0.5 + 0.85 * (N[0] * -0.5 + N[1] * 0.68 + N[2] * -0.5), 0.35, 1.25);
224
+ for (let c = 0; c < 3; c++) out[c] = colors[index * 3 + c] * shade;
225
+ } else {
226
+ const tone = 0.94 + 0.06 * noise((index % stride) / 9, ((index / stride) | 0) / 9, 88);
227
+ for (let c = 0; c < 3; c++) out[c] = parchment[c] * tone;
228
+ }
229
+ const deep = land.depth(index);
230
+ if (deep > 0) {
231
+ const t = 0.55 + 0.4 * sstep(0, 3, deep);
232
+ const tint = shaded ? water : waterPlain;
233
+ for (let c = 0; c < 3; c++) out[c] = lerp(out[c], tint[c], t);
234
+ }
235
+ return out;
236
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Pure map coordinate containment, atlas-to-land lookup, and nearest-place spot descriptions.
3
+ * Worker-safe: imports nothing of Three.js or the DOM.
4
+ * @module
5
+ */
6
+ import { TAU } from '../math/scalar.js';
7
+
8
+ /**
9
+ * Eight cardinal and intercardinal compass directions clockwise from north (`-z`).
10
+ * @type {ReadonlyArray<string>}
11
+ */
12
+ export const COMPASS_WINDS = Object.freeze(['north', 'north-east', 'east', 'south-east', 'south', 'south-west', 'west', 'north-west']);
13
+
14
+ /**
15
+ * Tests whether `(x, z)` lies within a square land's bounds `[x0, x0 + size] x [z0, z0 + size]`.
16
+ *
17
+ * @param {{ x0: number, z0: number, size: number }} land
18
+ * @param {number} x World X coordinate in metres.
19
+ * @param {number} z World Z coordinate in metres.
20
+ * @returns {boolean}
21
+ */
22
+ export function isOnLand(land, x, z) {
23
+ return x >= land.x0 && x <= land.x0 + land.size && z >= land.z0 && z <= land.z0 + land.size;
24
+ }
25
+
26
+ /**
27
+ * Maximum axis distance from the centre of a square land, normalised by its side length (0 at centre, 0.5 at edge).
28
+ *
29
+ * @param {{ x0: number, z0: number, size: number }} land
30
+ * @param {number} x World X coordinate in metres.
31
+ * @param {number} z World Z coordinate in metres.
32
+ * @returns {number}
33
+ */
34
+ export function landOffCentre(land, x, z) {
35
+ return Math.max(Math.abs(x - land.x0 - land.size / 2), Math.abs(z - land.z0 - land.size / 2)) / land.size;
36
+ }
37
+
38
+ /**
39
+ * Finds the flyable land covering atlas point `(x, y)`. Where overlapping lands both contain the point,
40
+ * chooses the land in which the point lies deeper inside its square.
41
+ *
42
+ * @template {{ x0: number, z0: number, size: number, fromAtlas: (x: number, y: number) => [number, number] }} T
43
+ * @param {Iterable<T>} lands Candidate lands.
44
+ * @param {number} x Atlas X coordinate.
45
+ * @param {number} y Atlas Y coordinate.
46
+ * @returns {T | null}
47
+ */
48
+ export function findLandAtAtlas(lands, x, y) {
49
+ let best = null;
50
+ let least = Infinity;
51
+ for (const land of lands) {
52
+ const [lx, lz] = land.fromAtlas(x, y);
53
+ const off = landOffCentre(land, lx, lz);
54
+ if (isOnLand(land, lx, lz) && off < least) {
55
+ least = off;
56
+ best = land;
57
+ }
58
+ }
59
+ return best;
60
+ }
61
+
62
+ /**
63
+ * Describes an arbitrary spot `(x, z)` on a land relative to its nearest named place,
64
+ * with a look target `(lx, lz)` facing that landmark.
65
+ *
66
+ * @param {object} options
67
+ * @param {{ id: string, name: string, size: number }} options.land Target land.
68
+ * @param {number} options.x World X coordinate in metres.
69
+ * @param {number} options.z World Z coordinate in metres.
70
+ * @param {ReadonlyArray<{ name: string, x: number, z: number }>} options.namedPlaces Named reference places on the land.
71
+ * @param {number} [options.nearShare=0.03] Fraction of `land.size` within which a spot reads as "near" the place.
72
+ * @param {ReadonlyArray<string>} [options.winds=COMPASS_WINDS] Eight compass direction names clockwise from north.
73
+ * @returns {{ land: string, x: number, z: number, lx: number, lz: number, where: string }}
74
+ */
75
+ export function describeMapSpot({ land, x, z, namedPlaces, nearShare = 0.03, winds = COMPASS_WINDS }) {
76
+ let nearest = null;
77
+ let least = Infinity;
78
+ for (let i = 0; i < namedPlaces.length; i++) {
79
+ const p = namedPlaces[i];
80
+ const d = Math.hypot(p.x - x, p.z - z);
81
+ if (d < least) {
82
+ least = d;
83
+ nearest = p;
84
+ }
85
+ }
86
+ if (!nearest) return { land: land.id, x, z, lx: x, lz: z - 1, where: 'in ' + land.name };
87
+ const wind = winds[(Math.round(Math.atan2(x - nearest.x, nearest.z - z) / (TAU / 8)) + 8) % 8];
88
+ const near = least < land.size * nearShare;
89
+ return {
90
+ land: land.id,
91
+ x,
92
+ z,
93
+ lx: nearest.x,
94
+ lz: near ? nearest.z - 1 : nearest.z,
95
+ where: (near ? 'near ' : wind + ' of ') + nearest.name,
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Formats a map selection card for a visitor-chosen spot.
101
+ *
102
+ * @param {object} options
103
+ * @param {{ id: string, name: string, size: number }} options.land
104
+ * @param {number} options.x World X coordinate in metres.
105
+ * @param {number} options.z World Z coordinate in metres.
106
+ * @param {object} options.at Sheet coordinates merged into the card (e.g. `{ x, z, land }` or `{ x, z, world: true }`).
107
+ * @param {ReadonlyArray<{ name: string, x: number, z: number }>} options.namedPlaces
108
+ * @param {string} [options.kindSuffix='a spot of your choosing']
109
+ * @param {number} [options.nearShare=0.03]
110
+ * @returns {object}
111
+ */
112
+ export function formatSpotCard({ land, x, z, at, namedPlaces, kindSuffix = 'a spot of your choosing', nearShare = 0.03 }) {
113
+ const spot = describeMapSpot({ land, x, z, namedPlaces, nearShare });
114
+ return {
115
+ ...at,
116
+ name: spot.where[0].toUpperCase() + spot.where.slice(1),
117
+ kind: `${land.name} · ${kindSuffix}`,
118
+ spot,
119
+ };
120
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Pure map view framing, sizing, zoom bounds, marker hit-testing, marker clustering, and
3
+ * orthogonal rectangle-union outlining. Worker-safe: imports nothing of Three.js or the DOM.
4
+ * @module
5
+ */
6
+ import { clamp } from '../math/scalar.js';
7
+
8
+ /**
9
+ * Clamps a view centre along one axis of a sheet running from `origin` for `size` units.
10
+ * When the view is wider than the sheet, keeps it centred on the sheet.
11
+ *
12
+ * @param {number} center Requested view centre in sheet units.
13
+ * @param {number} viewSpan Visible width or height in sheet units.
14
+ * @param {number} origin Sheet start coordinate along this axis.
15
+ * @param {number} size Sheet extent along this axis.
16
+ * @returns {number} Clamped centre in sheet units.
17
+ */
18
+ export function clampViewCenter(center, viewSpan, origin, size) {
19
+ return viewSpan >= size ? origin + size / 2 : clamp(center, origin + viewSpan / 2, origin + size - viewSpan / 2);
20
+ }
21
+
22
+ /**
23
+ * Computes a map sheet's transform (`k`, `x0`, `z0`, `w`, `h`, `u`, `mini`) in place on `out`,
24
+ * returning the clamped centre `[mx, mz]`. When `whole` is true the entire sheet fits inside
25
+ * the canvas at zoom 1; otherwise the shorter canvas side fills edge to edge at zoom 1.
26
+ *
27
+ * @param {object} out Mutable view record updated in place (`x0`, `z0`, `k`, `w`, `h`, `u`, `mini`).
28
+ * @param {object} options
29
+ * @param {number} options.cx Requested view centre X in sheet units.
30
+ * @param {number} options.cz Requested view centre Z/Y in sheet units.
31
+ * @param {number} options.zoom Current zoom multiplier.
32
+ * @param {number} options.originX Sheet X origin in sheet units.
33
+ * @param {number} options.originZ Sheet Z/Y origin in sheet units.
34
+ * @param {number} options.sheetWidth Sheet width in sheet units.
35
+ * @param {number} options.sheetHeight Sheet height in sheet units.
36
+ * @param {number} options.canvasWidth Canvas width in physical pixels.
37
+ * @param {number} options.canvasHeight Canvas height in physical pixels.
38
+ * @param {number} [options.dpr=1] Physical pixels per CSS pixel.
39
+ * @param {boolean} [options.whole=false] Fit the entire sheet inside the viewport at zoom 1.
40
+ * @returns {[number, number]} Clamped `[mx, mz]` centre in sheet units.
41
+ */
42
+ export function frameMapSheet(
43
+ out,
44
+ { cx, cz, zoom, originX, originZ, sheetWidth, sheetHeight, canvasWidth, canvasHeight, dpr = 1, whole = false },
45
+ ) {
46
+ const k =
47
+ (whole
48
+ ? Math.min(canvasWidth / sheetWidth, canvasHeight / sheetHeight)
49
+ : Math.max(canvasWidth / sheetWidth, canvasHeight / sheetHeight)) * zoom;
50
+ const mx = clampViewCenter(cx, canvasWidth / k, originX, sheetWidth);
51
+ const mz = clampViewCenter(cz, canvasHeight / k, originZ, sheetHeight);
52
+ out.k = k;
53
+ out.x0 = mx - canvasWidth / k / 2;
54
+ out.z0 = mz - canvasHeight / k / 2;
55
+ out.w = canvasWidth;
56
+ out.h = canvasHeight;
57
+ out.u = dpr;
58
+ out.mini = false;
59
+ return [mx, mz];
60
+ }
61
+
62
+ /**
63
+ * Computes a map canvas's CSS and physical pixel dimensions from its container layout.
64
+ * Stacked layouts cap height to `viewportHeight * narrowShare` (never taller than wide).
65
+ *
66
+ * @param {object} options
67
+ * @param {boolean} options.stacked Whether the legend is stacked below the canvas (`flexDirection === 'column'`).
68
+ * @param {number} options.parentWidth Parent container width in CSS pixels.
69
+ * @param {number} options.boxWidth Map box width in CSS pixels.
70
+ * @param {number} options.boxHeight Map box height in CSS pixels.
71
+ * @param {number} options.viewportHeight Live viewport height in CSS pixels.
72
+ * @param {number} [options.narrowShare=0.52] Maximum fraction of viewport height when stacked.
73
+ * @param {number} [options.minSide=240] Minimum width and height in CSS pixels.
74
+ * @param {number} [options.maxDpr=2] Maximum device pixel ratio.
75
+ * @param {number} [options.devicePixelRatio=1] Current screen pixel density.
76
+ * @returns {{ cssWidth: number, cssHeight: number, pixelWidth: number, pixelHeight: number, dpr: number }}
77
+ */
78
+ export function fitMapDimensions({
79
+ stacked,
80
+ parentWidth,
81
+ boxWidth,
82
+ boxHeight,
83
+ viewportHeight,
84
+ narrowShare = 0.52,
85
+ minSide = 240,
86
+ maxDpr = 2,
87
+ devicePixelRatio = 1,
88
+ }) {
89
+ const wide = stacked ? parentWidth : boxWidth;
90
+ const tall = stacked ? Math.min(wide, viewportHeight * narrowShare) : boxHeight;
91
+ const cssWidth = Math.max(minSide, Math.floor(wide));
92
+ const cssHeight = Math.max(minSide, Math.floor(tall));
93
+ const dpr = Math.min(devicePixelRatio || 1, maxDpr);
94
+ return {
95
+ cssWidth,
96
+ cssHeight,
97
+ pixelWidth: Math.round(cssWidth * dpr),
98
+ pixelHeight: Math.round(cssHeight * dpr),
99
+ dpr,
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Minimum zoom at which a square land sheet fits completely inside a canvas of `width` by `height`.
105
+ *
106
+ * @param {number} width Canvas width in pixels.
107
+ * @param {number} height Canvas height in pixels.
108
+ * @returns {number} Minimum zoom multiplier (at most 1).
109
+ */
110
+ export function sheetMinZoom(width, height) {
111
+ return Math.min(1, Math.min(width, height) / Math.max(width, height, 1));
112
+ }
113
+
114
+ /**
115
+ * Maximum zoom for a land sheet of `landSize` metres, scaling down on very large lands before baked ground blurs.
116
+ *
117
+ * @param {number} landSize Land side length in metres.
118
+ * @param {number} [divisor=400] Metres per zoom step.
119
+ * @param {number} [floor=9] Minimum maximum-zoom value.
120
+ * @returns {number} Maximum zoom multiplier.
121
+ */
122
+ export function sheetMaxZoom(landSize, divisor = 400, floor = 9) {
123
+ return Math.max(floor, landSize / divisor);
124
+ }
125
+
126
+ /**
127
+ * Picks the hit circle closest to `(px, py)` within its radius plus a touch-friendly padding.
128
+ *
129
+ * @template {{ x: number, y: number, r: number }} T
130
+ * @param {ReadonlyArray<T>} hits Screen-space hit circles.
131
+ * @param {number} px Tap X in canvas pixels.
132
+ * @param {number} py Tap Y in canvas pixels.
133
+ * @param {number} [dpr=1] Physical pixels per CSS pixel.
134
+ * @param {number} [padCss=8] Extra tap forgiveness in CSS pixels.
135
+ * @returns {T | null} Closest matching hit, or null.
136
+ */
137
+ export function pickMapHit(hits, px, py, dpr = 1, padCss = 8) {
138
+ let best = null;
139
+ let bestDist = 1e9;
140
+ const pad = padCss * dpr;
141
+ for (let i = 0; i < hits.length; i++) {
142
+ const h = hits[i];
143
+ const d = Math.hypot(h.x - px, h.y - py);
144
+ if (d < h.r + pad && d < bestDist) {
145
+ bestDist = d;
146
+ best = h;
147
+ }
148
+ }
149
+ return best;
150
+ }
151
+
152
+ /**
153
+ * Groups nearby screen-space items into clusters whose centroid averages their screen and world coordinates.
154
+ *
155
+ * @template {{ x: number, z: number }} T
156
+ * @param {ReadonlyArray<T>} items World items to cluster.
157
+ * @param {(x: number) => number} projectX Maps world X to canvas X.
158
+ * @param {(z: number) => number} projectY Maps world Z to canvas Y.
159
+ * @param {number} thresholdPx Maximum screen distance in pixels to merge into an existing cluster.
160
+ * @returns {Array<{ x: number, y: number, wx: number, wz: number, list: T[] }>}
161
+ */
162
+ export function clusterMapPoints(items, projectX, projectY, thresholdPx) {
163
+ const clusters = [];
164
+ for (let i = 0; i < items.length; i++) {
165
+ const item = items[i];
166
+ const x = projectX(item.x);
167
+ const y = projectY(item.z);
168
+ const existing = clusters.find(c => Math.hypot(c.x - x, c.y - y) < thresholdPx);
169
+ if (existing) {
170
+ const n = existing.list.push(item);
171
+ existing.x += (x - existing.x) / n;
172
+ existing.y += (y - existing.y) / n;
173
+ existing.wx += (item.x - existing.wx) / n;
174
+ existing.wz += (item.z - existing.wz) / n;
175
+ } else {
176
+ clusters.push({ x, y, wx: item.x, wz: item.z, list: [item] });
177
+ }
178
+ }
179
+ return clusters;
180
+ }
181
+
182
+ /**
183
+ * Computes the merged outer perimeter of axis-aligned square or rectangular frames as flat `[x0, y0, x1, y1, ...]`
184
+ * line segments. Overlapping or adjacent frames within `meetTolerance` share no interior border line.
185
+ *
186
+ * @param {ReadonlyArray<{ x: number, y: number, side?: number, width?: number, height?: number }>} frames
187
+ * @param {number} [meetTolerance=2] Coordinates within this distance snap into one grid line.
188
+ * @returns {number[]} Flat list of outer boundary segments `[x0, y0, x1, y1, ...]`.
189
+ */
190
+ export function rectUnionOutline(frames, meetTolerance = 2) {
191
+ const snap = values => {
192
+ const out = [];
193
+ for (const v of [...values].sort((a, b) => a - b)) {
194
+ if (!out.length || v - out[out.length - 1] > meetTolerance) out.push(v);
195
+ }
196
+ return out;
197
+ };
198
+ const widthOf = f => f.width ?? f.side;
199
+ const heightOf = f => f.height ?? f.side;
200
+ const xs = snap(frames.flatMap(f => [f.x, f.x + widthOf(f)]));
201
+ const ys = snap(frames.flatMap(f => [f.y, f.y + heightOf(f)]));
202
+ const inside = (x, y) =>
203
+ frames.some(
204
+ f =>
205
+ x > f.x - meetTolerance && x < f.x + widthOf(f) + meetTolerance && y > f.y - meetTolerance && y < f.y + heightOf(f) + meetTolerance,
206
+ );
207
+ const covered = (i, j) =>
208
+ i >= 0 && j >= 0 && i < xs.length - 1 && j < ys.length - 1 && inside((xs[i] + xs[i + 1]) / 2, (ys[j] + ys[j + 1]) / 2);
209
+ const segments = [];
210
+ for (let i = 0; i < xs.length; i++) {
211
+ for (let j = 0; j < ys.length - 1; j++) {
212
+ if (covered(i - 1, j) === covered(i, j)) continue;
213
+ let k = j;
214
+ while (k + 1 < ys.length - 1 && covered(i - 1, k + 1) !== covered(i, k + 1)) k++;
215
+ segments.push(xs[i], ys[j], xs[i], ys[k + 1]);
216
+ j = k;
217
+ }
218
+ }
219
+ for (let j = 0; j < ys.length; j++) {
220
+ for (let i = 0; i < xs.length - 1; i++) {
221
+ if (covered(i, j - 1) === covered(i, j)) continue;
222
+ let k = i;
223
+ while (k + 1 < xs.length - 1 && covered(k + 1, j - 1) !== covered(k + 1, j)) k++;
224
+ segments.push(xs[i], ys[j], xs[k + 1], ys[j]);
225
+ i = k;
226
+ }
227
+ }
228
+ return segments;
229
+ }