@nika-js/onlymap 0.13.1 → 0.13.2

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +2 -2
  3. package/bin/dem-tiles.mjs +270 -0
  4. package/bin/onlymapjs.mjs +138 -34
  5. package/dist/{basemap-zG1-omic.js → basemap-CdSCIWCl.js} +2 -2
  6. package/dist/{build-Bbi4SleC.js → build-CUx4yR_O.js} +10 -10
  7. package/dist/camera-altitude.d.ts +29 -0
  8. package/dist/{client-CIH6ToMI.js → client-DVkMuuPp.js} +2 -2
  9. package/dist/color.d.ts +15 -0
  10. package/dist/credit-chrome.d.ts +11 -0
  11. package/dist/elements/om-map.d.ts +41 -1
  12. package/dist/geodesy.d.ts +2 -0
  13. package/dist/{geoparquet-CyWsYt9S.js → geoparquet-DuCEsCOu.js} +3 -3
  14. package/dist/{globe-view-Xelgj_KW.js → globe-view-BWNfn-Sx.js} +1 -1
  15. package/dist/ground-controller.d.ts +39 -0
  16. package/dist/{hillshade-Zbg50lm6.js → hillshade-DyfYxqNm.js} +61 -64
  17. package/dist/{hillshade-shader-DI2uLSNU.js → hillshade-shader-BWA0USDQ.js} +12 -11
  18. package/dist/hillshade-shader.d.ts +2 -2
  19. package/dist/hillshade.d.ts +0 -29
  20. package/dist/{index-CpFNIkOO.js → index-BfHaNHyY.js} +20687 -19351
  21. package/dist/{index-ClAPAqcm.js → index-CCj9Z5yt.js} +38 -38
  22. package/dist/{index-BL_YCKiW.js → index-Cc3huYsW.js} +62 -62
  23. package/dist/{index-BwtXeP_F.js → index-DRGcZmBm.js} +1 -1
  24. package/dist/{index-DnCmvLuC.js → index-DYrgHprN.js} +61 -61
  25. package/dist/{index-BbVnkgld.js → index-DabUE8w3.js} +38 -38
  26. package/dist/{index-JFuN4DCn.js → index-DfzI_j0D.js} +1 -1
  27. package/dist/{index-6eeSlSqN.js → index-DiDoH_BG.js} +3 -3
  28. package/dist/{index-BtRsa5oc.js → index-dUoVyYIW.js} +18 -18
  29. package/dist/index.d.ts +1 -1
  30. package/dist/{lerc-C3SKC6CU.js → lerc-CUV0h9Ci.js} +1 -1
  31. package/dist/onlymap.standalone.js +37857 -36438
  32. package/dist/onlymapjs.js +49 -49
  33. package/dist/plane-gpu/plane-basemap.d.ts +0 -14
  34. package/dist/{post-process-effect-C3P9VwC9.js → post-process-effect-DPrpqybM.js} +1 -1
  35. package/dist/programmatic.d.ts +3 -1
  36. package/dist/{raster-BgCnz9-Z.js → raster-CrRQNJE7.js} +4 -4
  37. package/dist/{raster-pipeline-CKdpKgFo.js → raster-pipeline-D9g8RAo4.js} +11 -11
  38. package/dist/runtime-core.d.ts +132 -0
  39. package/dist/sea-surface.d.ts +18 -0
  40. package/dist/terrain-derive.d.ts +39 -0
  41. package/dist/terrain-ground.d.ts +31 -0
  42. package/dist/terrain-heightfield.d.ts +17 -9
  43. package/dist/terrain-inspect-GowNVtMZ.js +96 -0
  44. package/dist/terrain-inspect.d.ts +34 -0
  45. package/dist/terrain-nodata.d.ts +50 -0
  46. package/dist/terrain-priority.d.ts +92 -0
  47. package/dist/terrain-sample.d.ts +6 -0
  48. package/dist/terrain-skirt.d.ts +6140 -0
  49. package/dist/terrain-texture-mask.d.ts +40 -0
  50. package/dist/terrain-tint.d.ts +61 -0
  51. package/dist/terrain.d.ts +132 -8
  52. package/dist/{text-on-path-BpVLX8Yt.js → text-on-path-BoFbm-tl.js} +1 -1
  53. package/dist/version.d.ts +1 -1
  54. package/dist/viewport-filter.d.ts +9 -0
  55. package/dist/volumetrics.d.ts +11 -0
  56. package/dist/{zarr-Cur_pzNa.js → zarr-C8CU8LXU.js} +2 -2
  57. package/docs/cartograph.md +2 -2
  58. package/llms.txt +1 -1
  59. package/onlymapjs.html-data.json +162 -2
  60. package/package.json +2 -1
  61. package/skills/onlymapjs/SKILL.md +5 -2
  62. package/skills/onlymapjs/references/syntax.md +3 -3
package/CHANGELOG.md CHANGED
@@ -8,6 +8,30 @@ Note: npm collapsed a few closely-spaced releases — the GPX/FlatGeobuf (0.5.4)
8
8
  and GeoParquet (0.5.5) work shipped to npm together as **0.5.6**, so npm's
9
9
  version list jumps 0.5.3 → 0.5.6. Each logical version is listed here regardless.
10
10
 
11
+ ## 0.13.2 — 2026-10-20
12
+
13
+ ### Added
14
+ - **Dive below sea level.** `camera-target="terrain"` makes the camera orbit the ground under the view centre, so zooming in descends into a canyon or onto a seabed. `camera-clearance="15"` keeps the eye that many metres above the ground, for gestures, flights and the zoom buttons alike.
15
+ - **`map.getCamera()`** reports the camera's `altitude`, the `targetElevation` under the view centre and the `clearance` above the ground, in true metres, for a depth or altitude gauge. `om-view-changed` carries the same three values.
16
+ - **A keyless bathymetry preset:** `terrain="seascape"` draws the seafloor worldwide (GEBCO), with regional surveys up to zoom 14.
17
+ - **Several DEMs on one map.** Rank `<om-terrain>` children in `terrain="survey, context"`: the first-ranked source wins inside its `extent`, and the ground is shared cleanly between them, with no z-fighting and no need to push one dataset down to hide it.
18
+ - **Your own survey, with its gaps and datum.** `nodata="-32768"` turns a survey's empty cells into holes that show the next source, colour and height. `vertical-offset` corrects a datum difference between sources. On a single DEM they are `terrain-nodata` and `terrain-vertical-offset`.
19
+ - **`npx onlymapjs inspect-terrain page.html`** (or `await map.inspectTerrain()`) reads your terrain tiles and tells you which `vertical-offset` and `nodata` to set.
20
+ - **`npx onlymapjs dem-tiles survey.tif --out tiles`** turns a GeoTIFF DEM into terrain tiles and prints the `<om-terrain>` line to paste. It needs the `geotiff` package installed.
21
+ - **Imagery sharper than the DEM:** `texture-max-zoom` keeps draping imagery at its own zoom over a coarser elevation grid.
22
+ - **Seeing that it is under water:** `terrain-tint="depth"` shades the seabed by depth, `terrain-tint="slope"` colours ground by steepness, and `sea-surface` draws a translucent plane at sea level. `terrain-texture-mask="land"` keeps imagery on the land with the seabed bare, and `"sea"` does the reverse.
23
+ - **Terrain presets credit their data** on the map, in `attributions()` and on cartograph sheets.
24
+ - **A new example, *Dive the seafloor*:** Monterey Canyon, a survey over a regional grid, rebuilt in markup with no workarounds.
25
+
26
+ ### Changed
27
+ - **`mapterhorn` no longer drapes satellite imagery.** Its imagery source now serves a watermark without a key.
28
+ - **`getViewState()` returns only the five camera fields** (longitude, latitude, zoom, pitch, bearing). Internal renderer values no longer leak into it, the React adapter or snapshots.
29
+
30
+ ### Fixed
31
+ - **Markers and 3D models over ground below sea level now stand on it.** They drew at sea level, because the terrain's height map could not hold a negative height.
32
+ - **No more thin cracks between terrain tiles** where neighbouring tiles load at different zooms.
33
+ - **Draped tiled layers no longer drop tiles over high ground.** They were culled as if the ground were at sea level.
34
+
11
35
  ## 0.13.1 — 2026-10-16
12
36
 
13
37
  ### Fixed
package/README.md CHANGED
@@ -307,7 +307,7 @@ Plus `OmMap.snapshotIR(html)` to lock down what a manifest *means* in a snapshot
307
307
 
308
308
  ## 3D
309
309
 
310
- `ScenegraphLayer` instances glTF/GLB models at coordinates (no three.js, no loader wiring) — `color`/`get-color` tint the model (a shader multiply over its own baked texture/material, so per-row `get-color="$status_color"` recolors a fleet by data without swapping model files), `Tile3DLayer` consumes OGC 3D Tiles, `GeoJsonLayer` extrudes polygons (`extruded get-elevation="$height"`), and the camera tilts via `pitch`/`bearing` attributes. Terrain is one attribute: `<om-map terrain="terrarium">` raises a real DEM surface (keyless AWS tiles; `mapterhorn` keyless too, paired with a CARTO Positron drape by default; `maptiler-terrain` keyed; or a bring-your-own `{z}/{x}/{y}` DEM URL + `terrain-decoder`), geographic layers drape onto it automatically (per-layer `terrain="drape|offset|off"` overrides; 3D models sit ON the surface), `terrain-exaggeration` scales the relief, and `terrain-texture` drapes imagery. Terrain replaces an active basemap while on (flat canvas vs raised surface) and restores it when off. **BIM models require explicit terrain**: a georeferenced model's absolute elevation only means anything against a DEM surface, and the library never writes attributes for you — a model that resolves real elevation on a map without a `terrain` attribute raises an error through the validation channel at load time (any authored value satisfies it, including an explicit `terrain="off"` for flat-ground siting). When terrain IS active, `BIMLayer` automatically re-plants itself at its file's own `IfcMapConversion.OrthogonalHeight` (its real absolute elevation) instead of the local Z≈0 a flat basemap expects — no attribute to author, it just lands on the surface. Scene lighting is declarative: `<om-map lighting="daylight">` (presets `daylight`/`studio`/`flat`/`custom`, tuned via `lighting-ambient`, `lighting-sun`, `lighting-sun-azimuth`/`-elevation`, or `lighting-sun-date` for a solar-position sun) — attribute-backed, so lighting changes are undoable and story-steppable via the `set-lighting` action. `<om-widget type="lighting">` gives users native preset radios + tuning sliders over the same attributes. Converting IFC/CAD upstream: [docs/3d-assets.md](docs/3d-assets.md).
310
+ `ScenegraphLayer` instances glTF/GLB models at coordinates (no three.js, no loader wiring) — `color`/`get-color` tint the model (a shader multiply over its own baked texture/material, so per-row `get-color="$status_color"` recolors a fleet by data without swapping model files), `Tile3DLayer` consumes OGC 3D Tiles, `GeoJsonLayer` extrudes polygons (`extruded get-elevation="$height"`), and the camera tilts via `pitch`/`bearing` attributes. Terrain is one attribute: `<om-map terrain="terrarium">` raises a real DEM surface (keyless AWS tiles, seabed included — but only to zoom 10: above it the ocean decodes as sea level, so `terrain-max-zoom="10"` keeps a seafloor when you zoom closer — and `camera-target="terrain"` makes the camera orbit the ground under the view centre, so zooming in descends to it, below sea level over a seabed, with `camera-clearance="15"` holding the eye that many metres off the ground; several DEMs make one surface with `<om-terrain>` children ranked in `terrain="survey, context"` — the first-ranked source alone draws inside its `extent` (a 10 m survey over a regional grid, no z-fighting, tiles untouched; `nodata="-32768"` on a source makes its gaps holes that show the next source, height and all, and `vertical-offset` corrects a datum difference between datasets; `map.inspectTerrain()` — or `npx onlymapjs inspect-terrain page.html` — reads the tiles and reports a step where sources meet, with the `vertical-offset` that closes a steady one, and heights no ground has, with the `nodata` to set; `npx onlymapjs dem-tiles survey.tif --out tiles` tiles your own GeoTIFF DEM — any CRS the library knows, no GDAL — and prints the `<om-terrain>` line to paste; `texture-max-zoom="15"` drapes imagery at its own zoom over a coarser DEM, the deeper tiles' heights rebuilt from the DEM); `terrain-tint="slope"` colours ground by its true slope (sediment on the flat, rock on the walls, `terrain-tint-flat`/`-steep` to choose), `terrain-tint="depth"` shades the seabed as if seen through water (`terrain-tint-shallow` at the coast fading to `terrain-tint-deep` by `terrain-tint-max-depth` metres; land untouched; `"slope depth"` for both), and `sea-surface="rgba(…)"` lays a translucent plane at sea level that the seabed shows through, `terrain-texture-mask="land"` keeps a `terrain-texture` on the land only — satellite imagery on the coast, the seafloor bare under it (`"sea"` is the reverse); each terrain preset credits its data on the map and on printed sheets, like a basemap (a DEM URL of your own is yours to credit); `mapterhorn` keyless too (land only — its sea is flat); `seascape` keyless BATHYMETRY from Open Waters (GEBCO worldwide, regional surveys to zoom 14; land flat; not for navigation); `maptiler-terrain` keyed; or a bring-your-own `{z}/{x}/{y}` DEM URL + `terrain-decoder`), geographic layers drape onto it automatically (per-layer `terrain="drape|offset|off"` overrides; 3D models sit ON the surface), `terrain-exaggeration` scales the relief, and `terrain-texture` drapes imagery. Terrain replaces an active basemap while on (flat canvas vs raised surface) and restores it when off. **BIM models require explicit terrain**: a georeferenced model's absolute elevation only means anything against a DEM surface, and the library never writes attributes for you — a model that resolves real elevation on a map without a `terrain` attribute raises an error through the validation channel at load time (any authored value satisfies it, including an explicit `terrain="off"` for flat-ground siting). When terrain IS active, `BIMLayer` automatically re-plants itself at its file's own `IfcMapConversion.OrthogonalHeight` (its real absolute elevation) instead of the local Z≈0 a flat basemap expects — no attribute to author, it just lands on the surface. Scene lighting is declarative: `<om-map lighting="daylight">` (presets `daylight`/`studio`/`flat`/`custom`, tuned via `lighting-ambient`, `lighting-sun`, `lighting-sun-azimuth`/`-elevation`, or `lighting-sun-date` for a solar-position sun) — attribute-backed, so lighting changes are undoable and story-steppable via the `set-lighting` action. `<om-widget type="lighting">` gives users native preset radios + tuning sliders over the same attributes. Converting IFC/CAD upstream: [docs/3d-assets.md](docs/3d-assets.md).
311
311
 
312
312
  **Clip box.** `<om-map clip-box-min="[lng,lat,elev]" clip-box-max="[lng,lat,elev]">` cuts a real axis-aligned 3D box through the whole scene — every layer is clipped by default (`clip="off"` opts a layer out), `clip-box-invert` shows outside the box instead of inside, and `clip-box-highlight` dims clipped-out geometry instead of discarding it (a non-destructive preview). Works on any layer type, including georeferenced `Tile3DLayer`/`BIMLayer` content, so a dense BIM scene can be cut open to see what's inside. Attribute-backed (undoable, story-steppable) via the `set-clip-box` action; `<om-widget type="clip-box">` gives users the same six numeric fields plus invert/highlight toggles. v1 is axis-aligned only — rotated boxes are a documented follow-up.
313
313
 
@@ -410,7 +410,7 @@ Two things it gets right that hand-rolled hillshades usually don't. **Tile edges
410
410
 
411
411
  - **`OmMap.*`** — `validate`, `snapshotIR`, `snapshotDescriptorIR`, `resolveImageOverlay`, `registerLayer`, `registerWidget`, `registerAction`, `registerSource`, `registerFormat`, `registerBasemap`, `configureBasemap`, `configureData`, `configureTelemetry`, `configureLicense`, `getLayerSchema`
412
412
  - **`@nika-js/onlymap/deck`** — the bundled deck.gl classes (`CompositeLayer`, `TileLayer`, …) for building custom layer types: shims must extend the same class hierarchy the core renders with, not a second installed deck.gl copy. Recipe: [docs/custom-layers.md](docs/custom-layers.md)
413
- - **On a `<om-map>` element** — `ready` (promise), `flyTo(coords, zoom?)`, `setLayerVisible(id, bool)`, `getLayers()`, `emit(action, payload)`, `snapshot(opts?)` (canvas-only PNG of basemap + layers at device pixels — DOM widgets/overlays and provider attribution are NOT captured, so exports must render credits themselves; `{as: "blob"}` for files, default dataURL); `attributions()` (the basemap's providers as plain text — what an export must credit; the bubbling `om-attributions-changed` event fires when a style loads); the `om-view-changed` event fires once the camera settles (debounced; `detail` = `{longitude, latitude, zoom, pitch, bearing, origin}`, where `origin` is `"user"` for gesture-driven bursts vs `"programmatic"` for API/story moves — the echo-suppression signal for state sync) — the camera-persistence hook; the `om-map-point` event (`detail = {coordinate: [lng,lat]|null, kind: "click"|"hover"}`) fires on every click/hover with the map coordinate, including empty-map clicks picks discard — the hook for custom capture tools the built-in draw widget doesn't cover; the `om-tileset-load` event (`detail = {layerId, tileset}`) surfaces a `Tile3DLayer`'s live deck `Tileset3D` for tools that need the real tileset (e.g. region export), not the IR; `pickAt([x, y])` / `pickRect({x, y, width, height})` ask what is under a pixel or inside a screen rectangle and `unproject([x, y])` / `project([lng, lat])` convert between pixels and coordinates — queries that leave the selection, `om-map-point` and behaviors alone, with a `pickMode` property (`"authored"` | `"all"`) that lets a picker tool reach layers the author did not make `pickable` without editing the document; a `diagnostics` property that makes the map report its validation problems as `om-validation-error` events (and `getDiagnostics()` for the latest) without a `validate` attribute or panel, `data-layer` on legend and layer-switcher rows, and an overlay's `templateSource` (its template with `{{fields}}` intact) — what a host's picker reads without editing the document (0.11.7+); `document.querySelector("om-map")` is fully typed
413
+ - **On a `<om-map>` element** — `ready` (promise), `flyTo(coords, zoom?)`, `getCamera()` (the camera plus where its eye is: `altitude` against sea level, `targetElevation` — the ground under the view centre — and `clearance` above the ground beneath the eye, true metres, cheap enough for every animation frame; also on `MapController`, and in the `om-view-changed` detail, which reads only DEM tiles already held — null there until a `getCamera()` call has fetched them), `setLayerVisible(id, bool)`, `getLayers()`, `emit(action, payload)`, `snapshot(opts?)` (canvas-only PNG of basemap + layers at device pixels — DOM widgets/overlays and provider attribution are NOT captured, so exports must render credits themselves; `{as: "blob"}` for files, default dataURL); `attributions()` (the basemap's providers as plain text — what an export must credit; the bubbling `om-attributions-changed` event fires when a style loads); the `om-view-changed` event fires once the camera settles (debounced; `detail` = `{longitude, latitude, zoom, pitch, bearing, origin}`, where `origin` is `"user"` for gesture-driven bursts vs `"programmatic"` for API/story moves — the echo-suppression signal for state sync) — the camera-persistence hook; the `om-map-point` event (`detail = {coordinate: [lng,lat]|null, kind: "click"|"hover"}`) fires on every click/hover with the map coordinate, including empty-map clicks picks discard — the hook for custom capture tools the built-in draw widget doesn't cover; the `om-tileset-load` event (`detail = {layerId, tileset}`) surfaces a `Tile3DLayer`'s live deck `Tileset3D` for tools that need the real tileset (e.g. region export), not the IR; `pickAt([x, y])` / `pickRect({x, y, width, height})` ask what is under a pixel or inside a screen rectangle and `unproject([x, y])` / `project([lng, lat])` convert between pixels and coordinates — queries that leave the selection, `om-map-point` and behaviors alone, with a `pickMode` property (`"authored"` | `"all"`) that lets a picker tool reach layers the author did not make `pickable` without editing the document; a `diagnostics` property that makes the map report its validation problems as `om-validation-error` events (and `getDiagnostics()` for the latest) without a `validate` attribute or panel, `data-layer` on legend and layer-switcher rows, and an overlay's `templateSource` (its template with `{{fields}}` intact) — what a host's picker reads without editing the document (0.11.7+); `document.querySelector("om-map")` is fully typed
414
414
  - **`MapController`** — the framework-grade programmatic front-end (typed `LayerDescriptor`s → the same reconcile core, no DOM manifest): `setLayers`, `watch`, `emit`, camera methods, `injectPick`, `ready`, `snapshot`, `setEffects` (deck `Effect` instances, 1:1 — takes precedence over the document's `<om-effect>` chain while set; `null` hands the chain back), `suspend`/`resume`, an `onViewChange(view, origin)` option (the `om-view-changed` twin), plus `onMapPoint` / `onTilesetLoad` options (the `om-map-point` / `om-tileset-load` twins). Active descriptors own reference-counted fetch/poll/socket handles: layer removal, transport-option change, suspend, and destroy release them. Accessor props normally take functions; schema-declared accessors also accept restricted expression strings such as `getPosition: "[$lon, $lat]"`, which makes the descriptor JSON-safe for native/cross-process bridges. `snapshotDescriptorIR(descriptors)` resolves that lane without fetching URL data. The same `pickAt`/`pickRect`/`unproject`/`pickMode` the element has are on the controller. The React adapter rides the function form; vanilla/native hosts may use either
415
415
  - **`getStore(token)`** — the external-store contract: per-token `{subscribe, getSnapshot}` stores (`viewport`/`selection`/`layers`/`data:<id>`) with cached immutable plain-data snapshots and `origin` tagging — directly consumable by `useSyncExternalStore` (the React adapter's own hooks ride it), MobX autoruns, Redux listeners, Zustand mirrors. ~20-line integration-tested recipes for Redux Toolkit, MobX/mobx-keystone, Zustand, and Jotai: [docs/external-stores.md](docs/external-stores.md)
416
416
  - **Testing** — `mountForTest`, and imports are SSR-safe (importing in Node/jsdom never touches browser globals)
@@ -0,0 +1,270 @@
1
+ /**
2
+ * `onlymapjs dem-tiles <in.tif> --out <dir>` — a GeoTIFF DEM to Terrarium
3
+ * tiles an `<om-terrain>` reads (docs/design/underwater-terrain.md, Phase I,
4
+ * piece 4). No GDAL:
5
+ *
6
+ * - `geotiff` reads the raster window by window (an optional dependency,
7
+ * installed by the user like Playwright is for `record`).
8
+ * - The file's CRS (its EPSG code, or `--crs` / `--crs-def`) goes through
9
+ * the library's own `resolveProjection` — the bundled CRS table and proj4
10
+ * the map itself uses — so every output pixel's lng/lat is projected into
11
+ * the file and sampled bilinearly.
12
+ * - No-data (`--nodata`, else the file's GDAL_NODATA, and NaN) never mixes
13
+ * into a height: a pixel whose neighbours are all no-data is no-data, and
14
+ * it is written as the Terrarium sentinel −32768 — so `nodata="-32768"` on
15
+ * the source turns it into a hole.
16
+ * - Lower zooms are 2×2 averages of the zoom above, skipping no-data.
17
+ * - PNG through node:zlib; WebP only when `sharp` is installed.
18
+ *
19
+ * It prints the `<om-terrain>` line to paste: src, decoder, nodata, the
20
+ * data's extent and its zooms.
21
+ */
22
+ import { mkdirSync, writeFileSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { deflateSync } from "node:zlib";
25
+
26
+ export const NODATA_SENTINEL = -32768;
27
+ const TILE = 256;
28
+ const EARTH = 40_075_016.686;
29
+
30
+ /** Terrarium: height = (R·256 + G + B/256) − 32768; no-data (NaN) is the sentinel. */
31
+ export function encodeTerrarium(height) {
32
+ const rgb = [0, 0, 0];
33
+ writeTerrarium(rgb, 0, height);
34
+ return rgb;
35
+ }
36
+
37
+ /** encodeTerrarium into `out` at `at` — no array per pixel. */
38
+ export function writeTerrarium(out, at, height) {
39
+ const v = height === height ? Math.max(0, Math.min(65535.996, height + 32768)) : 0;
40
+ const r = Math.floor(v / 256);
41
+ const g = Math.floor(v - r * 256);
42
+ out[at] = r;
43
+ out[at + 1] = g;
44
+ out[at + 2] = Math.floor((v - r * 256 - g) * 256);
45
+ }
46
+
47
+ const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
48
+ let c = n;
49
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
50
+ return c >>> 0;
51
+ });
52
+ function crc32(buf) {
53
+ let c = 0xffffffff;
54
+ for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
55
+ return (c ^ 0xffffffff) >>> 0;
56
+ }
57
+ function chunk(type, data) {
58
+ const len = Buffer.alloc(4);
59
+ len.writeUInt32BE(data.length);
60
+ const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
61
+ const crc = Buffer.alloc(4);
62
+ crc.writeUInt32BE(crc32(body));
63
+ return Buffer.concat([len, body, crc]);
64
+ }
65
+ /**
66
+ * A square 8-bit RGB PNG from `rgb` (width × width × 3 bytes), filter-free —
67
+ * an encoder that re-quantised or colour-managed anything would corrupt the
68
+ * heights a DEM tile carries. Also the e2e fixtures' tile encoder.
69
+ */
70
+ export function rgbPng(rgb, width = TILE, level = 9) {
71
+ const row = width * 3;
72
+ const raw = Buffer.alloc(width * (row + 1));
73
+ for (let y = 0; y < width; y++) {
74
+ raw[y * (row + 1)] = 0; // filter type: none
75
+ raw.set(rgb.subarray(y * row, (y + 1) * row), y * (row + 1) + 1);
76
+ }
77
+ const ihdr = Buffer.alloc(13);
78
+ ihdr.writeUInt32BE(width, 0);
79
+ ihdr.writeUInt32BE(width, 4);
80
+ ihdr.set([8, 2, 0, 0, 0], 8); // 8-bit RGB
81
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw, { level })), chunk("IEND", Buffer.alloc(0))]);
82
+ }
83
+
84
+ /** A 256×256 Terrarium PNG of a tile's heights (NaN = no data). */
85
+ export function tilePng(heights) {
86
+ const rgb = Buffer.alloc(TILE * TILE * 3);
87
+ for (let i = 0; i < TILE * TILE; i++) writeTerrarium(rgb, i * 3, heights[i]);
88
+ return rgbPng(rgb);
89
+ }
90
+
91
+ export const lngOf = (x, z) => (x / 2 ** z) * 360 - 180;
92
+ export const latOf = (y, z) => (Math.atan(Math.sinh(Math.PI * (1 - (2 * y) / 2 ** z))) * 180) / Math.PI;
93
+ const tileX = (lng, z) => Math.floor(((lng + 180) / 360) * 2 ** z);
94
+ const tileY = (lat, z) => {
95
+ const r = (lat * Math.PI) / 180;
96
+ return Math.floor(((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2) * 2 ** z);
97
+ };
98
+
99
+ /** The CRS a GeoTIFF declares, as "EPSG:n" — or null for none / user-defined (32767). Projected rasters never fall back to their geographic key. */
100
+ export function declaredCrs(keys) {
101
+ const usable = (code) => code && code !== 32767;
102
+ const projected = keys.GTModelTypeGeoKey === 1 || usable(keys.ProjectedCSTypeGeoKey) || keys.ProjectedCSTypeGeoKey === 32767;
103
+ if (projected) return usable(keys.ProjectedCSTypeGeoKey) ? `EPSG:${keys.ProjectedCSTypeGeoKey}` : null;
104
+ return usable(keys.GeographicTypeGeoKey) ? `EPSG:${keys.GeographicTypeGeoKey}` : null;
105
+ }
106
+
107
+ /**
108
+ * Tile a GeoTIFF. `deps.resolveProjection` (the library's) and `deps.geotiff`
109
+ * are injectable for tests; the CLI passes the shipped ones.
110
+ */
111
+ export async function tileDem(opts, deps) {
112
+ const { input, out, format = "png", log = console.log } = opts;
113
+ const { geotiff, resolveProjection, sharp } = deps;
114
+ const tiff = await geotiff.fromFile(input);
115
+ const image = await tiff.getImage();
116
+ const width = image.getWidth();
117
+ const height = image.getHeight();
118
+ const transform = image.fileDirectory?.ModelTransformation;
119
+ if (transform && (transform[1] !== 0 || transform[4] !== 0)) throw new Error("The GeoTIFF is rotated or sheared (ModelTransformation): warp it north-up first, e.g. gdalwarp.");
120
+ const [ox, oy] = image.getOrigin();
121
+ const [rx, ry] = image.getResolution();
122
+ const keys = image.getGeoKeys?.() ?? image.geoKeys ?? {};
123
+ // PixelIsPoint (GTRasterTypeGeoKey 2): the origin is the first pixel's CENTRE, half a pixel inside its corner.
124
+ const point = keys.GTRasterTypeGeoKey === 2;
125
+ const cornerX = point ? ox - rx / 2 : ox;
126
+ const cornerY = point ? oy - ry / 2 : oy;
127
+ const epsg = opts.crs ?? declaredCrs(keys);
128
+ if (!epsg && !opts.crsDef) throw new Error("The GeoTIFF declares no EPSG code (or a user-defined CRS). Pass --crs EPSG:xxxx, or --crs-def '<proj4 or WKT>'.");
129
+ const projection = await resolveProjection(epsg ?? "EPSG:0", opts.crsDef ?? null);
130
+ if (!projection) throw new Error(`No definition for ${epsg}. Pass --crs-def '<proj4 or WKT>'.`);
131
+ const declared = opts.nodata ?? (typeof image.getGDALNoData === "function" ? image.getGDALNoData() : null);
132
+ const hasDeclared = declared !== null && declared !== undefined;
133
+ const isNoData = (v) => Number.isNaN(v) || (hasDeclared && Math.abs(v - declared) < 1e-6) || v < -1e30 || v > 1e30;
134
+
135
+ // The data's lng/lat box: the raster's outline, densely projected.
136
+ const outline = [];
137
+ for (let k = 0; k <= 64; k++) {
138
+ const t = k / 64;
139
+ for (const [c, r] of [[t * width, 0], [width, t * height], [(1 - t) * width, height], [0, (1 - t) * height]]) outline.push(projection.inverse([cornerX + c * rx, cornerY + r * ry]));
140
+ }
141
+ const ring = outline.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));
142
+ // Across ±180° the outline jumps a whole turn (a projected file) or runs past it (a geographic one); an <om-terrain> extent cannot hold either.
143
+ if (ring.some((p, k) => p[0] < -180 || p[0] > 180 || (k && Math.abs(p[0] - ring[k - 1][0]) > 180))) throw new Error("The GeoTIFF crosses the ±180° meridian: split it there (e.g. gdalwarp -te) and tile each half as its own source.");
144
+ const lngs = ring.map((p) => p[0]);
145
+ const lats = ring.map((p) => p[1]);
146
+ const extent = [Math.min(...lngs), Math.max(-85.05, Math.min(...lats)), Math.max(...lngs), Math.min(85.05, Math.max(...lats))];
147
+ const latMid = (extent[1] + extent[3]) / 2;
148
+ const pixelMetres = Math.abs(rx) * projection.metresPerUnit * (projection.units === "degree" ? Math.cos((latMid * Math.PI) / 180) : 1);
149
+ const maxZoom = opts.maxZoom ?? Math.max(0, Math.min(20, Math.round(Math.log2((EARTH * Math.cos((latMid * Math.PI) / 180)) / (TILE * pixelMetres)))));
150
+ const minZoom = Math.min(maxZoom, opts.minZoom ?? Math.max(0, Math.floor(Math.log2(360 / Math.max(1e-9, extent[2] - extent[0])))));
151
+
152
+ const encode = async (heights) => {
153
+ if (format === "webp") {
154
+ const rgb = Buffer.alloc(TILE * TILE * 3);
155
+ for (let i = 0; i < heights.length; i++) writeTerrarium(rgb, i * 3, heights[i]);
156
+ return sharp(rgb, { raw: { width: TILE, height: TILE, channels: 3 } }).webp({ lossless: true }).toBuffer();
157
+ }
158
+ return tilePng(heights);
159
+ };
160
+ let written = 0;
161
+ const write = async (z, x, y, heights) => {
162
+ const dir = join(out, String(z), String(x));
163
+ mkdirSync(dir, { recursive: true });
164
+ writeFileSync(join(dir, `${y}.${format}`), await encode(heights));
165
+ written++;
166
+ };
167
+ const touches = (z, x, y) => lngOf(x + 1, z) > extent[0] && lngOf(x, z) < extent[2] && latOf(y, z) > extent[1] && latOf(y + 1, z) < extent[3];
168
+
169
+ /** One top-zoom tile: every pixel projected into the file and sampled (bilinear, no-data corners skipped); null if it holds no data. */
170
+ const sampleTile = async (tx, ty) => {
171
+ const cells = new Float64Array(TILE * TILE * 2);
172
+ let minC = Infinity, maxC = -Infinity, minR = Infinity, maxR = -Infinity;
173
+ for (let py = 0; py < TILE; py++) {
174
+ const lat = latOf(ty + (py + 0.5) / TILE, maxZoom);
175
+ for (let px = 0; px < TILE; px++) {
176
+ const [sx, sy] = projection.forward([lngOf(tx + (px + 0.5) / TILE, maxZoom), lat]);
177
+ const c = (sx - cornerX) / rx - 0.5;
178
+ const r = (sy - cornerY) / ry - 0.5;
179
+ const i = (py * TILE + px) * 2;
180
+ cells[i] = c;
181
+ cells[i + 1] = r;
182
+ if (Number.isFinite(c) && Number.isFinite(r)) {
183
+ if (c < minC) minC = c;
184
+ if (c > maxC) maxC = c;
185
+ if (r < minR) minR = r;
186
+ if (r > maxR) maxR = r;
187
+ }
188
+ }
189
+ }
190
+ const wx0 = Math.max(0, Math.floor(minC)), wx1 = Math.min(width, Math.ceil(maxC) + 2);
191
+ const wy0 = Math.max(0, Math.floor(minR)), wy1 = Math.min(height, Math.ceil(maxR) + 2);
192
+ if (wx0 >= wx1 || wy0 >= wy1) return null; // the tile misses the raster
193
+ const [band] = await image.readRasters({ window: [wx0, wy0, wx1, wy1], samples: [0] });
194
+ const ww = wx1 - wx0;
195
+ const wh = wy1 - wy0;
196
+ const heights = new Float32Array(TILE * TILE);
197
+ let any = false;
198
+ for (let k = 0; k < TILE * TILE; k++) {
199
+ const c = cells[k * 2] - wx0;
200
+ const r = cells[k * 2 + 1] - wy0;
201
+ const c0 = Math.floor(c), r0 = Math.floor(r);
202
+ const fc = c - c0, fr = r - r0;
203
+ let sum = 0, weight = 0;
204
+ for (let dr = 0; dr <= 1; dr++) {
205
+ const rr = r0 + dr;
206
+ if (rr < 0 || rr >= wh) continue;
207
+ for (let dc = 0; dc <= 1; dc++) {
208
+ const cc = c0 + dc;
209
+ if (cc < 0 || cc >= ww) continue;
210
+ const v = band[rr * ww + cc];
211
+ if (isNoData(v)) continue;
212
+ const w = (dc ? fc : 1 - fc) * (dr ? fr : 1 - fr);
213
+ sum += w * v;
214
+ weight += w;
215
+ }
216
+ }
217
+ // Inside the raster's own footprint only (a pixel past its edge has no corner at all).
218
+ const inside = c >= -0.5 && r >= -0.5 && c <= ww - 0.5 && r <= wh - 0.5;
219
+ heights[k] = inside && weight > 1e-9 ? sum / weight : NaN;
220
+ if (heights[k] === heights[k]) any = true;
221
+ }
222
+ return any ? heights : null;
223
+ };
224
+
225
+ /** 2×2 averages of the four children (null where a child has none), skipping no-data. */
226
+ const average = (children) => {
227
+ const heights = new Float32Array(TILE * TILE).fill(NaN);
228
+ children.forEach((child, q) => {
229
+ if (!child) return;
230
+ const offX = (q & 1) * 128, offY = (q >> 1) * 128;
231
+ for (let y = 0; y < 128; y++) {
232
+ for (let x = 0; x < 128; x++) {
233
+ const i = y * 2 * TILE + x * 2;
234
+ let sum = 0, n = 0;
235
+ for (const v of [child[i], child[i + 1], child[i + TILE], child[i + TILE + 1]]) if (v === v) sum += v, n++;
236
+ heights[(offY + y) * TILE + offX + x] = n ? sum / n : NaN;
237
+ }
238
+ }
239
+ });
240
+ return heights;
241
+ };
242
+
243
+ /**
244
+ * Depth-first: a tile is built from its four children and written, then
245
+ * they are dropped — memory holds a few tiles per zoom level, not the
246
+ * whole top zoom (a big survey's thousands of top tiles).
247
+ */
248
+ const build = async (z, x, y) => {
249
+ if (!touches(z, x, y)) return null;
250
+ let heights;
251
+ if (z === maxZoom) heights = await sampleTile(x, y);
252
+ else {
253
+ const children = [];
254
+ for (let q = 0; q < 4; q++) children.push(await build(z + 1, x * 2 + (q & 1), y * 2 + (q >> 1)));
255
+ heights = children.some(Boolean) ? average(children) : null;
256
+ }
257
+ if (heights && z >= minZoom) await write(z, x, y, heights);
258
+ return heights;
259
+ };
260
+ for (let x = tileX(extent[0], minZoom); x <= tileX(extent[2] - 1e-12, minZoom); x++) {
261
+ for (let y = tileY(extent[3], minZoom); y <= tileY(extent[1] + 1e-12, minZoom); y++) await build(minZoom, x, y);
262
+ }
263
+
264
+ const round = (v) => Number(v.toFixed(5));
265
+ const src = `${opts.srcPrefix ?? out}/{z}/{x}/{y}.${format}`;
266
+ const line = `<om-terrain id="${opts.id ?? "survey"}" src="${src}" decoder="terrarium" nodata="${NODATA_SENTINEL}" extent="[${extent.map(round).join(", ")}]" min-zoom="${minZoom}" max-zoom="${maxZoom}"></om-terrain>`;
267
+ log(`Wrote ${written} tiles (zoom ${minZoom}–${maxZoom}, ${projection.code}) to ${out}`);
268
+ log(line);
269
+ return { written, minZoom, maxZoom, extent, line };
270
+ }
package/bin/onlymapjs.mjs CHANGED
@@ -14,6 +14,8 @@ function usage() {
14
14
  onlymapjs check-layout <manifest.html>
15
15
  onlymapjs record <manifest.html> [options]
16
16
  onlymapjs export <manifest.html> [options]
17
+ onlymapjs inspect-terrain <manifest.html>
18
+ onlymapjs dem-tiles <dem.tif> --out <dir> [options]
17
19
  onlymapjs --help
18
20
 
19
21
  Commands:
@@ -28,6 +30,18 @@ Commands:
28
30
  check-layout
29
31
  Load a browser-runnable manifest in isolated headless Chromium,
30
32
  audit real widget geometry at 360/640/768/1024px, and exit 0/1.
33
+ dem-tiles Tile a GeoTIFF DEM (a survey, a public grid) into Terrarium
34
+ tiles an <om-terrain> reads, reprojecting from the file's CRS.
35
+ No-data cells become holes (written as -32768). Prints the
36
+ <om-terrain> line to paste. Needs geotiff (npm install -D geotiff).
37
+ inspect-terrain
38
+ Load a map page in isolated headless Chromium and read its
39
+ terrain's own tiles for what the markup cannot tell: a step
40
+ where two <om-terrain> sources meet (a steady one is a vertical
41
+ datum difference, with the vertical-offset that closes it) and
42
+ heights no real ground has (the tiles' no-data value, with the
43
+ nodata to set). Warnings only; exits 0 unless the page fails.
44
+ Needs Playwright.
31
45
  record Play a story load-paced in isolated headless Chromium and write a
32
46
  video in which every frame's 3D tiles are fully refined — no
33
47
  pop-in, no blur, however slow the tile server. Captures one
@@ -44,6 +58,15 @@ Options (export):
44
58
  against (default: the manifest's own directory).
45
59
  --force Overwrite an existing output file.
46
60
 
61
+ Options (dem-tiles):
62
+ --out <dir> Where the {z}/{x}/{y} tiles go (required).
63
+ --nodata <v> The file's no-data value (default: its GDAL_NODATA tag; NaN always).
64
+ --min-zoom <z> Lowest zoom (default: where the data spans about a tile).
65
+ --max-zoom <z> Highest zoom (default: the file's own resolution).
66
+ --format <f> png (default) or webp (lossless; needs sharp installed).
67
+ --crs <code> The file's CRS when it declares none, e.g. EPSG:32610.
68
+ --crs-def <def> A proj4 or WKT definition for a CRS the library does not bundle.
69
+ --id <name> The <om-terrain> id in the printed line (default: survey).
47
70
  Options (record):
48
71
  --story <id> Which <om-story> to record (default: the first one).
49
72
  --out <file> Output path; .mp4 (H.264) or .webm (VP9). Default <manifest>.mp4.
@@ -163,25 +186,23 @@ async function startStaticServer(manifestPath, packageRoot) {
163
186
  return { server, url: `http://127.0.0.1:${address.port}/` };
164
187
  }
165
188
 
166
- async function checkLayout(manifestArg) {
167
- if (!manifestArg) throw new Error("check-layout needs a manifest HTML path.\nUsage: onlymapjs check-layout <manifest.html>");
189
+ /**
190
+ * Open a manifest in an isolated headless Chromium, served with the package's
191
+ * own build, and hand `run` the page. A failure inside `run` carries the
192
+ * page's first errors — usually the real cause when the map never came up.
193
+ */
194
+ async function withManifestPage(command, manifestArg, banner, run) {
195
+ if (!manifestArg) throw new Error(`${command} needs a manifest HTML path.\nUsage: onlymapjs ${command} <manifest.html>`);
168
196
  const manifestPath = resolve(process.cwd(), manifestArg);
169
- if (!existsSync(manifestPath) || !statSync(manifestPath).isFile()) {
170
- throw new Error(`Manifest not found: ${manifestPath}`);
171
- }
172
- if (extname(manifestPath).toLowerCase() !== ".html") {
173
- throw new Error(`check-layout expects an .html manifest, received: ${manifestPath}`);
174
- }
175
-
176
- const playwright = await importPlaywright("check-layout");
177
-
197
+ if (!existsSync(manifestPath) || !statSync(manifestPath).isFile()) throw new Error(`Manifest not found: ${manifestPath}`);
198
+ if (extname(manifestPath).toLowerCase() !== ".html") throw new Error(`${command} expects an .html manifest, received: ${manifestPath}`);
199
+ const playwright = await importPlaywright(command);
178
200
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
179
- const { auditLayout } = await import(new URL("../dist/onlymapjs.js", import.meta.url));
180
201
  const { server, url } = await startStaticServer(manifestPath, packageRoot);
181
202
  let browser;
182
203
  try {
183
- console.log(`Auditing ${manifestPath}`);
184
- console.log("Note: check-layout executes this page's scripts inside an isolated headless Chromium context.");
204
+ console.log(`${banner} ${manifestPath}`);
205
+ console.log(`Note: ${command} executes this page's scripts inside an isolated headless Chromium context.`);
185
206
  browser = await launchChromium(playwright);
186
207
  const context = await browser.newContext({ serviceWorkers: "block" });
187
208
  const page = await context.newPage();
@@ -191,15 +212,41 @@ async function checkLayout(manifestArg) {
191
212
  if (msg.type() === "error") pageErrors.push(msg.text().split("\n")[0]);
192
213
  });
193
214
  await page.goto(url, { waitUntil: "domcontentloaded" });
194
- let diagnostics;
195
215
  try {
196
- diagnostics = await auditLayout(page);
216
+ return await run(page);
197
217
  } catch (error) {
198
- // The page never produced a map. Its own console/pageerror output is the
199
- // real cause — surface it so the failure is self-explaining.
200
218
  const detail = pageErrors.length ? `\nPage errors:\n ${pageErrors.slice(0, 3).join("\n ")}` : "";
201
219
  throw new Error(`${error instanceof Error ? error.message : String(error)}${detail}`);
202
220
  }
221
+ } finally {
222
+ await browser?.close();
223
+ await new Promise((resolveClose) => server.close(resolveClose));
224
+ }
225
+ }
226
+
227
+ /** Walk `rest`, calling `onArg(arg, next)`; `next()` takes the flag's value, and throws when there is none. */
228
+ function eachArg(rest, onArg) {
229
+ for (let i = 0; i < rest.length; i += 1) {
230
+ const arg = rest[i];
231
+ onArg(arg, () => {
232
+ i += 1;
233
+ if (i >= rest.length) throw new Error(`${arg} needs a value.`);
234
+ return rest[i];
235
+ });
236
+ }
237
+ }
238
+
239
+ /** A flag's numeric value — finite, and above zero when `positive`. */
240
+ function numberArg(flag, raw, positive = false) {
241
+ const value = Number(raw);
242
+ if (!Number.isFinite(value) || (positive && value <= 0)) throw new Error(`${flag} needs a ${positive ? "positive " : ""}number, received: ${raw}`);
243
+ return value;
244
+ }
245
+
246
+ async function checkLayout(manifestArg) {
247
+ const { auditLayout } = await import(new URL("../dist/onlymapjs.js", import.meta.url));
248
+ return withManifestPage("check-layout", manifestArg, "Auditing", async (page) => {
249
+ const diagnostics = await auditLayout(page);
203
250
  if (diagnostics.length === 0) {
204
251
  console.log("CLEAN: no widget layout problems at 360, 640, 768, or 1024px.");
205
252
  return 0;
@@ -207,26 +254,78 @@ async function checkLayout(manifestArg) {
207
254
  for (const diagnostic of diagnostics) console.error(JSON.stringify(diagnostic));
208
255
  console.error(`FAILED: ${diagnostics.length} layout diagnostic(s).`);
209
256
  return diagnostics.some((diagnostic) => diagnostic.severity === "error") ? 1 : 0;
210
- } finally {
211
- await browser?.close();
212
- await new Promise((resolveClose) => server.close(resolveClose));
257
+ });
258
+ }
259
+
260
+ async function demTilesCommand(rest) {
261
+ const opts = { format: "png" };
262
+ eachArg(rest, (arg, next) => {
263
+ if (arg === "--out") opts.out = next();
264
+ else if (arg === "--nodata") opts.nodata = numberArg(arg, next());
265
+ else if (arg === "--min-zoom") opts.minZoom = numberArg(arg, next());
266
+ else if (arg === "--max-zoom") opts.maxZoom = numberArg(arg, next());
267
+ else if (arg === "--format") opts.format = next();
268
+ else if (arg === "--crs") opts.crs = next();
269
+ else if (arg === "--crs-def") opts.crsDef = next();
270
+ else if (arg === "--id") opts.id = next();
271
+ else if (arg.startsWith("--")) throw new Error(`Unknown dem-tiles option: ${arg}`);
272
+ else if (!opts.input) opts.input = resolve(process.cwd(), arg);
273
+ else throw new Error(`Unexpected argument: ${arg}`);
274
+ });
275
+ if (!opts.input || !opts.out) throw new Error("Usage: onlymapjs dem-tiles <dem.tif> --out <dir> [--nodata v] [--min-zoom z] [--max-zoom z] [--format png|webp]");
276
+ if (!existsSync(opts.input)) throw new Error(`GeoTIFF not found: ${opts.input}`);
277
+ if (opts.format !== "png" && opts.format !== "webp") throw new Error(`--format is png or webp, received: ${opts.format}`);
278
+ let geotiff;
279
+ try {
280
+ geotiff = await import("geotiff");
281
+ } catch {
282
+ throw new Error("dem-tiles reads GeoTIFFs with the geotiff package, which is not installed.\nInstall it with:\n npm install --save-dev geotiff");
213
283
  }
284
+ let sharp;
285
+ if (opts.format === "webp") {
286
+ try {
287
+ sharp = (await import("sharp")).default;
288
+ } catch {
289
+ throw new Error("--format webp encodes with sharp, which is not installed. Use --format png, or:\n npm install --save-dev sharp");
290
+ }
291
+ }
292
+ const { resolveProjection } = await import(new URL("../dist/onlymapjs.js", import.meta.url));
293
+ const { tileDem } = await import(new URL("./dem-tiles.mjs", import.meta.url));
294
+ await tileDem({ ...opts, out: resolve(process.cwd(), opts.out), srcPrefix: opts.out.replace(/\/+$/, "") }, { geotiff, resolveProjection, sharp });
295
+ return 0;
296
+ }
297
+
298
+ async function inspectTerrainCommand(manifestArg) {
299
+ return withManifestPage("inspect-terrain", manifestArg, "Inspecting the terrain of", async (page) => {
300
+ const entries = await page.evaluate(async () => {
301
+ const deadline = Date.now() + 30_000;
302
+ let map = document.querySelector("om-map");
303
+ while (!map && Date.now() < deadline) {
304
+ await new Promise((r) => setTimeout(r, 100));
305
+ map = document.querySelector("om-map");
306
+ }
307
+ if (!map) throw new Error("no <om-map> on the page");
308
+ const notReady = new Promise((_, reject) => setTimeout(() => reject(new Error("the map did not become ready within 60 s")), 60_000));
309
+ await Promise.race([map.ready, notReady]);
310
+ if (typeof map.inspectTerrain !== "function") throw new Error("this OnlyMapJS build has no inspectTerrain() — upgrade @nika-js/onlymap");
311
+ return map.inspectTerrain();
312
+ });
313
+ if (!entries.length) {
314
+ console.log("CLEAN: no step between terrain sources, and no no-data-like heights, in the tiles read.");
315
+ return 0;
316
+ }
317
+ for (const entry of entries) {
318
+ console.log(`${entry.severity.toUpperCase()} ${entry.element}${entry.attribute ? ` [${entry.attribute}]` : ""}: ${entry.message}`);
319
+ console.log(` fix: ${entry.fix}`);
320
+ }
321
+ return 0;
322
+ });
214
323
  }
215
324
 
216
325
  function parseRecordArgs(rest) {
217
326
  const opts = { manifest: undefined, out: undefined, story: undefined, fps: undefined, width: 1280, height: 720, scale: 1, keepFrames: false, timeoutS: 600, maxHoldS: undefined };
218
- const numberFor = (flag, raw) => {
219
- const value = Number(raw);
220
- if (!Number.isFinite(value) || value <= 0) throw new Error(`${flag} needs a positive number, received: ${raw}`);
221
- return value;
222
- };
223
- for (let i = 0; i < rest.length; i += 1) {
224
- const arg = rest[i];
225
- const next = () => {
226
- i += 1;
227
- if (i >= rest.length) throw new Error(`${arg} needs a value.`);
228
- return rest[i];
229
- };
327
+ const numberFor = (flag, raw) => numberArg(flag, raw, true);
328
+ eachArg(rest, (arg, next) => {
230
329
  if (arg === "--out") opts.out = next();
231
330
  else if (arg === "--story") opts.story = next();
232
331
  else if (arg === "--fps") opts.fps = numberFor("--fps", next());
@@ -243,7 +342,7 @@ function parseRecordArgs(rest) {
243
342
  else if (arg.startsWith("--")) throw new Error(`Unknown record option: ${arg}`);
244
343
  else if (opts.manifest === undefined) opts.manifest = arg;
245
344
  else throw new Error(`Unexpected argument: ${arg}`);
246
- }
345
+ });
247
346
  if (!opts.manifest) throw new Error("record needs a manifest HTML path.\nUsage: onlymapjs record <manifest.html> [options]");
248
347
  return opts;
249
348
  }
@@ -819,6 +918,11 @@ try {
819
918
  process.exitCode = await recordStory(rest);
820
919
  } else if (command === "export") {
821
920
  process.exitCode = await exportStandalone(rest);
921
+ } else if (command === "dem-tiles") {
922
+ process.exitCode = await demTilesCommand(rest);
923
+ } else if (command === "inspect-terrain") {
924
+ if (rest.length !== 1) throw new Error("Usage: onlymapjs inspect-terrain <manifest.html>");
925
+ process.exitCode = await inspectTerrainCommand(rest[0]);
822
926
  } else {
823
927
  console.error(`Unknown command: ${command}\n`);
824
928
  usage();
@@ -1,5 +1,5 @@
1
- import { aQ as Y_, N as Ou, H as Id, k as K_, aR as J_, aS as Q_, D as Yf, Z as ey, aT as ty } from "./index-CpFNIkOO.js";
2
- import { a as iy } from "./globe-view-Xelgj_KW.js";
1
+ import { aZ as Y_, N as Ou, H as Id, k as K_, a_ as J_, a$ as Q_, D as Yf, Z as ey, b0 as ty } from "./index-BfHaNHyY.js";
2
+ import { a as iy } from "./globe-view-BWNfn-Sx.js";
3
3
  const ry = /* @__PURE__ */ new Set(["tile.openstreetmap.org", "a.tile.openstreetmap.org", "b.tile.openstreetmap.org", "c.tile.openstreetmap.org"]);
4
4
  function ny(Me) {
5
5
  let Q;