@spellkave/world-map 0.0.0-bootstrap → 0.0.0-stage

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.
package/src/svg/model.ts DELETED
@@ -1,459 +0,0 @@
1
- import {
2
- composeChildLocalToParentFrame,
3
- isEphemeralInstanceGraph,
4
- localBoundsCenter,
5
- metresPerParentLocalUnit,
6
- } from "./compose.ts";
7
- import { cellRes10ToHex } from "./h3-layout.ts";
8
- import type {
9
- SpatialGraphEdge,
10
- SpatialGraphModel,
11
- SpatialGraphNode,
12
- SpatialGraphNodeExtent,
13
- SpatialGraphToolRows,
14
- SpatialSliceMode,
15
- SpatialViewOptions,
16
- } from "./types.ts";
17
-
18
- function stringValue(row: Record<string, unknown>, key: string): string | null {
19
- const value = row[key];
20
- return typeof value === "string" ? value : null;
21
- }
22
-
23
- function numberValue(row: Record<string, unknown>, key: string): number | null {
24
- const value = row[key];
25
- return typeof value === "number" && Number.isFinite(value) ? value : null;
26
- }
27
-
28
- function booleanValue(row: Record<string, unknown>, key: string): boolean {
29
- return row[key] === true;
30
- }
31
-
32
- function titleFromId(id: string): string {
33
- return (id.split("/").at(-1) ?? id)
34
- .replaceAll("_", " ")
35
- .replace(/\b\w/g, (letter) => letter.toUpperCase());
36
- }
37
-
38
- function roundFloor(elevation: number): number {
39
- // Snap near-integers so 0.0 and -0.0 and 0.01 band as one floor key.
40
- return Math.round(elevation * 1000) / 1000;
41
- }
42
-
43
- /**
44
- * Auto-pick slice when the caller omits `slice`.
45
- * Indoor/tactical multi-floor → elevation_band; unpositioned → topology_only; else metric.
46
- */
47
- export function pickDefaultSlice(
48
- nodes: readonly SpatialGraphNode[],
49
- options: SpatialViewOptions,
50
- ): SpatialSliceMode {
51
- if (options.slice !== undefined) return options.slice;
52
- const graphScoped = options.graphId !== undefined && options.graphId.trim().length > 0;
53
- // Outdoor world compose: same H3 plane methodology as web when cells exist.
54
- if (!graphScoped && options.preferH3World !== false) {
55
- const withCell = nodes.filter((n) => n.cellRes10Hex).length;
56
- if (withCell >= 2 && withCell / Math.max(nodes.length, 1) >= 0.5) return "h3_world";
57
- }
58
- const positioned = nodes.filter((n) => Number.isFinite(n.x) && Number.isFinite(n.y));
59
- if (positioned.length === 0 && nodes.length > 0) return "topology_only";
60
- const floors = new Set(positioned.map((n) => roundFloor(n.elevation)));
61
- const indoorish = positioned.some(
62
- (n) => n.substrateId === "indoor" || n.substrateId === "tactical",
63
- );
64
- if (indoorish && floors.size > 1) return "elevation_band";
65
- return "metric";
66
- }
67
-
68
- /**
69
- * Build a spatial-graph model from tool-result-shaped row arrays
70
- * (`spellkave_query` list rows or equivalent manifest row objects).
71
- */
72
- export function buildSpatialGraphModel(
73
- rows: SpatialGraphToolRows,
74
- options: SpatialViewOptions = {},
75
- ): SpatialGraphModel {
76
- const graphRows = rows.place_graphs ?? [];
77
- const allNodes = rows.place_nodes ?? [];
78
- const selectedGraph = options.graphId?.trim();
79
- const graphScoped = selectedGraph !== undefined && selectedGraph.length > 0;
80
-
81
- const graphMetaById = new Map<
82
- string,
83
- {
84
- metresPerUnit: number;
85
- substrateId: string | null;
86
- displayName: string | null;
87
- parentGraphId: string;
88
- originCellRes10Hex: string | null;
89
- bearing: number;
90
- anchorNodeId: string | null;
91
- isEphemeralInstance: boolean;
92
- }
93
- >();
94
- for (const row of graphRows) {
95
- const id = stringValue(row, "place_graph_id");
96
- if (id === null) continue;
97
- const metresPerUnit = numberValue(row, "metres_per_unit");
98
- const bearing = numberValue(row, "bearing");
99
- graphMetaById.set(id, {
100
- metresPerUnit: metresPerUnit !== null && metresPerUnit > 0 ? metresPerUnit : 1,
101
- substrateId: stringValue(row, "substrate_id"),
102
- displayName: stringValue(row, "display_name"),
103
- parentGraphId: stringValue(row, "parent_graph_id") ?? "",
104
- originCellRes10Hex: cellRes10ToHex(row.origin_cell_res10),
105
- bearing: bearing ?? 0,
106
- anchorNodeId: stringValue(row, "anchor_node_id"),
107
- isEphemeralInstance: isEphemeralInstanceGraph(row, id),
108
- });
109
- }
110
-
111
- // sk-pej D-2: compose an ephemeral session-grid graph over its parent's
112
- // own topology by default (operator decision 2026-08-13 — "one picture,
113
- // no mode switch"). Gated on is_ephemeral_instance (NOT merely a
114
- // non-empty parent_graph_id) so ordinary authored nesting — elven-mini's
115
- // tomb/inn under hamlet, is_ephemeral_instance=false — never composes;
116
- // see compose.ts's isEphemeralInstanceGraph doc for why that gate is
117
- // load-bearing (committed elevation_band renders would otherwise move).
118
- const composeParentOpt = options.composeParent !== false;
119
- const selectedMeta = graphScoped ? graphMetaById.get(selectedGraph!) : undefined;
120
- const composeParentGraphId =
121
- composeParentOpt && selectedMeta?.isEphemeralInstance === true && selectedMeta.parentGraphId
122
- ? selectedMeta.parentGraphId
123
- : "";
124
- const composeParentGraph = composeParentGraphId !== "" && graphMetaById.has(composeParentGraphId);
125
- const includedGraphIds = graphScoped
126
- ? new Set(composeParentGraph ? [selectedGraph!, composeParentGraphId] : [selectedGraph!])
127
- : null;
128
-
129
- // Collect candidates (respect graph filter + outdoor world-compose rule).
130
- type Raw = {
131
- id: string;
132
- label: string;
133
- graphId: string;
134
- x: number | null;
135
- y: number | null;
136
- posPresent: boolean;
137
- elevation: number;
138
- elevationPresent: boolean;
139
- substrateId: string | null;
140
- cellRes10Hex: string | null;
141
- extent: SpatialGraphNodeExtent | null;
142
- /** Set only for composed tactical-grid cells; see SpatialGraphNode. */
143
- unlabeled?: boolean;
144
- };
145
- /** Planar geometry (graph-local units) of a node's own authored extent, or
146
- * null when none is authored / the shape carries no supported geometry. Metre →
147
- * unit conversion uses the node graph's backdrop grid distance when present,
148
- * because positioned backdrop coordinates are image cells; otherwise it
149
- * falls back to the graph's metres_per_unit.
150
- * Bundle defaults are deliberately not resolved here (no mod_bundle rows
151
- * in the tool row set) — an unauthored node keeps the renderer's 1-unit
152
- * fallback footprint. */
153
- const explicitExtent = (
154
- row: Record<string, unknown>,
155
- graphId: string,
156
- ): SpatialGraphNodeExtent | null => {
157
- const shapeId = stringValue(row, "extent_shape_id");
158
- if (shapeId === null || shapeId.length === 0) return null;
159
- let params: Record<string, unknown>;
160
- try {
161
- params = JSON.parse(stringValue(row, "extent_params_json") ?? "");
162
- } catch {
163
- return null;
164
- }
165
- const mapLayer = (rows.map_layers ?? []).find(
166
- (candidate) => stringValue(candidate, "place_graph_id") === graphId,
167
- );
168
- const metresPerUnit = metresPerParentLocalUnit(
169
- mapLayer,
170
- graphMetaById.get(graphId)?.metresPerUnit ?? 1,
171
- );
172
- const num = (key: string): number | null =>
173
- typeof params[key] === "number" && (params[key] as number) > 0
174
- ? (params[key] as number)
175
- : null;
176
- // Keep planar axes separate. sk-6rm may widen the existing shape params
177
- // rather than add ids; accepting either form here prevents this renderer
178
- // from baking in a scalar-only model.
179
- const halfAxes: [number | null, number | null] | null =
180
- shapeId === "core/area/sphere"
181
- ? [num("radius_x_m") ?? num("radius_m"), num("radius_y_m") ?? num("radius_m")]
182
- : shapeId === "core/area/cube"
183
- ? [num("extent_x_m") ?? num("extent_m"), num("extent_y_m") ?? num("extent_m")]
184
- : null;
185
- if (halfAxes === null || halfAxes[0] === null || halfAxes[1] === null) return null;
186
- const halfDepthMetres =
187
- shapeId === "core/area/sphere"
188
- ? (num("radius_z_m") ?? num("radius_m"))
189
- : (num("extent_z_m") ?? num("extent_m"));
190
- if (halfDepthMetres === null) return null;
191
- return {
192
- shapeId,
193
- params,
194
- widthUnits: (halfAxes[0] * 2) / metresPerUnit,
195
- heightUnits: (halfAxes[1] * 2) / metresPerUnit,
196
- depthMetres: halfDepthMetres * 2,
197
- };
198
- };
199
- const raws: Raw[] = [];
200
- for (const row of allNodes) {
201
- const id = stringValue(row, "node_id");
202
- const graphId = stringValue(row, "place_graph_id");
203
- if (id === null || graphId === null) continue;
204
- if (graphScoped) {
205
- if (!includedGraphIds!.has(graphId)) continue;
206
- } else {
207
- const substrate = stringValue(row, "substrate_id");
208
- // Unfiltered world compose: outdoor only (legacy).
209
- if (substrate !== "outdoor") continue;
210
- }
211
- const elevN = numberValue(row, "pose_elevation");
212
- const elevPresent = booleanValue(row, "pose_elevation_present");
213
- raws.push({
214
- id,
215
- label: stringValue(row, "display_name") ?? titleFromId(id),
216
- graphId,
217
- x: numberValue(row, "pos_x"),
218
- y: numberValue(row, "pos_y"),
219
- posPresent: booleanValue(row, "pos_present"),
220
- elevation: elevPresent && elevN !== null ? elevN : (elevN ?? 0),
221
- elevationPresent: elevPresent || elevN !== null,
222
- substrateId: stringValue(row, "substrate_id"),
223
- cellRes10Hex: cellRes10ToHex(row.cell_res10),
224
- extent: explicitExtent(row, graphId),
225
- });
226
- }
227
-
228
- // sk-pej D-2: fold the child (grid) graph's raw local coordinates into
229
- // the PARENT's own local frame, in place, before slicing/layout ever
230
- // see them — downstream (pickDefaultSlice probe, asNodes, layout.ts's
231
- // bounds-normalising offset) then treats the composed set as one shared
232
- // coordinate space, so parent nodes and the grid move together as a
233
- // rigid body (and, via layout.graphs including the parent's own graph
234
- // id, its authored [[map_layers]] backdrop lines up too — render-svg.ts
235
- // matches backdrops by graph id already present in the laid-out set).
236
- if (composeParentGraph) {
237
- const parentMeta = graphMetaById.get(composeParentGraphId)!;
238
- const anchorNodeId = selectedMeta!.anchorNodeId;
239
- const anchorRaw =
240
- anchorNodeId !== null && anchorNodeId.length > 0
241
- ? raws.find((r) => r.graphId === composeParentGraphId && r.id === anchorNodeId)
242
- : undefined;
243
- if (anchorRaw !== undefined && anchorRaw.x !== null && anchorRaw.y !== null) {
244
- const childPositioned = raws.filter(
245
- (r) => r.graphId === selectedGraph && r.x !== null && r.y !== null,
246
- );
247
- const center = localBoundsCenter(
248
- childPositioned.map((r) => ({ x: r.x as number, y: r.y as number })),
249
- );
250
- // The ONE metres -> parent-graph-local-unit conversion (compose.ts's
251
- // metresPerParentLocalUnit doc has the full grounding): prefer the
252
- // parent's OWN [[map_layers]] row's grid_distance_m (already metres
253
- // since sk-yze) over its place_graph_definition.metres_per_unit,
254
- // which is frequently an unmaintained default disconnected from the
255
- // backdrop's real cell size.
256
- const parentMapLayerRow = (rows.map_layers ?? []).find(
257
- (row) => stringValue(row, "place_graph_id") === composeParentGraphId,
258
- );
259
- const composeParams = {
260
- childMetresPerUnit: selectedMeta!.metresPerUnit,
261
- parentMetresPerUnit: metresPerParentLocalUnit(parentMapLayerRow, parentMeta.metresPerUnit),
262
- bearingDeg: selectedMeta!.bearing,
263
- anchor: { x: anchorRaw.x, y: anchorRaw.y },
264
- center,
265
- };
266
- for (const r of childPositioned) {
267
- const p = composeChildLocalToParentFrame(r.x as number, r.y as number, composeParams);
268
- r.x = p.x;
269
- r.y = p.y;
270
- // generate_tactical_grid hardcodes pose_elevation=0 regardless of
271
- // the anchor's real floor (tactical_grid.rs) — composing onto the
272
- // wrong elevation band would silently drop the grid from the
273
- // default elevation_band slice (z=0±0.5). Adopt the anchor's own
274
- // elevation instead so the composed picture stays on one floor.
275
- r.elevation = anchorRaw.elevation;
276
- r.elevationPresent = anchorRaw.elevationPresent;
277
- // 100 "Cell 4,7" labels smear into an unreadable band across the
278
- // backdrop art and carry no information a reader wants — the mark
279
- // IS the cell. Suppressed only for COMPOSED cells: a caller who
280
- // asks for the bare grid (compose_parent=false) has no backdrop to
281
- // collide with and keeps its labels.
282
- r.unlabeled = true;
283
- }
284
- }
285
- }
286
-
287
- const asNodes = (list: Raw[], forceTopology: boolean): SpatialGraphNode[] =>
288
- list.flatMap((r) => {
289
- if (forceTopology) {
290
- return [
291
- {
292
- id: r.id,
293
- label: r.label,
294
- unlabeled: r.unlabeled,
295
- graphId: r.graphId,
296
- x: 0,
297
- y: 0,
298
- elevation: r.elevation,
299
- elevationPresent: r.elevationPresent,
300
- substrateId: r.substrateId,
301
- cellRes10Hex: r.cellRes10Hex,
302
- extent: r.extent ?? undefined,
303
- extentUnits: r.extent ? Math.max(r.extent.widthUnits, r.extent.heightUnits) : undefined,
304
- },
305
- ];
306
- }
307
- // H3 world can place cells without graph-local pos; metric still needs pos.
308
- const allowCellOnly = options.slice === "h3_world" || !graphScoped;
309
- if ((!r.posPresent || r.x === null || r.y === null) && !(allowCellOnly && r.cellRes10Hex)) {
310
- return [];
311
- }
312
- return [
313
- {
314
- id: r.id,
315
- label: r.label,
316
- unlabeled: r.unlabeled,
317
- graphId: r.graphId,
318
- x: r.x ?? 0,
319
- y: r.y ?? 0,
320
- elevation: r.elevation,
321
- elevationPresent: r.elevationPresent,
322
- substrateId: r.substrateId,
323
- cellRes10Hex: r.cellRes10Hex,
324
- extent: r.extent ?? undefined,
325
- extentUnits: r.extent ? Math.max(r.extent.widthUnits, r.extent.heightUnits) : undefined,
326
- },
327
- ];
328
- });
329
-
330
- // Pre-slice positioned nodes for floor discovery / auto mode.
331
- const positionedProbe = asNodes(raws, false);
332
- const sliceMode = pickDefaultSlice(
333
- positionedProbe.length > 0
334
- ? positionedProbe
335
- : asNodes(raws, true).map((n, i) => ({ ...n, x: i, y: 0 })),
336
- options,
337
- );
338
-
339
- let working = asNodes(raws, sliceMode === "topology_only");
340
- const allFloors = [...new Set(working.map((n) => roundFloor(n.elevation)))].sort((a, b) => a - b);
341
-
342
- let sliceLabel: string = sliceMode;
343
- if (sliceMode === "elevation_band") {
344
- const z = options.z ?? 0;
345
- const tol = options.zTolerance ?? 0.5;
346
- working = working.filter((n) => Math.abs(n.elevation - z) <= tol);
347
- sliceLabel = `elevation_band z=${z}±${tol}`;
348
- } else if (sliceMode === "all_floors_offset") {
349
- sliceLabel = `all_floors_offset floors=[${allFloors.join(",")}]`;
350
- } else if (sliceMode === "topology_only") {
351
- sliceLabel = "topology_only";
352
- } else if (sliceMode === "h3_world") {
353
- sliceLabel = "h3_world";
354
- } else {
355
- sliceLabel = "metric";
356
- }
357
-
358
- const nodes = working;
359
- const attachmentAnchorById = new Map(
360
- (rows.notable_anchor_nodes ?? []).flatMap((row) => {
361
- const id = stringValue(row, "node_id");
362
- return id === null ? [] : [[id, row] as const];
363
- }),
364
- );
365
- const notableScopes = (rows.visible_spatial_niche_attachments ?? []).flatMap((attachment) => {
366
- const anchorNodeId = stringValue(attachment, "place_node_id");
367
- const nicheId = stringValue(attachment, "niche_id");
368
- if (anchorNodeId === null || anchorNodeId === "" || nicheId === null) return [];
369
- const anchor = attachmentAnchorById.get(anchorNodeId);
370
- if (anchor === undefined) return [];
371
- const graphId = stringValue(anchor, "place_graph_id");
372
- const x = numberValue(anchor, "pos_x");
373
- const y = numberValue(anchor, "pos_y");
374
- if (graphId === null || x === null || y === null || !booleanValue(anchor, "pos_present"))
375
- return [];
376
- if (includedGraphIds !== null && !includedGraphIds.has(graphId)) return [];
377
- const extent = explicitExtent(anchor, graphId);
378
- return extent === null ? [] : [{ anchorNodeId, nicheId, x, y, extent }];
379
- });
380
- const nodeIds = new Set(nodes.map((node) => node.id));
381
- const edges: SpatialGraphEdge[] = (rows.place_edges ?? []).flatMap((row) => {
382
- const from = stringValue(row, "from_node_id");
383
- const to = stringValue(row, "to_node_id");
384
- if (from === null || to === null) return [];
385
- // Single-graph: both ends must be present.
386
- if (graphScoped) {
387
- if (!nodeIds.has(from) || !nodeIds.has(to)) return [];
388
- } else {
389
- // Outdoor world: keep edges touching any outdoor node (indoor portal stubs).
390
- if (!nodeIds.has(from) && !nodeIds.has(to)) return [];
391
- }
392
- return [{ from, to, graphId: stringValue(row, "place_graph_id") ?? "" }];
393
- });
394
-
395
- const actorByPlace = new Map<string, number>();
396
- for (const row of rows.actor_spatial_locations ?? []) {
397
- const place = stringValue(row, "place_node_id");
398
- if (place === null || !nodeIds.has(place)) continue;
399
- actorByPlace.set(place, (actorByPlace.get(place) ?? 0) + 1);
400
- }
401
-
402
- const graphIds = [...new Set(nodes.map((n) => n.graphId))];
403
- const graphs = graphIds.map((graphId) => {
404
- const meta = graphMetaById.get(graphId);
405
- return {
406
- graphId,
407
- metresPerUnit: meta?.metresPerUnit ?? 1,
408
- substrateId:
409
- meta?.substrateId ?? nodes.find((n) => n.graphId === graphId)?.substrateId ?? null,
410
- displayName: meta?.displayName ?? null,
411
- parentGraphId: meta?.parentGraphId ?? "",
412
- originCellRes10Hex: meta?.originCellRes10Hex ?? null,
413
- bearing: meta?.bearing ?? 0,
414
- anchorNodeId: meta?.anchorNodeId ?? null,
415
- };
416
- });
417
- // Include outdoor root meta even if filter dropped its nodes (need origin for h3_world).
418
- for (const [graphId, meta] of graphMetaById) {
419
- if (graphs.some((g) => g.graphId === graphId)) continue;
420
- if (meta.substrateId !== "outdoor" || !meta.originCellRes10Hex) continue;
421
- graphs.push({
422
- graphId,
423
- metresPerUnit: meta.metresPerUnit,
424
- substrateId: meta.substrateId,
425
- displayName: meta.displayName,
426
- parentGraphId: meta.parentGraphId,
427
- originCellRes10Hex: meta.originCellRes10Hex,
428
- bearing: meta.bearing,
429
- anchorNodeId: meta.anchorNodeId,
430
- });
431
- }
432
-
433
- const anchor =
434
- (selectedGraph !== undefined
435
- ? stringValue(
436
- graphRows.find((r) => stringValue(r, "place_graph_id") === selectedGraph) ?? {},
437
- "anchor_node_id",
438
- )
439
- : null) ??
440
- stringValue(graphRows[0] ?? {}, "anchor_node_id") ??
441
- nodes[0]?.id ??
442
- null;
443
-
444
- return {
445
- nodes,
446
- edges,
447
- actorClusters: [...actorByPlace.entries()].map(([placeNodeId, count]) => ({
448
- placeNodeId,
449
- count,
450
- })),
451
- graphs,
452
- root: anchor !== null && nodeIds.has(anchor) ? anchor : (nodes[0]?.id ?? null),
453
- reachable: [...nodeIds],
454
- unreachable: [],
455
- floors: allFloors,
456
- sliceLabel,
457
- notableScopes,
458
- };
459
- }