@bendyline/molen-tooling 0.0.4 → 0.0.6

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/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as formatPacked, A as inspectContentPack, B as searchDocs, C as checkTypesOp, D as buildContentPack, E as reserveNamespace, F as previewFigure, H as describeOps, I as listFigurePresets, J as checkSoundbank, K as planAudio, L as exportFrames, M as bakeNetwork, N as generateTypes, O as extractContentPack, Q as formatBytes, R as driveScene, S as rasterizeMaterial, T as projectInfo, U as formatOp, V as OPS_CATALOG, W as checkScripts, X as stageAssets, Z as screenshotAsset, _ as loadComponentRegistry, b as diffSnapshots, c as validateAsset, d as runSimulation, dt as playExperience, et as packAsset, f as screenshotScene, g as listSchemasOp, h as listComponentsOp, i as bakeWorldgen, it as importAsset, j as verifyContentPack, k as fetchContentPack, l as applyUvPaintOp, m as getSchemaOp, n as worldgenStats, nt as listAssets, p as getComponentOp, q as importSound, r as previewWorldgen, s as simWatch, t as formatWorldgenStats, tt as inspectAsset, u as testTypes, v as scaffoldExperience, w as listTypes, x as runReplayFile, y as listTemplates } from "./ops-DMGcWoL2.mjs";
2
+ import { $ as formatPacked, A as inspectContentPack, B as searchDocs, C as checkTypesOp, D as buildContentPack, E as reserveNamespace, F as previewFigure, H as describeOps, I as listFigurePresets, J as checkSoundbank, K as planAudio, L as exportFrames, M as bakeNetwork, N as generateTypes, O as extractContentPack, Q as formatBytes, R as driveScene, S as rasterizeMaterial, T as projectInfo, U as formatOp, V as OPS_CATALOG, W as checkScripts, X as stageAssets, Z as screenshotAsset, _ as loadComponentRegistry, b as diffSnapshots, c as validateAsset, d as runSimulation, dt as playExperience, et as packAsset, f as screenshotScene, g as listSchemasOp, h as listComponentsOp, i as bakeWorldgen, it as importAsset, j as verifyContentPack, k as fetchContentPack, l as applyUvPaintOp, m as getSchemaOp, n as worldgenStats, nt as listAssets, p as getComponentOp, q as importSound, r as previewWorldgen, s as simWatch, t as formatWorldgenStats, tt as inspectAsset, u as testTypes, v as scaffoldExperience, w as listTypes, x as runReplayFile, y as listTemplates } from "./ops-2qoHKV54.mjs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { formatIssues } from "@bendyline/molen-schema";
@@ -1254,7 +1254,7 @@ async function cmdWorldgen(args) {
1254
1254
  return 2;
1255
1255
  }
1256
1256
  async function cmdMcp() {
1257
- const { startMcpServer } = await import("./mcp-BtuworIW.mjs");
1257
+ const { startMcpServer } = await import("./mcp-ClDdiqq4.mjs");
1258
1258
  await startMcpServer();
1259
1259
  return 0;
1260
1260
  }
@@ -26,6 +26,12 @@ capability for shapes that genuinely need sculpting, retopology, rigging, or com
26
26
 
27
27
  For shared polygonal style, fidelity targets and canonical materials, follow [3D art guidelines](3d-art-guidelines.md).
28
28
 
29
+ For programmatic captures of reflective metal or glass, pass `reflections: true` to
30
+ `screenshotScene` or `screenshotAsset` from `@bendyline/molen-tooling`. This enables the
31
+ viewer's shared procedural sky/ground environment; the default remains the legacy light rig.
32
+ The repository landmark capture script accepts `--reflections` and records that mode in its
33
+ hash-bound report. See [sky reflections](sky.md#reflections) for the runtime lighting model.
34
+
29
35
  ## 1. Convert the prompt into an asset brief
30
36
 
31
37
  Before making geometry, decide the points that affect the runtime result:
@@ -51,8 +51,11 @@ Transitions have 15% hysteresis.
51
51
 
52
52
  Builtin vegetation uses three shared models in spatial cells; the far fir/conifer is 12 triangles
53
53
  and the far broadleaf crown is 20. Building cells use authored materials nearby, a single
54
- vertex-color material farther away, then remove window/door/trim faces while retaining walls,
55
- roof shapes and foundations. Cell bounds let frustum culling reject offscreen batches.
54
+ vertex-color material farther away (where window glass keeps a dark glass tone rather than turning
55
+ white, and buildings still cast shadows), then remove door, trim and detail faces while retaining
56
+ walls, roof shapes, foundations and windows, so a distant facade keeps its rows of windows. Cells
57
+ store positions as 16-bit offsets with one uniform scale per cell and normals as 8-bit values,
58
+ 20 bytes a vertex instead of 35. Cell bounds let frustum culling reject offscreen batches.
56
59
  These are conservative authored detail tolerances, not measured mesh-simplification error bounds.
57
60
 
58
61
  Terrain selection also culls by horizontal view direction. Mesh frustum culling and the GPU
@@ -60,6 +60,15 @@ Pass `reflections: false` for the legacy light-only appearance. A host-assigned
60
60
  compass bearing, 0 north and clockwise) place the sun, and unless `environment.sun.direction` is
61
61
  given the sunlight comes from the same point, so lit faces agree with the glow in the sky. `fog`,
62
62
  `water`, `background` and the rest of `environment` (ambient light, tone mapping, exposure) follow.
63
+ `ground` recolors the terrain package's bare-ground surface layers by name (for example
64
+ `{ lowland: '#8b9e70' }`), and `landcover` sets landcover class colors (forest, grass, park,
65
+ residential, commercial…) over the style pack's palette; an unlisted class falls back to a
66
+ neutral olive.
67
+
68
+ Buildings, trees and landmarks cast sun shadows onto everything around what the camera frames:
69
+ the orbit target (sized to the view), or a little ahead of the walker, car or aircraft. The
70
+ shadow map follows that focus in whole texels, so edges hold still as it moves. Adaptive quality
71
+ turns shadows off at its two lowest levels; `shadows: false` turns them off entirely.
63
72
 
64
73
  `touchJoystickContainer` adds an on-screen movement stick while walking, driving or flying. By default it
65
74
  appears only on touch devices; pass `touchJoystick: 'always'` to show it everywhere.
@@ -69,7 +78,10 @@ appears only on touch devices; pass `touchJoystick: 'always'` to show it everywh
69
78
  - **orbit** (default): the map camera from [camera navigation](navigation.md). `flyTo(target)`
70
79
  animates and `jumpTo(target)` moves at once. The target takes `latitude`, `longitude`, and
71
80
  optionally `range` in meters, `heading` (a compass bearing in radians) and `pitch` (radians of
72
- tilt below the horizon).
81
+ tilt below the horizon). The camera stays within `earthOrbitMaxRange(viewDistance)` of its target
82
+ (45% of the current performance tier's terrain view distance, at least 2 km), so it cannot pull
83
+ back past where the scene still draws; a farther `range` is clamped, and the limit follows
84
+ adaptive quality.
73
85
  - **walk**: `setMode('walk')` drops a walker at the view center. It has capsule collision against
74
86
  terrain, buildings and props, WASD or the touch stick to move, mouse-look with pointer lock, and
75
87
  Space to jump.
@@ -181,12 +193,66 @@ const view = await mountEarthView({
181
193
  });
182
194
  ```
183
195
 
184
- The host can return `archives` in the result to fetch tiles from its own PMTiles service. Keep
196
+ The host can return `archives` in the result to fetch tiles from its own PMTiles service
197
+ (`elevation`, `landcover`, `features`, and `buildingDetail` for a package's finer building tier;
198
+ see [terrain](terrain.md)). A building-detail archive that fails to open is reported as an error
199
+ and the view carries on with the feature tiles' own footprints. Keep
185
200
  pack attribution visible through `view.credits`, which follows the active terrain source. Listen
186
201
  for `terrainchange` to refresh an attribution panel when the package changes. Direct jumps and
187
202
  completed flights resolve the destination immediately; manual panning rechecks the host source
188
203
  after about five kilometers. A second jump while a region is loading follows the latest target.
189
204
 
205
+ ## Byte cache and prefetch
206
+
207
+ Terrain, landcover, feature and building tiles, content packs and the small documents that name
208
+ them can persist across visits in a byte cache from `@bendyline/molen-pack/cache`. Ground a viewer
209
+ has seen then streams from disk instead of the network, and a revisited city costs almost no
210
+ requests. The cache splits each archive into 64 KiB blocks held in memory and in IndexedDB,
211
+ merges neighbouring misses into one range request, shares a block between concurrent reads, and
212
+ evicts least recently used blocks past a byte budget.
213
+
214
+ ```ts
215
+ import { createBlockCache, createIndexedDbByteStore, createMemoryByteStore } from '@bendyline/molen-pack/cache';
216
+ import { loadEarthContent, mountEarthView, openPacksFromIndex } from '@bendyline/molen-earth/client';
217
+
218
+ const store = createIndexedDbByteStore({ name: 'my-app-bytes', budgetBytes: 300 * 1024 * 1024 });
219
+ const byteCache = createBlockCache(store ?? createMemoryByteStore());
220
+
221
+ const packs = await openPacksFromIndex(indexUrl, undefined, undefined, { byteCache });
222
+ const view = await mountEarthView({
223
+ canvas,
224
+ terrain,
225
+ baseUrl,
226
+ content: await loadEarthContent(packs),
227
+ byteCache,
228
+ camera: { latitude: 47.6205, longitude: -122.3493, range: 1500 },
229
+ });
230
+ ```
231
+
232
+ The view opens the package's own archives through the cache, keyed by the SHA-256 that its
233
+ `files` list or archive sets give, or by URL when none is listed. Archives you pass in `archives`
234
+ are used as given, so route them through the cache yourself where you want them kept: wrap a
235
+ PMTiles source with `cachingRangeSource`, or open archive-set members with `cachingArchiveOpener`
236
+ from `@bendyline/molen-terrain/client`. A stable URL whose file is replaced in place needs
237
+ `keyBy: 'etag'`, so each server version becomes its own archive. Content packs are keyed by their
238
+ content hash, file and size. Pass the same cache to `openPacksFromIndex` and `mountEarthView` so
239
+ packs and terrain share one budget. `cachingDocumentFetch` keeps the small JSON documents (pack
240
+ index, archive sets, manifests) and revalidates them with `If-None-Match`, serving the stored copy
241
+ offline.
242
+
243
+ With a byte cache the view also prefetches. It follows the camera's own track, so it works for an
244
+ orbit pan, a car and an aircraft alike. It places virtual views 20, 40 and 60 seconds ahead,
245
+ selects their tiles the way the stream would, and reads those archive tiles into the cache. It
246
+ reads bytes only and decodes nothing, two reads at a time, only while the stream has a free load
247
+ slot, and pauses when the page is hidden, offline or on Save-Data. It waits out camera animations
248
+ (a fly-to, getting into a vehicle), whose momentary speed is not travel, and never looks more than
249
+ 15 km ahead. Tune it with `prefetch` (`horizonSeconds`, `stepsSeconds`, `maxConcurrent`,
250
+ `maxDistanceMeters`), or turn it off with `prefetch: false`. A host
251
+ that knows the route, such as a simulator's flight plan, queues places with
252
+ `view.prefetch([{ latitude, longitude, altitude }])`. Those go first and resolve once read. A
253
+ `flyTo` within the current frame queues its destination. `view.cacheStats()` reports block hits,
254
+ network requests, stored bytes and prefetch progress.
255
+
190
256
  ## Ambient life
191
257
 
192
258
  Cars drive the mapped roads, pedestrians walk the footways, trains run the railways and aircraft
@@ -220,14 +286,26 @@ tile must resolve the same model origin, avoiding inconsistent ground samples be
220
286
  `replaceRoads: { length, width, deckHeight?, deckHeights? }` describes a model-local rectangle along +X:
221
287
  mapped parallel bridge lines inside it are replaced only after the model loads successfully.
222
288
  Outside approach fragments remain procedural. `deckHeight` joins those approaches to the
223
- model's deck height above its origin, blending back over 100 m; include that margin in `bounds`.
289
+ model's deck height above its origin, blending back over at most 100 m; include that margin in `bounds`.
224
290
  For sloped decks, use `deckHeights: [negativeXEnd, positiveXEnd]` instead of `deckHeight`.
225
291
  Both heights are native model Y and follow the model's Y scale, resolved origin and heading.
226
- These joins apply to remaining bridge-tagged road fragments, not unrelated ground roads.
292
+ Each remaining bridge fragment uses its nearest authored endpoint and returns to the height
293
+ of a connected ground road at its far end. If a replaced bridge ends on the model boundary,
294
+ an outward ground approach sharing that endpoint receives a local height correction, fading
295
+ back to terrain within 20 m or the approach length. The painter and traffic graph use the same
296
+ profile. This does not generate a slab beneath ground roads or lift nearby perpendicular
297
+ crossings, tunnels or disconnected riverbank paths.
227
298
  Skewed or curved structures may add `replaceRoads.outline: [[x, z], ...]`, a simple native
228
299
  footprint polygon. It replaces the rectangle for suppression, including concave bends;
229
- parallel road segments outside it remain intact. `length` still locates the two connection
230
- stations at native X=-length/2 and X=+length/2, Z=0, and `deckHeights` keeps that endpoint order.
300
+ parallel road segments outside it remain intact. Connection stations use the outline's outer
301
+ intersections with native Z=0, ordered negative to positive X. Without an intersecting outline,
302
+ they fall back to X=-length/2 and X=+length/2. `deckHeights` keeps that endpoint order.
303
+ If the asset includes its retaining walls and approach pavement, set
304
+ `replaceRoads.includeConnectedApproaches: true`. A grade road is then clipped inside the outline
305
+ only if it shares a covered endpoint with a mapped bridge and continues outward along the bridge
306
+ axis. The remaining grade fragment receives a 20 m terrain blend. Nearby roads, transverse paths
307
+ and tunnels remain intact. This requires the source tile to retain the shared bridge/approach
308
+ endpoint; disconnected or generalized map geometry is left in place.
231
309
  Sunken structures can declare `groundCutout: { outline: [[x, z], ...], basis: 'source evidence' }` on a placement. The simple polygon uses native model metres and follows the same heading and scale as the model. It should bound the ground opening covered by the authored concourse or rim. The terrain pyramid subtracts the polygon from actual elevation and draped ground triangles across tile and LOD boundaries, preserving interpolated heights and surface attributes along its edge. The cutout becomes active only when its successfully loaded structure is visible, and the original ground returns on layer hiding or eviction. Failed or cancelled models leave the ground intact. Heights remain available for anchoring; an opening does not itself author walkable floors or collision.
232
310
 
233
311
  ### Bridge elevations and terrain fit
@@ -278,9 +356,13 @@ model eviction. `build-copernicus-bridge-evidence.py` and the capture runner's
278
356
  neither capture set substitutes altered heights to make a bridge fit. These reports are research
279
357
  evidence and are excluded from the Earth runtime pack.
280
358
 
281
- If `replaceFootprint` is set, a nongeneralized mapped building is suppressed only when the
282
- anchor falls inside its polygon and the replacement model has loaded. Failed models keep the
283
- procedural building. An Earth pack without a placement document still loads.
359
+ If `replaceFootprint` is set, a mapped building is suppressed only when the anchor falls inside
360
+ its polygon and the replacement model has loaded. Failed models keep the procedural building.
361
+ Generalized sources (Protomaps below zoom 15, and tiles overzoomed from them) merge neighboring
362
+ footprints, so there the polygon is suppressed only when neither side exceeds the loaded model's
363
+ horizontal extent by more than 1.6 times plus 12 meters; a larger polygon is a merged block of
364
+ other buildings and keeps its procedural shell. An Earth pack without a placement document still
365
+ loads.
284
366
 
285
367
  For unsurveyed orientation, `orientation: 'mapped'` requires an explicit
286
368
  `mapIdentity: { wikidata: 'Q…', maxDistance: 150 }`. The viewer admits that model only after a
@@ -320,8 +402,8 @@ uniformly scale native models, bounded from 0.2 to 5 times native dimensions; fo
320
402
  adjusts the three dimensions independently. Explicit source `direction`
321
403
  or compass bearings take priority; otherwise footprints use their longest axis and points
322
404
  default north. This default is an estimate, especially for rotatable turbine nacelles.
323
- Rules with `replaceFootprint: true` can also replace a nongeneralized footprint containing a
324
- matching POI, after the asset loads. This is useful when a windmill is a POI plus an unclassified
405
+ Rules with `replaceFootprint: true` can also replace a footprint containing a matching POI,
406
+ after the asset loads, under the same size rule for generalized footprints. This is useful when a windmill is a POI plus an unclassified
325
407
  building outline; the default leaves point features independent of building shells.
326
408
 
327
409
  The renderer admits at most 64 category models per tile and obeys each rule's smaller budget.
@@ -420,8 +502,10 @@ on-demand material eviction policy is not yet implemented.
420
502
  Constant roughness and metalness channels use exact numeric factors instead of textures;
421
503
  other maps retain their authored pixels. Across the full library this removes 58 texture
422
504
  allocations, reducing estimated base-level RGBA8 texel storage from 45.75 to 31.25 MiB.
423
- These are storage estimates, not measured driver allocations. Alpha-cutout surfaces retain
424
- linear sampling without mip averaging so small perforations remain open.
505
+ These are storage estimates, not measured driver allocations. Hard alpha-cutout surfaces retain
506
+ linear sampling without mip averaging. Fine porous surfaces can opt into `alphaCoverage: true`:
507
+ mipmapped alpha blending preserves average open area at distance, with the same `BLEND` fallback
508
+ in portable GLBs. Review overlapping transparent layers and close-up hole detail from both sides.
425
509
 
426
510
  Hosts composing their own renderer can supply `StructureModelLibrary` with
427
511
  `resolveSurface: ({ ref, slot }) => materials.materialFor(slot, ref)` using a
@@ -462,7 +546,28 @@ These regional forms are visual priors, not surveyed attributes of individual bu
462
546
  - `view.credits` holds the package's required attributions, OpenStreetMap first with its link.
463
547
  Keep them visible whenever the view is.
464
548
  - `quality: 'auto'` adapts terrain budgets, building detail and pixel ratio to measured frame
465
- times (`stats().qualityLevel`, 0-5). A preset pins the quality.
549
+ times (`stats().qualityLevel`, 0-5, with `stats().qualityReason`). A preset pins the quality.
550
+ It starts at `earthInitialQualityLevel()`: level 1 on touch devices and at 2 GiB or less, 2 at
551
+ 4 GiB, otherwise 3, and climbs no higher than `maxQualityLevel` (default 3; above it buildings
552
+ switch to the high preset, which rebuilds them across the view). Where the browser can time the GPU (`renderer.createGpuTimer()`), the view
553
+ reports GPU and CPU work per frame, so slow frames while tiles stream in lower the level only
554
+ when rendering itself is the cost; without GPU timing it goes by frame times alone. The view
555
+ first calibrates quickly, so a slow device settles within seconds. Once a level has held for
556
+ 12 s it turns sticky, because a level change swaps resolution and detail across the view: down
557
+ after 2.5 s of sustained overload, up after 20 s of headroom, at least 6 s apart. Any change
558
+ waits until the camera has been still for 0.6 s (at most 4 s); memory pressure above 1.25
559
+ applies it at once.
560
+ - Ground 20° past each side of the view stays loaded as bare terrain (the stream's
561
+ `peripheralDegrees`), so turning the camera reveals ground at once and its buildings and trees
562
+ follow.
563
+ - Memory pressure (`stats().memoryPressure`) is the geometry on screen over `memoryBudget`, a
564
+ fixed per-device budget: `earthMemoryBudget()` gives 96 MiB per GiB the browser reports within
565
+ 192–768 MiB, or 256 MiB on touch devices and 512 MiB elsewhere without a report. Above 1 the
566
+ level steps down, and since stepping down selects fewer, coarser tiles, pressure falls rather
567
+ than cascading to the minimum. The terrain cache keeps at least the budget, so ground just left
568
+ is still warm when the view pans back.
569
+ - `stats().worldgen` counts styled building generation since the current terrain stream started
570
+ (with content packs): tiles generated, buildings drawn as geometry, and instanced stand-ins.
466
571
  - `setPaused(true)` stops rendering while the view is hidden, and `dispose()` releases the GPU
467
572
  context, workers and listeners. Mounting is abortable through `signal`.
468
573
 
@@ -113,6 +113,12 @@ pixels and its old entries are pruned. Store failures fall back to baking. `crea
113
113
  and `mountEarthView` accept the store as `materialStore`; World Explorer passes the IndexedDB store
114
114
  unless `materialCache=0`.
115
115
 
116
+ Terrain and content bytes persist the same way through a `BlockCache` from
117
+ `@bendyline/molen-pack/cache`, passed to `mountEarthView` as `byteCache` (see
118
+ [the Earth view](earth-view.md)). It saves network and decompression time, not frame time: decoding
119
+ and meshing still run for every tile the stream loads. Prefetching reads bytes only, so it never
120
+ competes with tile construction on the main thread.
121
+
116
122
  World-generation workers also prepare building spatial cells and full/structural LOD indices.
117
123
  The renderer requests `renderCellsOnly` when using cell LODs so it does not retain a redundant
118
124
  canonical building mesh. Per-cell Three object assembly is a separate queue job. Generation
@@ -4,8 +4,11 @@
4
4
  pins, labels you render to images, waypoints. A marker keeps a constant on-screen size. It sits on
5
5
  the ground, re-snapping as finer terrain streams in, hides behind hills and buildings through the
6
6
  depth test, and can fade with distance. With `declutter: true` a pin whose on-screen footprint
7
- overlaps a more important one is hidden: higher `priority` first, then pins already on screen (so
8
- they do not flicker as the camera moves), then the nearest. The Earth view declutters its markers. They ignore the scene's fog, so distance haze never washes a
7
+ overlaps a more important one is hidden: higher `priority` first, then pins already on screen, then
8
+ the nearest. A pin on screen keeps its place until the inner part of its footprint is covered,
9
+ while a newcomer needs its whole footprint clear, so pins do not flicker as the camera moves. Pins
10
+ fade in and out over `fadeMs` (default 180; 0 pops), and a pin fading out no longer takes taps.
11
+ The Earth view declutters its markers. They ignore the scene's fog, so distance haze never washes a
9
12
  pin into a blank card; the layer's own `fade` handles distance. Markers are budgeted so the nearest or most important ones
10
13
  draw, and `pick(x, y)` resolves a click or tap to a marker id.
11
14
 
@@ -84,6 +84,7 @@ evidence across environments rather than a proof across JS engines; see
84
84
  - `outputs` maps PBR slots (baseColor, roughness, metalness, normal, emissive, ao) to node ids.
85
85
  - Cycles are a validation error naming the path.
86
86
  - Optional `alphaTest: 0.5` renders base-color RGBA alpha as cutout holes; ramps accept `#rrggbbaa`. Omitted graphs remain opaque. Cutouts write depth normally and do not use blended transparency.
87
+ - For fine porous surfaces, `alphaCoverage: true` uses mipmapped alpha blending. It preserves average open area when holes become smaller than a pixel, avoiding repeating interference bands. It requires `baseColor` and cannot be combined with `alphaTest`. Portable glTF graph fallbacks use the same standard `BLEND` mode. As with other transparent materials, intersecting layers need appropriate geometry grouping and sorting; review them from both sides.
87
88
 
88
89
  Bake and inspect:
89
90
 
@@ -48,7 +48,10 @@ zoom). Motion eases toward a goal, so every change feels smooth.
48
48
  `flyTo({ target, range, heading, pitch }, { durationMs })` animates to a framing. It rises
49
49
  mid-flight on long hops so the camera clears the scenery, and any direct input cancels it.
50
50
  `set(state)` jumps immediately, and `state` reads the current framing. The target settles onto the
51
- ground as finer terrain arrives, and the camera never dips below `minClearance`.
51
+ ground as finer terrain arrives, and the camera never dips below `minClearance`. `minRange` and
52
+ `maxRange` (default 20 m and 400 km) bound the distance; `setRangeLimits({ minRange, maxRange })`
53
+ changes them later, for example when the distance a scene draws changes, and a camera outside the
54
+ new limits eases back inside them. `rangeLimits` reads them.
52
55
 
53
56
  ## Fly
54
57
 
@@ -88,6 +88,11 @@ When enabled, sky lighting replaces `environment.ambient` and `environment.sun`.
88
88
  instead. Sunlight fades around the horizon; moonlight depends on altitude, phase and darkness.
89
89
  Only the Sun casts a sky shadow in phase 1. Shadows also require `environment.shadows` and
90
90
  scene geometry that casts/receives shadows; their local frustum follows the camera.
91
+ `renderer.setShadowQuality('off' | 'low' | 'medium' | 'high')` turns sun shadows on or off at a
92
+ map resolution without rebuilding the environment, and `renderer.setShadowFocus({ center,
93
+ radius })` aims them at a point in absolute world coordinates covering ±`radius` meters — for a
94
+ large world, what the camera frames rather than the camera itself. The box moves in whole
95
+ shadow-map texels so edges do not shimmer; `setShadowFocus(undefined)` restores the default.
91
96
  `sun.visible`/`moon.visible` control the disks independently of lighting. Use the corresponding
92
97
  light intensity to disable illumination. `sun.size` and `moon.size` are visual multipliers;
93
98
  the default 1 preserves real angular size. Larger values help stylized scenes and small displays.
@@ -99,7 +99,9 @@ await surfaces.setOptions({
99
99
  ## What is drawn
100
100
 
101
101
  - Modern streets use asphalt, exposed shoulder strips, curb/sidewalk bands, lane dividers, edge paint, stop
102
- bars and zebra crossings. Mapped paths are cut at same-grade carriageway edges, so footway
102
+ bars and zebra crossings. Shoulders, like the other street details, are drawn on the finest
103
+ detail tiles only: a few decimeters wide, they are below a pixel on the coarser tiles kilometers
104
+ away, where draping them segment by segment once cost more memory than the roads themselves. Mapped paths are cut at same-grade carriageway edges, so footway
103
105
  fills cannot compete with asphalt at walking height; paths beneath bridges remain continuous.
104
106
  Nearby nodes on divided roads form one junction; crossings follow
105
107
  the external approaches, and short turning links receive no independent crossings. Same-grade
@@ -176,7 +176,9 @@ movement trigger coherent grid-snapped rebases for every engine-owned object aut
176
176
 
177
177
  `terrainStreamBudgetForQuality('economy' | 'balanced' | 'high')` returns portable residency and
178
178
  concurrency budgets. `stream.stats()` reports decoded samples, geometry bytes, triangles, draw
179
- calls, instances, loading/failure counts, and evictions for live quality diagnostics.
179
+ calls, instances, loading/failure counts, and evictions for live quality diagnostics. It walks
180
+ every resident tile's objects to count them, so call it for diagnostics, not every frame:
181
+ `stream.loading()` (tiles and layers loading now) and `stream.pressure()` are constant-time.
180
182
 
181
183
  ## 4. Screenshot it headlessly
182
184
 
@@ -240,6 +242,48 @@ transport call `createTerrainArchiveSetArchive(urlOrDocument, { openArchive })`
240
242
  and `encodeTerrainArchiveSetPartitions` writes the run-length lists. Validate a set document with
241
243
  `molen validate archive-set.json`.
242
244
 
245
+ A set can instead (or as well) be partitioned by **geohash**. Each entry of `geohash` is a tier:
246
+ a band of levels with one archive per geohash cell of `precision` characters, named by a URL
247
+ template, and the `cells` that have an archive as a run-length list of geohash indices (the
248
+ cell's characters read as one base-32 number). Equal-angle cells match data organized by geohash
249
+ and give readable names; a whole planet can be stacked as a small base plus, say, two-character
250
+ cells for the middle levels and three-character cells (1.40625°, about 156 km at the equator)
251
+ for detail:
252
+
253
+ ```json
254
+ {
255
+ "format": "molen/archive-set@1",
256
+ "name": "world-elevation",
257
+ "tileType": "png",
258
+ "base": { "url": "base.pmtiles", "minLevel": 0, "maxLevel": 5 },
259
+ "archives": [],
260
+ "geohash": [
261
+ { "precision": 2, "minLevel": 6, "maxLevel": 8, "url": "g2/{cell}.pmtiles", "cells": "320-330" },
262
+ { "precision": 3, "minLevel": 9, "maxLevel": 13, "url": "g3/{cell}.pmtiles", "cells": "11331-11400" }
263
+ ]
264
+ }
265
+ ```
266
+
267
+ Geohash cells do not nest with Mercator tiles, so a tile belongs to the cell holding its center:
268
+ `terrainTileGeohash(level, x, y, precision)` in the kernel half is the rule, and producers must
269
+ place every tile by it (extra tiles in an archive are harmless). Cells not listed are never
270
+ requested, so open ocean costs nothing. `partitionLevel` is required only when `archives` is not
271
+ empty; tiers may not share levels with each other or the base. `encodeTerrainArchiveSetCells`
272
+ writes the `cells` list from geohashes, `terrainArchiveSetTierCells` expands it, and the kernel
273
+ exports the geohash helpers (`encodeGeohash`, `geohashIndex`, `geohashFromIndex`,
274
+ `geohashBounds`).
275
+
276
+ `openArchive(url, id, entry)` receives each member's `sha256` and `bytes` when the set lists them.
277
+ To keep tiles across visits, pass `cachingArchiveOpener(cache)` (`@bendyline/molen-terrain/client`)
278
+ over a `BlockCache` from `@bendyline/molen-pack/cache`. It keys each archive by its listed hash,
279
+ or by URL when none is listed, and reads repeated tiles from memory or IndexedDB. Without a host
280
+ archive, the package adapters open sources through an optional `transport` (`{ openArchive, fetch }`)
281
+ on `openTerrainPackageElevation`, `openTerrainPackagePyramid`, `openTerrainPackageSemantics` and the
282
+ stream factories. `openTerrainPackageArchive(source, baseUrl, { openArchive, fetch, id, entry })`
283
+ does the same for one source, and `terrainPackageArchiveEntry(pkg, source)` finds a single
284
+ archive's `files` record. The Earth view wires all of this from one `byteCache` option (see
285
+ [the Earth view](earth-view.md)).
286
+
243
287
  Compilers write package archives with the portable PMTiles v3 writer in
244
288
  `@bendyline/molen-terrain/kernel` (Node, Workers and browsers). `writePmtilesArchive(tiles,
245
289
  { tileType: 'png', bounds })` builds a whole archive in memory; for archives too large for memory,
@@ -295,15 +339,28 @@ function frame(position: [number, number, number]) {
295
339
 
296
340
  The selector measures projected source-sample spacing, adapts its error/range to the selected-tile
297
341
  budget, requests ancestors before descendants, and retains a displayed parent until all selected
298
- descendant coverage is resident. `stream.stats()` adds selected/displayed counts, effective
342
+ descendant coverage is resident. A selected tile that is not resident yet shows through its
343
+ nearest cached ancestor, except where finer ground is already on screen over it, which stays until
344
+ the tile arrives. When the warm cache has lost the intermediate levels, that ancestor can be far
345
+ coarser than the view; it stands in only if it would not hide detail on screen elsewhere, and
346
+ otherwise the new tile's patch waits briefly empty rather than the whole area dropping to the
347
+ coarse tile. `stream.stats()` adds selected/displayed counts, effective
299
348
  screen-space error, displayed-level range, and leaf fallback count. Quality presets set explicit
300
349
  error, view-distance, concurrency, selection, and residency budgets. Include `direction` and
301
350
  `aspect` in each view update to reject tiles safely outside a guarded horizontal camera cone while
302
- retaining direction-independent coarse coverage to the configured distance. In-flight surface
351
+ retaining direction-independent coarse coverage to the configured distance. `peripheralDegrees`
352
+ widens that cone for ground only: tiles up to that many degrees past it stay selected at reduced
353
+ detail (`peripheralDetail`, default 0.4, weighs their error) as bare terrain, without layers, so
354
+ turning the camera reveals ground that is already there; layers build once the tile is in view. In-flight surface
303
355
  requests finish into a bounded warm cache instead of being restarted on every small camera turn;
304
356
  hidden cached tiles are evicted only when capacity is needed. Sparse descendants also share a
305
357
  bounded decoded-ancestor cache, avoiding repeated PNG decode/resample work while panning.
306
358
 
359
+ With `shadows: true` every tile surface and layer mesh receives sun shadows, and layer meshes
360
+ taller than `shadowCasterHeight` (default 1.5 m: buildings, trees, landmarks) cast them. A layer
361
+ marks draped parts with `userData.shadowCaster = false` (inherited by their children; landcover,
362
+ water and road surfaces are marked) and water with `userData.shadowReceiver = false`.
363
+
307
364
  `TerrainPyramidTileLayer` provides the same classification/hydrology/human-feature lifecycle over
308
365
  adaptive tiles. Its optional inclusive `minLevel`/`maxLevel` bounds keep expensive decoration off
309
366
  coarse fallback and horizon tiles. Layer objects become visible only with their selected surface,
@@ -362,6 +419,39 @@ ancestors, since one ancestor serves up to four children at a time. Layers creat
362
419
  `createTerrainPackageSemanticLayers` then reach the package's `maxLevel`; pass `overzoom: false`
363
420
  to stop them at the sidecar's levels.
364
421
 
422
+ Basemaps also generalize buildings below their last zoom: Protomaps keeps almost no footprints
423
+ below zoom 15, so a zoom-13 or zoom-14 feature tile shows streets and trees but no houses. A
424
+ package can carry that last zoom separately, often only near where people look, as a building
425
+ detail sidecar:
426
+
427
+ ```json
428
+ "features": {
429
+ "source": { "kind": "pmtiles-set", "url": "https://tiles.example/archive-set.json" },
430
+ "encoding": "mvt",
431
+ "layers": ["water", "transportation", "building", "poi"],
432
+ "profile": "protomaps-basemap@1",
433
+ "buildingDetail": {
434
+ "source": { "kind": "pmtiles-set", "url": "https://tiles.example/hd/archive-set.json" },
435
+ "level": 15
436
+ }
437
+ }
438
+ ```
439
+
440
+ The human-feature layer then takes its buildings and places from the detail level for tiles up to
441
+ two levels coarser (`buildingDetail: { maxDepth }` on `createTerrainPackageSemanticLayers`, or
442
+ `false` to keep the generalized footprints); roads, water and land use stay as the feature tiles
443
+ have them. `composeTerrainBuildingDetail` assembles a coarser tile from its detail descendants
444
+ (4 or 16 tiles): a footprint seen by several descendants is matched by its source id and its
445
+ clipped copies are unioned, so each building appears once, whole, cut exactly where a real tile
446
+ at the coarser level with a proportionally narrower buffer would cut it. `buildingSourceLevel` on
447
+ the composed tile tells renderers that narrower buffer, so tile-edge ownership still agrees between
448
+ neighbours. Descendants the archive lacks keep the coarse tile's buildings in their part of the
449
+ tile. `createBuildingDetailTerrainSemanticSource` wraps any feature source this way and keeps
450
+ recently loaded detail tiles, since a tile and its children share them. Only the `building` and
451
+ `poi` layers of detail tiles are decoded. The detail archive is optional: if it cannot be opened,
452
+ `openTerrainPackageSemantics` reports `buildingDetailError` and the feature tiles carry on alone.
453
+ Hosts with their own transport pass `buildingDetailArchive`.
454
+
365
455
  The package elevation pyramid may be sparse. `createTerrainPackagePyramidHeightSource` walks to the
366
456
  nearest declared ancestor when an exact tile is absent, then crops and resamples that ancestor into
367
457
  the requested tile bounds. This supports broad coarse coverage plus a small regional detail window
@@ -329,22 +329,35 @@ Containment is a spatial inference because stock Protomaps does not publish pare
329
329
 
330
330
  ## 8. Budgets and quality
331
331
 
332
- `worldgenTileBudgetForQuality(quality, levelBelowMax)` caps buildings and vertices per tile.
333
- Building batches reserve simple architecture before allocating extra detail to the largest
334
- footprints. The budget fallback preserves the authored footprint, roof shape, and (where the
335
- active style tier permits them) up to three window columns and two rows per wall, using shared
336
- vertex-colored materials during reservation. Eligible simplified buildings recover their shared
337
- textures when material groups fit, even if no geometric detail fits. High admits 24 material
338
- groups at the finest level, including flat fallback slots. The fallback omits raised window
339
- surrounds, trim bands, overhangs, separate foundation meshes, and roof
340
- props. Simplified and coarse buildings extend their walls below the lowest sampled ground,
341
- keeping roofs and windows level without gaps on downhill sides or extra vertices and draw calls.
342
- Box fallbacks do the same; intentionally elevated `minHeight` parts retain their clearance.
343
- `detailedCount` limits eligibility for extra detail; it no longer turns all later buildings into
344
- boxes. Vertex and material-group caps still apply, with boxes used when the simple geometry
345
- cannot fit or the requested tier is beyond the style's last tier. Buildings beyond
346
- `maxBuildings` are still omitted. Quality and detail remain tile-based, not camera-distance
347
- updates per building.
332
+ `worldgenTileBudgetForQuality(quality, levelBelowMax)` caps buildings and vertices per tile. The
333
+ numbers are sized for real footprints: a zoom-15 suburb puts 800 to 1,600 houses in a zoom-14
334
+ tile, and a downtown about 1,700 footprints and parts.
335
+
336
+ A batch spends its budget in priority order, largest footprints first. First every building gets
337
+ walls and its roof shape (the style's coarsest tier); only when even that does not fit does a
338
+ building become an instanced stand-in. Then buildings gain a simplified facade while it fits, then
339
+ the largest (`detailedCount`) gain full detail. The simplified facade preserves the authored
340
+ footprint, roof shape and, where the active style tier permits them, a window on every floor:
341
+ walls with up to three bays keep their real windows, and longer walls draw each floor's punched or
342
+ grid windows as one strip whose window texture repeats once per bay, four vertices a floor and
343
+ wall. It uses shared vertex-colored materials during reservation; eligible simplified buildings
344
+ recover their shared textures when material groups fit, even if no geometric detail fits. Interior
345
+ openings come with full detail only: cut into every budget facade they would cost a crowded
346
+ neighbourhood its windows. High admits 24 material groups at the finest level, including flat
347
+ fallback slots. The fallback omits raised window surrounds, trim bands, overhangs, separate
348
+ foundation meshes, and roof props. Simplified and coarse buildings extend their walls below the
349
+ lowest sampled ground, keeping roofs and windows level without gaps on downhill sides or extra
350
+ vertices and draw calls. Stand-ins do the same; intentionally elevated `minHeight` parts retain
351
+ their clearance.
352
+
353
+ Stand-ins are instanced: `builtin:box` for flat-roofed buildings, and `builtin:box.gable` (set
354
+ `buildings:box.gable`) for pitched ones, a box whose walls stop at the eave (`GABLE_BOX_EAVE` of
355
+ its height) under a roof ridged along its longer side, the roof shaded darker than the walls. From
356
+ the air a neighbourhood of stand-ins still reads as roofs. `buildingBoxGeometry(modelRef)` returns
357
+ the shared geometry for either. Buildings beyond `maxBuildings` are still omitted. Quality and
358
+ detail remain tile-based, not camera-distance updates per building. `worldgenBuildingCellSize`
359
+ batches the finest level's buildings into 512 m cells and coarser levels' into 1024 m cells, since
360
+ each cell is a draw.
348
361
 
349
362
  Generation is cooperative: the renderer yields between chunks of both reservation and detail
350
363
  work, and aborts when a tile is evicted. The explorer HUD reports buildings, boxes, and generation
@@ -353,7 +366,7 @@ time per tile.
353
366
  Detail tiers come from the level below the finest (tier 0 at the finest level, 1 one level
354
367
  below, ...) plus one at economy quality. A style's `lod.tiers` say which features survive each
355
368
  tier: roof shape, roof features, facade windows, facade bands, props; beyond the last tier the
356
- building is a tinted box. `maxMaterialGroups` caps the mesh groups (draw calls) of one batch:
369
+ building is a stand-in. `maxMaterialGroups` caps the mesh groups (draw calls) of one batch:
357
370
  once a batch would exceed it, later buildings render their textured parts as vertex colors
358
371
  (`stats.materialsCollapsed`), so the largest buildings keep their textures first.
359
372
 
@@ -1,6 +1,6 @@
1
1
  # Archive set (`molen/archive-set@1`)
2
2
 
3
- One tile pyramid split across PMTiles archives: a coarse base plus detail archives partitioned by the tile at a fixed level.
3
+ One tile pyramid split across PMTiles archives: a coarse base plus detail archives partitioned by the tile at a fixed level or by geohash cell.
4
4
 
5
5
  ## Example
6
6
 
@@ -56,7 +56,7 @@ One tile pyramid split across PMTiles archives: a coarse base plus detail archiv
56
56
  "type": "integer",
57
57
  "minimum": 0,
58
58
  "maximum": 10,
59
- "description": "Level whose tiles partition the detail archives; a detail tile belongs to the archive listing its ancestor at this level."
59
+ "description": "Level whose tiles partition the detail archives; a detail tile belongs to the archive listing its ancestor at this level. Required when archives is not empty."
60
60
  },
61
61
  "base": {
62
62
  "type": "object",
@@ -161,13 +161,58 @@ One tile pyramid split across PMTiles archives: a coarse base plus detail archiv
161
161
  "additionalProperties": false
162
162
  },
163
163
  "description": "Detail archives, each owning a disjoint set of partition cells."
164
+ },
165
+ "geohash": {
166
+ "type": "array",
167
+ "items": {
168
+ "type": "object",
169
+ "properties": {
170
+ "precision": {
171
+ "type": "integer",
172
+ "minimum": 1,
173
+ "maximum": 6,
174
+ "description": "Geohash length of a cell (3: 1.40625° square, about 156 km at the equator)."
175
+ },
176
+ "minLevel": {
177
+ "type": "integer",
178
+ "minimum": 0,
179
+ "maximum": 30,
180
+ "description": "Coarsest level the tier serves."
181
+ },
182
+ "maxLevel": {
183
+ "type": "integer",
184
+ "minimum": 0,
185
+ "maximum": 30,
186
+ "description": "Finest level the tier serves."
187
+ },
188
+ "url": {
189
+ "type": "string",
190
+ "minLength": 1,
191
+ "pattern": "\\{cell\\}",
192
+ "description": "Archive URL template, relative to this document or absolute; {cell} becomes the cell geohash."
193
+ },
194
+ "cells": {
195
+ "type": "string",
196
+ "pattern": "^(\\d+(-\\d+)?(,\\d+(-\\d+)?)*)?$",
197
+ "description": "Run-length list of the cells that have an archive, as geohash indices (the characters read as one base-32 number)."
198
+ }
199
+ },
200
+ "required": [
201
+ "precision",
202
+ "minLevel",
203
+ "maxLevel",
204
+ "url",
205
+ "cells"
206
+ ],
207
+ "additionalProperties": false
208
+ },
209
+ "description": "Geohash-partitioned tiers: per band of levels, one archive per cell; a tile belongs to the cell holding its center."
164
210
  }
165
211
  },
166
212
  "required": [
167
213
  "format",
168
214
  "name",
169
215
  "tileType",
170
- "partitionLevel",
171
216
  "archives"
172
217
  ],
173
218
  "additionalProperties": false
@@ -62,6 +62,10 @@ A small node graph (noise, gradients, ramps, blends) CPU-rasterized to textures.
62
62
  "const": "molen/matgraph@1",
63
63
  "description": "Format envelope; always 'molen/matgraph@1'."
64
64
  },
65
+ "alphaCoverage": {
66
+ "description": "Filter baseColor alpha as fractional surface coverage for porous surfaces. Uses mipmapped alpha blending; requires baseColor and excludes alphaTest. Like portable glTF BLEND, overlapping transparent surfaces require sorting.",
67
+ "type": "boolean"
68
+ },
65
69
  "alphaTest": {
66
70
  "description": "Optional alpha cutout threshold for baseColor RGBA. Omit for opaque materials; this does not enable blended transparency.",
67
71
  "type": "number",
@@ -217,6 +217,9 @@ WGS84 anchors for authored models; draft entries are indexed but not rendered.
217
217
  "items": false,
218
218
  "minItems": 2,
219
219
  "maxItems": 2
220
+ },
221
+ "includeConnectedApproaches": {
222
+ "type": "boolean"
220
223
  }
221
224
  },
222
225
  "required": [