@bendyline/molen-client 0.0.15 → 0.0.16

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.
@@ -1,4 +1,4 @@
1
- import { n as CameraPose } from "./renderer-4kSVioiH.mjs";
1
+ import { n as CameraPose } from "./renderer-Scr1Mz0g.mjs";
2
2
 
3
3
  //#region src/camera-track.d.ts
4
4
  interface CameraTrackKeyframe {
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { a as readModelSignals, n as ModelSignals, r as createModelSignalVisual, t as ModelSignalVisual } from "./model-signals-BpeXhsim.mjs";
2
2
  import { a as createUrlAssetProvider, i as UrlAssetProviderOptions, n as AssetProvider, r as LoadedGltf, t as AssetCache } from "./assets-IbO4GJpF.mjs";
3
- import { A as SkyReflectionFilter, C as SkyVisualOptions, D as evaluateEarthSky, E as EarthSkyState, F as AdmissionOptions, I as AdmissionSample, L as FrameAdmissionOptions, M as SkyReflections, N as createWebGlSkyReflectionFilter, O as skyTimeMs, P as reflectionStateFromLights, R as FrameAdmissionQueue, S as SkyVisual, T as CelestialPosition, _ as WeatherVisual, a as RendererBackendPreference, b as SkyFrame, c as TopDownOrtho, d as ShadowFocus, f as ShadowQuality, g as FarShadowInfo, h as createGpuFrameTimer, i as RendererBackend, j as SkyReflectionState, k as starDirection, l as nextWorldOrigin, m as GpuFrameTimerOptions, n as CameraPose, o as RendererOptions, p as GpuFrameTimer, r as Renderer, s as ThreeRenderer, t as AutoWorldOriginOptions, u as orthoFrustum, v as WeatherVisualOptions, w as defaultSkyPalette, x as SkyStar, y as CloudQuality, z as SceneAdmission } from "./renderer-4kSVioiH.mjs";
3
+ import { A as SkyReflectionFilter, B as SceneAdmission, C as SkyVisualOptions, D as evaluateEarthSky, E as EarthSkyState, F as AdmissionBacklog, I as AdmissionOptions, L as AdmissionSample, M as SkyReflections, N as createWebGlSkyReflectionFilter, O as skyTimeMs, P as reflectionStateFromLights, R as FrameAdmissionOptions, S as SkyVisual, T as CelestialPosition, _ as WeatherVisual, a as RendererBackendPreference, b as SkyFrame, c as TopDownOrtho, d as ShadowFocus, f as ShadowQuality, g as FarShadowInfo, h as createGpuFrameTimer, i as RendererBackend, j as SkyReflectionState, k as starDirection, l as nextWorldOrigin, m as GpuFrameTimerOptions, n as CameraPose, o as RendererOptions, p as GpuFrameTimer, r as Renderer, s as ThreeRenderer, t as AutoWorldOriginOptions, u as orthoFrustum, v as WeatherVisualOptions, w as defaultSkyPalette, x as SkyStar, y as CloudQuality, z as FrameAdmissionQueue } from "./renderer-Scr1Mz0g.mjs";
4
4
  import { a as normalizeInputAxis, i as InputMapOptions, n as InputGamepad, o as resolveAction, r as InputMap, t as InputBindings } from "./input-Ckev_Kvj.mjs";
5
- import { a as isInstanceBatch, i as InstanceMatrixAttribute, n as INSTANCE_BATCH_MATRIX_COLUMNS, o as isInstanceBatchGeometry, r as InstanceBatch, t as INSTANCE_BATCH_COLOR } from "./instance-batch-CO4YD6rd.mjs";
5
+ import { a as expandRenderBounds, c as INSTANCE_BATCH_COLOR, d as InstanceMatrixAttribute, f as isInstanceBatch, i as boxOutsideView, l as INSTANCE_BATCH_MATRIX_COLUMNS, n as RENDER_BOUNDS_STALE, o as markRenderBoundsChanged, p as isInstanceBatchGeometry, r as RENDER_MATRICES_STALE, s as viewProjection, t as RENDER_BOUNDS, u as InstanceBatch } from "./render-bounds-B4yQoiYR.mjs";
6
6
  import { CloudType, Command, ControlAction, CustomSkyData, Delta, DiagMessage, EarthObserver, EarthSkyData, EngineEvent, EntityId, GlassData, GlassStateData, JsonObject, JsonValue, Keyframe, LiveryData, LiveryGraphic, MessageLink, ModelSignalSpec, Quat, ResolvedWeather, SceneCamera, SceneInput, SceneManifest, SkyAppearance, SkyBodyData, SkyData, SkyData as SkyData$1, SkyPalette, SkyTime, Vec3, WeatherData, WeatherProfile, resolveWeather, weatherProfile } from "@bendyline/molen-schema";
7
7
  import * as THREE from "three";
8
8
  import { Intersection, Object3D } from "three";
@@ -57,6 +57,14 @@ interface AdaptiveQualitySample {
57
57
  /** Estimated resident working set / memory budget. Values above one lower detail. */
58
58
  memoryPressure?: number;
59
59
  /**
60
+ * The host's view is still arriving (a first mount, a jump to a new place): slow frames and
61
+ * stalls are that arrival, not the level's cost. A step now would rebuild what is half loaded at
62
+ * another level and start the wait again, so frame time neither lowers nor raises detail while
63
+ * it is set; memory pressure, and measured GPU time over twice the frame budget, still lower it. Hosts clear it once the view has loaded, or after
64
+ * a bound of their own, so a device that cannot afford the level still steps down afterwards.
65
+ */
66
+ settling?: boolean;
67
+ /**
60
68
  * The level asks for more than streaming can hold or deliver, by the host's own measure: tiles
61
69
  * rebuilt after eviction, a view that crowds its cache. Frame times do not show this (the work
62
70
  * runs outside the frame), so a level can look affordable while it never finishes loading.
@@ -115,6 +123,7 @@ declare class AdaptiveQualityController {
115
123
  private overloadMs;
116
124
  private headroomMs;
117
125
  private loading;
126
+ private settling;
118
127
  private cpuTotalMs;
119
128
  private cpuSamples;
120
129
  private gpuTotalMs;
@@ -909,4 +918,4 @@ declare const defaultEnvironment: EnvironmentData;
909
918
  */
910
919
  declare function applyEnvironment(renderer: Renderer, env: EnvironmentData): void;
911
920
  //#endregion
912
- export { type AdaptiveQualityChange, AdaptiveQualityController, type AdaptiveQualityOptions, type AdaptiveQualityReason, type AdaptiveQualitySample, type AdaptiveQualityStats, type AdmissionOptions, type AdmissionSample, AssetCache, type AssetOptions, type AssetProvider, type AutoWorldOriginOptions, type CameraPose, type CameraTarget, type CelestialPosition, type ClientCore, type ClientCoreOptions, type ClientDiagCode, type ClientError, type ClientOptions, type CloudQuality, type CloudType, type CustomSkyData, type DecoderConfig, type EarthObserver, type EarthSkyData, type EarthSkyState, type EnvironmentData, type FarShadowInfo, type FrameAdmissionOptions, FrameAdmissionQueue, type GpuFrameTimer, type GpuFrameTimerOptions, INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, type InputBindings, type InputGamepad, InputMap, type InputMapOptions, type InputRuleOptions, InstanceBatch, InstanceMatrixAttribute, type InterpTransform, InterpolationBuffer, type KindContext, type KindHandle, type KindView, type LightData, type LiveryVisual, type LoadedGltf, MaterialResolver, type MirrorReader, type ModelSignalVisual, type ModelSignals, type MolenClient, type MountExperienceOptions, type MountedExperience, type Renderable, type RenderableKind, Renderer, type RendererBackend, type RendererBackendPreference, type RendererOptions, type ResolvedWeather, type SceneAdmission, type SceneBackend, SceneMirror, type SceneOptimizationOptions, type ShadowFocus, type ShadowQuality, type SkyAppearance, type SkyBodyData, type SkyData, type SkyFrame, type SkyPalette, type SkyReflectionFilter, type SkyReflectionState, SkyReflections, type SkyStar, type SkyTime, SkyVisual, type SkyVisualOptions, type StarCatalogRow, type StaticBatchOptions, THREE, type ThreeRenderer, ThreeSceneBackend, type TopDownOrtho, type Unsubscribe, type UrlAssetProviderOptions, type WeatherData, type WeatherProfile, WeatherVisual, type WeatherVisualOptions, applyEnvironment, applyInputRules, applyLivery, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, isInstanceBatch, isInstanceBatchGeometry, lerp3, liveryGraphicTexture, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };
921
+ export { type AdaptiveQualityChange, AdaptiveQualityController, type AdaptiveQualityOptions, type AdaptiveQualityReason, type AdaptiveQualitySample, type AdaptiveQualityStats, type AdmissionBacklog, type AdmissionOptions, type AdmissionSample, AssetCache, type AssetOptions, type AssetProvider, type AutoWorldOriginOptions, type CameraPose, type CameraTarget, type CelestialPosition, type ClientCore, type ClientCoreOptions, type ClientDiagCode, type ClientError, type ClientOptions, type CloudQuality, type CloudType, type CustomSkyData, type DecoderConfig, type EarthObserver, type EarthSkyData, type EarthSkyState, type EnvironmentData, type FarShadowInfo, type FrameAdmissionOptions, FrameAdmissionQueue, type GpuFrameTimer, type GpuFrameTimerOptions, INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, type InputBindings, type InputGamepad, InputMap, type InputMapOptions, type InputRuleOptions, InstanceBatch, InstanceMatrixAttribute, type InterpTransform, InterpolationBuffer, type KindContext, type KindHandle, type KindView, type LightData, type LiveryVisual, type LoadedGltf, MaterialResolver, type MirrorReader, type ModelSignalVisual, type ModelSignals, type MolenClient, type MountExperienceOptions, type MountedExperience, RENDER_BOUNDS, RENDER_BOUNDS_STALE, RENDER_MATRICES_STALE, type Renderable, type RenderableKind, Renderer, type RendererBackend, type RendererBackendPreference, type RendererOptions, type ResolvedWeather, type SceneAdmission, type SceneBackend, SceneMirror, type SceneOptimizationOptions, type ShadowFocus, type ShadowQuality, type SkyAppearance, type SkyBodyData, type SkyData, type SkyFrame, type SkyPalette, type SkyReflectionFilter, type SkyReflectionState, SkyReflections, type SkyStar, type SkyTime, SkyVisual, type SkyVisualOptions, type StarCatalogRow, type StaticBatchOptions, THREE, type ThreeRenderer, ThreeSceneBackend, type TopDownOrtho, type Unsubscribe, type UrlAssetProviderOptions, type WeatherData, type WeatherProfile, WeatherVisual, type WeatherVisualOptions, applyEnvironment, applyInputRules, applyLivery, applySceneCamera, boxOutsideView, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, expandRenderBounds, followCameraPose, isInstanceBatch, isInstanceBatchGeometry, lerp3, liveryGraphicTexture, localCommand, markRenderBoundsChanged, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, viewProjection, weatherProfile };
package/dist/index.mjs CHANGED
@@ -5,6 +5,7 @@ import { createGlassVisual } from "./glass.mjs";
5
5
  import { n as liveryGraphicTexture, t as applyLivery } from "./livery-qcDLzbU9.mjs";
6
6
  import { a as cloudShellGeometry, i as cloudQualitySettings, n as CloudUniforms, o as createWebGlCloudMaterial, r as cloudDeckGeometry, s as cloudNoise, t as CloudTextures } from "./clouds-DmASLVoe.mjs";
7
7
  import { a as createSnowCoverUniforms, f as writeSnowCover, s as injectSnowCover } from "./snow-cover-Bh0woabf.mjs";
8
+ import { a as expandRenderBounds, i as boxOutsideView, n as RENDER_BOUNDS_STALE, o as markRenderBoundsChanged, r as RENDER_MATRICES_STALE, s as viewProjection, t as RENDER_BOUNDS } from "./render-bounds-uRp_yPp6.mjs";
8
9
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
9
10
  import { a as isInstanceBatch, i as InstanceMatrixAttribute, n as INSTANCE_BATCH_MATRIX_COLUMNS, o as isInstanceBatchGeometry, r as InstanceBatch, t as INSTANCE_BATCH_COLOR } from "./instance-batch-Ds-oKQW4.mjs";
10
11
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
@@ -54,6 +55,7 @@ var AdaptiveQualityController = class {
54
55
  overloadMs = 0;
55
56
  headroomMs = 0;
56
57
  loading = false;
58
+ settling = false;
57
59
  cpuTotalMs = 0;
58
60
  cpuSamples = 0;
59
61
  gpuTotalMs = 0;
@@ -100,7 +102,7 @@ var AdaptiveQualityController = class {
100
102
  this.lastPauseMs = this.clockMs;
101
103
  this.resetMeasurements();
102
104
  this.previousPause = true;
103
- if (repeated && this.level > this.minLevel) {
105
+ if (repeated && this.level > this.minLevel && sample.settling !== true) {
104
106
  this.lastPauseMs = Number.NEGATIVE_INFINITY;
105
107
  return this.change(this.level - 1, "frame-time");
106
108
  }
@@ -114,6 +116,7 @@ var AdaptiveQualityController = class {
114
116
  if (this.frames.length < 512) this.frames.push(elapsed);
115
117
  else this.frames[this.frameCursor++ % 512] = elapsed;
116
118
  this.loading ||= sample.loading === true;
119
+ this.settling ||= sample.settling === true;
117
120
  this.strained ||= sample.strained === true;
118
121
  if (Number.isFinite(sample.cpuFrameMs) && (sample.cpuFrameMs ?? 0) > 0) {
119
122
  this.cpuTotalMs += sample.cpuFrameMs ?? 0;
@@ -173,16 +176,19 @@ var AdaptiveQualityController = class {
173
176
  this.slowFrameRatio = ordered.filter((value) => value > this.targetFrameMs * 1.25).length / ordered.length;
174
177
  this.samples = ordered.length;
175
178
  const memory = this.memorySamples > 0 ? this.memoryTotal / this.memorySamples : 0;
176
- const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0);
179
+ const gpuWork = this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0;
180
+ const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, gpuWork);
177
181
  const measured = this.cpuSamples > 0 || this.gpuSamples > 0;
178
182
  const measuredBoth = this.cpuSamples > 0 && this.gpuSamples > 0;
179
183
  const loading = this.loading;
184
+ const settling = this.settling;
180
185
  const strained = this.strained;
181
186
  this.resetWindow();
182
187
  const overloaded = mean > this.targetFrameMs * 1.18 || this.p90FrameMs > this.targetFrameMs * 1.5 && this.slowFrameRatio >= .25;
183
- const headroom = (!loading || measuredBoth) && !strained && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * this.upgradeWorkFraction;
188
+ const headroom = !settling && (!loading || measuredBoth) && !strained && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * this.upgradeWorkFraction;
184
189
  const renderBound = !loading || !measured || work > this.targetFrameMs * .75;
185
- this.overloadMs = overloaded && renderBound ? this.overloadMs + elapsed : 0;
190
+ const gpuBound = gpuWork > this.targetFrameMs * 2;
191
+ this.overloadMs = overloaded && renderBound && (!settling || gpuBound) ? this.overloadMs + elapsed : 0;
186
192
  this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
187
193
  this.strainMs = strained ? this.strainMs + elapsed : 0;
188
194
  if (this.warmupElapsedMs < this.warmupMs) return;
@@ -218,6 +224,7 @@ var AdaptiveQualityController = class {
218
224
  this.frameCursor = 0;
219
225
  this.windowMs = 0;
220
226
  this.loading = false;
227
+ this.settling = false;
221
228
  this.strained = false;
222
229
  this.cpuTotalMs = 0;
223
230
  this.cpuSamples = 0;
@@ -2498,6 +2505,7 @@ var FrameAdmissionQueue = class {
2498
2505
  maxMs;
2499
2506
  maxBytes;
2500
2507
  maxJobs;
2508
+ backlog;
2501
2509
  urgentStreak = 0;
2502
2510
  orderedStreak = 0;
2503
2511
  /** Jobs from the other lanes since the background lane last ran one. */
@@ -2516,14 +2524,16 @@ var FrameAdmissionQueue = class {
2516
2524
  this.maxMs = options.maxMilliseconds ?? 2;
2517
2525
  this.maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
2518
2526
  this.maxJobs = options.maxJobs ?? 32;
2527
+ this.backlog = void 0;
2519
2528
  this.backgroundWaitMs = options.backgroundWaitMs ?? 750;
2520
2529
  this.backgroundShare = options.backgroundShare ?? 8;
2521
2530
  if (!(this.backgroundWaitMs >= 0) || !(this.backgroundShare >= 1)) throw new RangeError("Background admission needs a nonnegative wait and a share of 1 or more");
2522
- this.setLimits({});
2531
+ this.setLimits({ backlog: options.backlog });
2523
2532
  }
2524
2533
  /**
2525
2534
  * Change the per-frame budget from the next frame on; omitted limits keep their values. A host
2526
- * can admit more when frames have time to spare (an adaptive quality tier, say).
2535
+ * can admit more when frames have time to spare (an adaptive quality tier, say). `backlog` is
2536
+ * replaced when the key is present: `undefined` takes the backlog budget away.
2527
2537
  */
2528
2538
  setLimits(limits) {
2529
2539
  const next = [
@@ -2532,7 +2542,26 @@ var FrameAdmissionQueue = class {
2532
2542
  limits.maxJobs ?? this.maxJobs
2533
2543
  ];
2534
2544
  if (!next.every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2545
+ const backlog = "backlog" in limits ? limits.backlog : this.backlog;
2546
+ if (backlog !== void 0 && (!(Number.isFinite(backlog.afterMs) && backlog.afterMs > 0) || ![backlog.maxMilliseconds, backlog.maxBytes].every((v) => v === void 0 || Number.isFinite(v) && v > 0))) throw new RangeError("A backlog budget needs a positive wait and positive limits");
2535
2547
  [this.maxMs, this.maxBytes, this.maxJobs] = next;
2548
+ this.backlog = backlog === void 0 ? void 0 : { ...backlog };
2549
+ }
2550
+ /**
2551
+ * How far into its backlog budget the queue is, 0 to 1: by how long the oldest job outside the
2552
+ * background lane has waited. Urgent jobs sit ahead of the others, each kind in arrival order
2553
+ * but for the ordered jobs taken from among them, so the oldest is the first of either kind.
2554
+ */
2555
+ pressure(now) {
2556
+ const backlog = this.backlog;
2557
+ const first = this.jobs[0];
2558
+ if (backlog === void 0 || first === void 0) return 0;
2559
+ let oldest = first.queued;
2560
+ if (first.options.priority === "urgent") {
2561
+ const normal = this.jobs.find((job) => job.options.priority !== "urgent");
2562
+ if (normal !== void 0 && normal.queued < oldest) oldest = normal.queued;
2563
+ }
2564
+ return Math.max(0, Math.min(1, (now - oldest - backlog.afterMs) / backlog.afterMs));
2536
2565
  }
2537
2566
  run(task, options = {}) {
2538
2567
  if (this.disposed || options.signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
@@ -2631,9 +2660,13 @@ var FrameAdmissionQueue = class {
2631
2660
  flush() {
2632
2661
  if (this.disposed || this.paused) return;
2633
2662
  const sinceLast = this.lastFlushEnd === void 0 ? 0 : this.clock() - this.lastFlushEnd;
2634
- const budget = this.frameBudget(sinceLast);
2663
+ const pressure = this.pressure(this.clock());
2664
+ const grown = (base, most) => most !== void 0 && most > base ? base + (most - base) * pressure : base;
2665
+ const maxMs = grown(this.maxMs, this.backlog?.maxMilliseconds);
2666
+ const maxBytes = grown(this.maxBytes, this.backlog?.maxBytes);
2667
+ const budget = this.frameBudget(sinceLast, maxMs);
2635
2668
  if (this.overrunMs > 0) {
2636
- const repaid = Math.max(this.maxMs, sinceLast * this.maxMs / NOMINAL_FRAME_MS);
2669
+ const repaid = Math.max(maxMs, sinceLast * maxMs / NOMINAL_FRAME_MS);
2637
2670
  this.overrunMs = Math.max(0, this.overrunMs - repaid);
2638
2671
  this.lastFlushEnd = this.clock();
2639
2672
  this.continuing = this.pending > 0;
@@ -2661,7 +2694,7 @@ var FrameAdmissionQueue = class {
2661
2694
  if (next === void 0) break;
2662
2695
  const cost = next.options.bytes ?? 0;
2663
2696
  const label = next.options.label ?? "admission";
2664
- if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > budget || bytes + cost > this.maxBytes)) break;
2697
+ if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > budget || bytes + cost > maxBytes)) break;
2665
2698
  lane.splice(index, 1);
2666
2699
  this.forget(next);
2667
2700
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
@@ -2698,18 +2731,19 @@ var FrameAdmissionQueue = class {
2698
2731
  this.request();
2699
2732
  }
2700
2733
  /**
2701
- * This frame's work allowance: the fixed budget, or for sustained software-rendering frames the
2702
- * same share of the shortest recent one. One long frame (a hitch) changes nothing.
2734
+ * This frame's work allowance: the budget (`maxMs`, the ordinary one or what a backlog has grown
2735
+ * it to), or for sustained software-rendering frames the same share of the shortest recent one.
2736
+ * One long frame (a hitch) changes nothing.
2703
2737
  */
2704
- frameBudget(sinceLast) {
2738
+ frameBudget(sinceLast, maxMs) {
2705
2739
  if (!this.continuing) this.recentFrames.length = 0;
2706
2740
  else {
2707
2741
  this.recentFrames.push(sinceLast);
2708
2742
  if (this.recentFrames.length > SLOW_FRAMES) this.recentFrames.shift();
2709
2743
  }
2710
- if (this.recentFrames.length < SLOW_FRAMES) return this.maxMs;
2744
+ if (this.recentFrames.length < SLOW_FRAMES) return maxMs;
2711
2745
  const shortest = Math.min(...this.recentFrames);
2712
- return shortest >= SLOW_FRAME_MS ? Math.max(this.maxMs, shortest * this.maxMs / NOMINAL_FRAME_MS) : this.maxMs;
2746
+ return shortest >= SLOW_FRAME_MS ? Math.max(maxMs, shortest * maxMs / NOMINAL_FRAME_MS) : maxMs;
2713
2747
  }
2714
2748
  dispose() {
2715
2749
  this.disposed = true;
@@ -4370,6 +4404,44 @@ function reflectionStateFromLights(ambient, sun, background, clouds) {
4370
4404
  }
4371
4405
  //#endregion
4372
4406
  //#region src/three/renderer.ts
4407
+ /** Renderer strings of the software rasterizers browsers fall back to (see softwareRasterizer). */
4408
+ const SOFTWARE_RASTERIZER = /swiftshader|llvmpipe|softpipe|lavapipe|basic render driver/i;
4409
+ /** How long the lights gathered for warm-up builds stand, ms (see `sceneLights`). */
4410
+ const LIGHTS_REFRESH_MS = 250;
4411
+ /** How often a group seen only by a shadow map has its levels of detail chosen again, ms. */
4412
+ const SHADOW_LOD_MS = 500;
4413
+ const cullMatrix = new THREE.Matrix4();
4414
+ const cullBox = new THREE.Box3();
4415
+ /** Frames (render groups' parents) whose world matrix a culling pass has brought up to date. */
4416
+ const cullFrames = /* @__PURE__ */ new WeakMap();
4417
+ let cullPass = 0;
4418
+ /** Whether `group` is under `scene`: a group its owner has detached keeps its parent. */
4419
+ function groupInScene(group, scene) {
4420
+ for (let cursor = group.parent; cursor !== null; cursor = cursor.parent) if (cursor === scene) return true;
4421
+ return false;
4422
+ }
4423
+ /** A WebGPU adapter that rasterizes on the CPU, by its own flag or its description. */
4424
+ function softwareAdapter(adapter) {
4425
+ const legacy = adapter;
4426
+ const info = adapter.info;
4427
+ const described = [
4428
+ info?.vendor,
4429
+ info?.architecture,
4430
+ info?.device,
4431
+ info?.description
4432
+ ].filter((part) => typeof part === "string").join(" ");
4433
+ return legacy.isFallbackAdapter === true || info?.isFallbackAdapter === true || SOFTWARE_RASTERIZER.test(described);
4434
+ }
4435
+ /** A WebGL context drawn by a software rasterizer, by its unmasked renderer string when exposed. */
4436
+ function softwareContext(gl) {
4437
+ try {
4438
+ const debug = gl.getExtension?.("WEBGL_debug_renderer_info");
4439
+ const name = gl.getParameter?.(debug ? debug.UNMASKED_RENDERER_WEBGL : gl.RENDERER);
4440
+ return typeof name === "string" && SOFTWARE_RASTERIZER.test(name);
4441
+ } catch {
4442
+ return false;
4443
+ }
4444
+ }
4373
4445
  /** Orthographic half-extents for a vertical view extent at an aspect ratio (pure; testable). */
4374
4446
  function orthoFrustum(viewHeight, aspect) {
4375
4447
  if (!Number.isFinite(viewHeight) || viewHeight <= 0) throw new Error("viewHeight must be finite and positive");
@@ -4432,7 +4504,21 @@ var Renderer = class Renderer {
4432
4504
  /** Per material, one prepared mesh of each kind it draws; see `prepareMaterialChange`. */
4433
4505
  materialMeshes = /* @__PURE__ */ new WeakMap();
4434
4506
  /** The scene's visible lights for warm-up builds, gathered once between rendered frames. */
4507
+ /**
4508
+ * WebGL render groups, for `cullRenderGroups`. Held weakly: a group is made before its owner
4509
+ * attaches it (a tile's, several frames before) and may never be, and one its owner has let
4510
+ * go of must not be kept alive here.
4511
+ */
4512
+ renderGroups = /* @__PURE__ */ new Set();
4513
+ /** Groups left out of the scene walk under way, to show again when it ends. */
4514
+ culledGroups = [];
4515
+ cullGroups = false;
4516
+ releaseShadowCulling;
4435
4517
  preparationLights;
4518
+ /** Every light the last walk of the scene found on show, and when it was (see `sceneLights`). */
4519
+ foundLights;
4520
+ foundLightsChildren = -1;
4521
+ foundLightsAt = Number.NEGATIVE_INFINITY;
4436
4522
  /**
4437
4523
  * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
4438
4524
  * `prepareVariants`.
@@ -4451,6 +4537,18 @@ var Renderer = class Renderer {
4451
4537
  get fallbackReason() {
4452
4538
  return this.fallback;
4453
4539
  }
4540
+ software;
4541
+ /**
4542
+ * Whether this device draws through a software rasterizer: SwiftShader (headless and
4543
+ * blocklisted-GPU Chromium), Mesa's llvmpipe or lavapipe, Windows' Basic Render Driver, or a
4544
+ * WebGPU fallback adapter. Every pixel and vertex then costs CPU time, so a host that sizes its
4545
+ * work to the device starts at its lowest tier. Read once, from the WebGL context's unmasked
4546
+ * renderer string (false where the browser hides it) or the WebGPU adapter's fallback flag.
4547
+ */
4548
+ get softwareRasterizer() {
4549
+ this.software ??= this.backend === "webgl" && softwareContext(this.three.getContext());
4550
+ return this.software;
4551
+ }
4454
4552
  scene;
4455
4553
  /** World-space objects live here so the renderer can rebase them near the camera. */
4456
4554
  worldRoot;
@@ -4728,7 +4826,8 @@ var Renderer = class Renderer {
4728
4826
  const probeMs = opts.backendProbeTimeoutMs ?? 5e3;
4729
4827
  try {
4730
4828
  if (typeof navigator === "undefined" || !("gpu" in navigator) || !navigator.gpu) throw new Error("WebGPU is unavailable in this browser or context");
4731
- if (await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request") === null) throw new Error("WebGPU reported no adapter for this device");
4829
+ const adapter = await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request");
4830
+ if (adapter === null) throw new Error("WebGPU reported no adapter for this device");
4732
4831
  const { createWebGpuDriver } = await import("./webgpu-driver-YWVTLOY7.mjs");
4733
4832
  const three = await withProbeTimeout(createWebGpuDriver(opts), probeMs, "initialization", (late) => {
4734
4833
  late.dispose();
@@ -4740,6 +4839,7 @@ var Renderer = class Renderer {
4740
4839
  return new Renderer(opts, {
4741
4840
  three,
4742
4841
  backend: "webgpu",
4842
+ softwareAdapter: softwareAdapter(adapter),
4743
4843
  clouds: {
4744
4844
  material: clouds.createWebGpuCloudMaterial,
4745
4845
  installShadows: (uniforms) => clouds.installWebGpuCloudShadows(three, uniforms),
@@ -4785,6 +4885,7 @@ var Renderer = class Renderer {
4785
4885
  this.viewportHeight = height;
4786
4886
  this.pixelRatio = pixelRatio;
4787
4887
  this.backend = initialized?.backend ?? "webgl";
4888
+ if (this.backend === "webgpu") this.software = initialized?.softwareAdapter === true;
4788
4889
  this.optimizer = initialized?.optimizer;
4789
4890
  this.cloudBackend = initialized?.clouds;
4790
4891
  this.three = initialized?.three ?? createWebGlRenderer({
@@ -4800,6 +4901,8 @@ var Renderer = class Renderer {
4800
4901
  this.cloudBackend.installShadows(this.cloudShadows);
4801
4902
  this.cloudBackend.installSnowCover(this.snowCover);
4802
4903
  } else {
4904
+ this.cullGroups = opts.cullRenderGroups !== false;
4905
+ if (this.cullGroups) this.installShadowCulling(this.three);
4803
4906
  const far = new FarShadow(this.three);
4804
4907
  this.farShadow = far;
4805
4908
  this.releaseCloudShadows = installWebGlCloudShadows(this.three, this.cloudShadows, (shader, material) => {
@@ -5400,15 +5503,37 @@ var Renderer = class Renderer {
5400
5503
  check();
5401
5504
  });
5402
5505
  }
5403
- /** The scene's visible lights, gathered once between rendered frames for warm-up builds. */
5506
+ /**
5507
+ * The scene's visible lights, for warm-up builds, as of this frame. Finding them is a walk of
5508
+ * the whole visible scene, and made once between rendered frames that was 1.2 ms of every frame
5509
+ * that prepared anything over a streamed city (two lights among nine thousand objects), which
5510
+ * in flight is all of them. So the lights found stand for `LIGHTS_REFRESH_MS`, or until the
5511
+ * scene's own children change, and each frame only checks which of them are still on show. A
5512
+ * light that appears deeper in the scene counts from the next walk: until then a warm-up is
5513
+ * built, and remembered, for the lights before it, so it is prepared again rather than taken
5514
+ * for ready.
5515
+ */
5404
5516
  sceneLights() {
5405
- this.preparationLights ??= (() => {
5517
+ if (this.preparationLights !== void 0) return this.preparationLights;
5518
+ const now = performance.now();
5519
+ const children = this.scene.children.length;
5520
+ if (this.foundLights === void 0 || children !== this.foundLightsChildren || now - this.foundLightsAt >= LIGHTS_REFRESH_MS) {
5406
5521
  const lights = [];
5407
5522
  THREE.Object3D.prototype.traverseVisible.call(this.scene, (object) => {
5408
5523
  if (object.isLight) lights.push(object);
5409
5524
  });
5410
- return lights;
5411
- })();
5525
+ this.foundLights = lights;
5526
+ this.foundLightsChildren = children;
5527
+ this.foundLightsAt = now;
5528
+ }
5529
+ const scene = this.scene;
5530
+ this.preparationLights = this.foundLights.filter((light) => {
5531
+ for (let cursor = light; cursor !== null; cursor = cursor.parent) {
5532
+ if (!cursor.visible) return false;
5533
+ if (cursor === scene) return true;
5534
+ }
5535
+ return false;
5536
+ });
5412
5537
  return this.preparationLights;
5413
5538
  }
5414
5539
  /**
@@ -5573,6 +5698,7 @@ var Renderer = class Renderer {
5573
5698
  if (hidden.light.visible !== hidden.visible) this.shadowCastersWarmed = false;
5574
5699
  hidden.light.visible = hidden.visible;
5575
5700
  this.hiddenAmbient = void 0;
5701
+ this.foundLights = void 0;
5576
5702
  }
5577
5703
  if (light === void 0) return;
5578
5704
  this.hiddenAmbient ??= {
@@ -5586,8 +5712,11 @@ var Renderer = class Renderer {
5586
5712
  const warmup = this.shadowCasterWarmup();
5587
5713
  if (warmup !== void 0) this.scene.add(warmup);
5588
5714
  try {
5715
+ this.cullOutOfView();
5589
5716
  this.optimized(() => this.three.render(this.scene, this.camera));
5590
5717
  } finally {
5718
+ for (const group of this.culledGroups) group.visible = true;
5719
+ this.culledGroups.length = 0;
5591
5720
  if (warmup !== void 0) {
5592
5721
  warmup.removeFromParent();
5593
5722
  for (const child of warmup.children) {
@@ -5599,6 +5728,127 @@ var Renderer = class Renderer {
5599
5728
  }
5600
5729
  }
5601
5730
  /**
5731
+ * Hide, for the scene walk about to start, every render group whose bounds lie wholly outside
5732
+ * the camera's view: three then skips it and everything under it when it brings world matrices
5733
+ * up to date, updates levels of detail and gathers what to draw, none of which can draw
5734
+ * anything from it. Shown again when the render ends (see `renderScene`), so nothing outside the
5735
+ * render sees a group hidden. Shadow maps are walked on their own terms (`installShadowCulling`).
5736
+ */
5737
+ cullOutOfView() {
5738
+ if (!this.cullGroups || this.renderGroups.size === 0) return;
5739
+ const camera = this.camera;
5740
+ if (camera.parent === null && camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
5741
+ viewProjection(camera, cullMatrix);
5742
+ for (const ref of this.renderGroups) {
5743
+ const group = ref.deref();
5744
+ if (group === void 0) {
5745
+ this.renderGroups.delete(ref);
5746
+ continue;
5747
+ }
5748
+ const parent = group.parent;
5749
+ if (parent === null) continue;
5750
+ const bounds = group.userData[RENDER_BOUNDS];
5751
+ if (bounds === void 0 || !group.visible || bounds.isEmpty()) continue;
5752
+ if (group.userData["renderBoundsStale"] === true) continue;
5753
+ if (!groupInScene(group, this.scene)) continue;
5754
+ if (cullFrames.get(parent) !== cullPass) {
5755
+ cullFrames.set(parent, cullPass);
5756
+ parent.updateWorldMatrix(true, false);
5757
+ }
5758
+ cullBox.copy(bounds).applyMatrix4(parent.matrixWorld);
5759
+ if (!boxOutsideView(cullMatrix, cullBox.min, cullBox.max)) continue;
5760
+ group.visible = false;
5761
+ this.culledGroups.push(group);
5762
+ }
5763
+ cullPass++;
5764
+ }
5765
+ /**
5766
+ * Walk each shadow map's casters without the render groups that cannot cast into it. A map is
5767
+ * drawn from its light, so what counts is the light's own view, not the camera's: groups hidden
5768
+ * for the camera come back for a light that reaches them (with their world matrices and levels
5769
+ * of detail brought up to date, which the scene's walk skipped), and groups the camera sees stay
5770
+ * out of a map that ends short of them. The sun's focused map covers a few hundred meters of a
5771
+ * view tens of kilometers deep, and three walked every object of that view for it. Lights
5772
+ * other than directional ones keep every group, as before.
5773
+ */
5774
+ installShadowCulling(renderer) {
5775
+ const shadowMap = renderer.shadowMap;
5776
+ const render = shadowMap.render;
5777
+ if (typeof render !== "function") return;
5778
+ const matrices = [];
5779
+ const depths = [];
5780
+ /** When each group out of view last had its levels of detail chosen for a shadow map. */
5781
+ const shadowLods = /* @__PURE__ */ new WeakMap();
5782
+ shadowMap.render = (lights, scene, camera) => {
5783
+ if (!this.cullGroups || this.renderGroups.size === 0 || lights.length === 0 || !renderer.shadowMap.enabled) {
5784
+ render.call(shadowMap, lights, scene, camera);
5785
+ return;
5786
+ }
5787
+ const shadowOf = (light) => light.shadow;
5788
+ const drawn = lights.filter((light) => {
5789
+ const shadow = shadowOf(light);
5790
+ return shadow !== void 0 && (shadow.autoUpdate || shadow.needsUpdate);
5791
+ });
5792
+ const directional = drawn.every((light) => light.isDirectionalLight);
5793
+ let count = 0;
5794
+ if (directional) for (const light of drawn) {
5795
+ const shadow = shadowOf(light);
5796
+ shadow.updateMatrices(light);
5797
+ let matrix = matrices[count];
5798
+ if (matrix === void 0) {
5799
+ matrix = new THREE.Matrix4();
5800
+ matrices[count] = matrix;
5801
+ }
5802
+ viewProjection(shadow.camera, matrix);
5803
+ const lens = shadow.camera;
5804
+ depths[count] = {
5805
+ view: lens.matrixWorldInverse,
5806
+ near: lens.near,
5807
+ far: lens.far
5808
+ };
5809
+ count++;
5810
+ }
5811
+ const changed = [];
5812
+ const hidden = new Set(this.culledGroups);
5813
+ const now = performance.now();
5814
+ for (const ref of this.renderGroups) {
5815
+ const group = ref.deref();
5816
+ const parent = group?.parent;
5817
+ if (group === void 0 || parent === null || parent === void 0) continue;
5818
+ const culled = hidden.has(group);
5819
+ if (!culled && !group.visible) continue;
5820
+ const bounds = group.userData[RENDER_BOUNDS];
5821
+ let reached = !directional || bounds === void 0 || bounds.isEmpty() || group.userData["renderBoundsStale"] === true;
5822
+ if (!reached) {
5823
+ cullBox.copy(bounds).applyMatrix4(parent.matrixWorld);
5824
+ for (let i = 0; i < count && !reached; i++) reached = !boxOutsideView(matrices[i], cullBox.min, cullBox.max, depths[i]);
5825
+ }
5826
+ if (reached === !culled) continue;
5827
+ group.visible = reached;
5828
+ changed.push(group);
5829
+ if (!reached) continue;
5830
+ if (group.matrixWorldNeedsUpdate || group.userData["renderMatricesStale"] === true) {
5831
+ group.userData[RENDER_MATRICES_STALE] = false;
5832
+ group.updateMatrixWorld();
5833
+ }
5834
+ if (now - (shadowLods.get(group) ?? Number.NEGATIVE_INFINITY) < SHADOW_LOD_MS) continue;
5835
+ shadowLods.set(group, now);
5836
+ group.traverseVisible((object) => {
5837
+ const lod = object;
5838
+ if (lod.isLOD && lod.autoUpdate) lod.update(camera);
5839
+ });
5840
+ }
5841
+ try {
5842
+ render.call(shadowMap, lights, scene, camera);
5843
+ } finally {
5844
+ for (const group of changed) group.visible = !group.visible;
5845
+ }
5846
+ };
5847
+ this.releaseShadowCulling = () => {
5848
+ shadowMap.render = render;
5849
+ };
5850
+ }
5851
+ /**
5602
5852
  * Once WebGL sun shadows draw, a frame of degenerate casters (one plain and one instanced mesh
5603
5853
  * per side): the shadow pass builds a depth program for each kind of caster the first time it
5604
5854
  * draws one, and the first double-sided caster in view held a mid-flight frame 10 ms. The
@@ -5703,9 +5953,18 @@ var Renderer = class Renderer {
5703
5953
  }
5704
5954
  return this.occlusion?.camera === this.camera ? this.occlusion.pass : void 0;
5705
5955
  }
5706
- /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
5956
+ /**
5957
+ * Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands.
5958
+ * WebGL leaves a group out of the scene walks it cannot be seen in, once its owner states its
5959
+ * bounds in `userData.renderBounds` (see `RENDER_BOUNDS`) and keeps them true as its content
5960
+ * changes (`expandRenderBounds`, `markRenderBoundsChanged`): see `cullRenderGroups`.
5961
+ */
5707
5962
  createRenderGroup() {
5708
- return this.optimizer?.createGroup() ?? new THREE.Group();
5963
+ const optimized = this.optimizer?.createGroup();
5964
+ if (optimized !== void 0) return optimized;
5965
+ const group = new THREE.Group();
5966
+ if (this.cullGroups) this.renderGroups.add(new WeakRef(group));
5967
+ return group;
5709
5968
  }
5710
5969
  /** Last completed visible frame, excluding offscreen resource preparation. */
5711
5970
  stats() {
@@ -5737,6 +5996,8 @@ var Renderer = class Renderer {
5737
5996
  this.activeWeather = void 0;
5738
5997
  this.releaseCloudShadows?.();
5739
5998
  this.farShadow?.dispose();
5999
+ this.releaseShadowCulling?.();
6000
+ this.renderGroups.clear();
5740
6001
  this.cloudTextures.dispose();
5741
6002
  this.reflections?.dispose();
5742
6003
  this.hideReflectedAmbient(void 0);
@@ -6412,4 +6673,4 @@ function decodeStarCatalog(input) {
6412
6673
  }));
6413
6674
  }
6414
6675
  //#endregion
6415
- export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InputMap, InstanceBatch, InstanceMatrixAttribute, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applyLivery, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, isInstanceBatch, isInstanceBatchGeometry, lerp3, liveryGraphicTexture, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };
6676
+ export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InputMap, InstanceBatch, InstanceMatrixAttribute, InterpolationBuffer, MaterialResolver, RENDER_BOUNDS, RENDER_BOUNDS_STALE, RENDER_MATRICES_STALE, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applyLivery, applySceneCamera, boxOutsideView, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, expandRenderBounds, followCameraPose, isInstanceBatch, isInstanceBatchGeometry, lerp3, liveryGraphicTexture, localCommand, markRenderBoundsChanged, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, viewProjection, weatherProfile };
@@ -1,2 +1,2 @@
1
- import { a as isInstanceBatch, i as InstanceMatrixAttribute, n as INSTANCE_BATCH_MATRIX_COLUMNS, o as isInstanceBatchGeometry, r as InstanceBatch, t as INSTANCE_BATCH_COLOR } from "./instance-batch-CO4YD6rd.mjs";
2
- export { INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InstanceBatch, InstanceMatrixAttribute, isInstanceBatch, isInstanceBatchGeometry };
1
+ import { a as expandRenderBounds, c as INSTANCE_BATCH_COLOR, d as InstanceMatrixAttribute, f as isInstanceBatch, i as boxOutsideView, l as INSTANCE_BATCH_MATRIX_COLUMNS, n as RENDER_BOUNDS_STALE, o as markRenderBoundsChanged, p as isInstanceBatchGeometry, r as RENDER_MATRICES_STALE, s as viewProjection, t as RENDER_BOUNDS, u as InstanceBatch } from "./render-bounds-B4yQoiYR.mjs";
2
+ export { INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InstanceBatch, InstanceMatrixAttribute, RENDER_BOUNDS, RENDER_BOUNDS_STALE, RENDER_MATRICES_STALE, boxOutsideView, expandRenderBounds, isInstanceBatch, isInstanceBatchGeometry, markRenderBoundsChanged, viewProjection };
@@ -1,2 +1,3 @@
1
+ import { a as expandRenderBounds, i as boxOutsideView, n as RENDER_BOUNDS_STALE, o as markRenderBoundsChanged, r as RENDER_MATRICES_STALE, s as viewProjection, t as RENDER_BOUNDS } from "./render-bounds-uRp_yPp6.mjs";
1
2
  import { a as isInstanceBatch, i as InstanceMatrixAttribute, n as INSTANCE_BATCH_MATRIX_COLUMNS, o as isInstanceBatchGeometry, r as InstanceBatch, t as INSTANCE_BATCH_COLOR } from "./instance-batch-Ds-oKQW4.mjs";
2
- export { INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InstanceBatch, InstanceMatrixAttribute, isInstanceBatch, isInstanceBatchGeometry };
3
+ export { INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InstanceBatch, InstanceMatrixAttribute, RENDER_BOUNDS, RENDER_BOUNDS_STALE, RENDER_MATRICES_STALE, boxOutsideView, expandRenderBounds, isInstanceBatch, isInstanceBatchGeometry, markRenderBoundsChanged, viewProjection };
@@ -61,6 +61,14 @@ interface MarkerSpec {
61
61
  interface MarkerLayerOptions {
62
62
  /** Ground height at world X/Z, or undefined while unknown. Required for ground-snapped markers. */
63
63
  groundHeight?: (x: number, z: number) => number | undefined;
64
+ /**
65
+ * How often a grounded marker reads its ground height again, ms (default 0: every update). The
66
+ * ground beneath a marker changes only as terrain streams in, and a host whose `groundHeight`
67
+ * samples streamed terrain pays for every read: a city's photo pins re-read each frame took
68
+ * about 3% of the main thread while an Earth view loaded. A marker not yet grounded, or moved,
69
+ * reads it at every update until it has one.
70
+ */
71
+ groundRefreshMs?: number;
64
72
  /** Most markers drawn at once; extras nearest last are hidden (default 256). */
65
73
  maxVisible?: number;
66
74
  /** Distances (meters) over which markers fade out: full at `near`, gone at `far`. */
package/dist/markers.mjs CHANGED
@@ -159,13 +159,19 @@ var MarkerLayer = class {
159
159
  const fadeMs = this.options.fadeMs ?? 180;
160
160
  const fadeStep = fadeMs > 0 ? elapsedMs / fadeMs : Number.POSITIVE_INFINITY;
161
161
  const hideUntilGrounded = this.options.hideUntilGrounded ?? true;
162
+ const groundRefreshMs = this.options.groundRefreshMs ?? 0;
162
163
  const candidates = [];
163
164
  for (const entry of this.entries.values()) {
164
165
  const { spec } = entry;
165
166
  let y = spec.y;
166
167
  if (y === void 0) {
167
- const ground = this.options.groundHeight?.(spec.x, spec.z);
168
- if (ground !== void 0) entry.groundY = ground;
168
+ if (entry.groundY === void 0 || nowMs - entry.groundReadMs >= groundRefreshMs) {
169
+ const ground = this.options.groundHeight?.(spec.x, spec.z);
170
+ if (ground !== void 0) {
171
+ entry.groundY = ground;
172
+ entry.groundReadMs = nowMs;
173
+ }
174
+ }
169
175
  y = entry.groundY === void 0 ? hideUntilGrounded ? void 0 : spec.elevation ?? 0 : entry.groundY + (spec.elevation ?? 0);
170
176
  }
171
177
  entry.sprite.visible = false;
@@ -314,6 +320,7 @@ var MarkerLayer = class {
314
320
  imageKey: spec.image,
315
321
  aspect: imageAspect(spec.image) ?? 1,
316
322
  groundY: void 0,
323
+ groundReadMs: Number.NEGATIVE_INFINITY,
317
324
  distance: 0,
318
325
  shown: false,
319
326
  presence: 0
@@ -0,0 +1,126 @@
1
+ import * as THREE from "three";
2
+
3
+ //#region src/three/instance-batch.d.ts
4
+ /** The geometry attributes a batch's instance matrices are read through, one matrix column each. */
5
+ declare const INSTANCE_BATCH_MATRIX_COLUMNS: readonly string[];
6
+ /** The geometry attribute a batch's instance colors are read through, when it has colors. */
7
+ declare const INSTANCE_BATCH_COLOR = "instanceColor";
8
+ /**
9
+ * A batch's instance matrices: one interleaved buffer that WebGL reads as a `mat4` attribute and
10
+ * WebGPU as four `vec4` columns, so either backend uploads it once. It keeps the `version` and
11
+ * `usage` an `InstancedBufferAttribute` reports, which its buffer holds.
12
+ */
13
+ declare class InstanceMatrixAttribute extends THREE.InterleavedBufferAttribute {
14
+ readonly isInstanceMatrixAttribute = true;
15
+ constructor(buffer: THREE.InstancedInterleavedBuffer);
16
+ get version(): number;
17
+ get usage(): THREE.Usage;
18
+ setUsage(usage: THREE.Usage): this;
19
+ get updateRanges(): {
20
+ start: number;
21
+ count: number;
22
+ }[];
23
+ addUpdateRange(start: number, count: number): void;
24
+ clearUpdateRanges(): void;
25
+ }
26
+ /**
27
+ * An `InstancedMesh` whose instances live in a geometry of its own, so WebGPU builds its shaders
28
+ * once for every batch of the same material and model layout instead of once per batch.
29
+ *
30
+ * Three's WebGPU renderer keys an instanced mesh's node build by the mesh, since its instance
31
+ * matrices are a node bound to that mesh's buffer: every batch streamed in paid a build of its own,
32
+ * about 10 ms of main thread each, which was most of a flight's streaming work. A batch instead
33
+ * carries its matrices and colors as instanced vertex attributes of an `InstancedBufferGeometry`
34
+ * that shares the model geometry's buffers, and the WebGPU driver reads them by name, the way it
35
+ * reads `position`: one build serves every batch, and each draw binds its own batch's vertex
36
+ * buffers, which a recorded render bundle replays as recorded. WebGL draws it as the
37
+ * `InstancedMesh` it is, with no setup, through three's own instancing.
38
+ *
39
+ * It keeps `InstancedMesh`'s API: `count`, `setMatrixAt`, `setColorAt`, bounds, raycasting and
40
+ * `dispose`. Assigning `geometry` selects the model it draws (a level of detail can swap it each
41
+ * frame without a new build, as long as the models share an attribute layout); `geometry` then reads
42
+ * back as the batch's own geometry and `sourceGeometry` as the model. Set colors before the first
43
+ * draw: a batch drawn without colors keeps its build. Models with morph targets are not supported.
44
+ */
45
+ declare class InstanceBatch<TMaterial extends THREE.Material | THREE.Material[] = THREE.Material | THREE.Material[]> extends THREE.InstancedMesh<THREE.BufferGeometry, TMaterial> {
46
+ readonly isInstanceBatch: true;
47
+ constructor(geometry: THREE.BufferGeometry, material: TMaterial, count: number);
48
+ /** The model geometry this batch draws (what `geometry` was last set to). */
49
+ get sourceGeometry(): THREE.BufferGeometry;
50
+ /**
51
+ * Draw the instances in `matrices`, sixteen floats each as `Matrix4.elements` lays them out.
52
+ * The batch takes the array over; set `count` to match.
53
+ */
54
+ setInstanceMatrices(matrices: Float32Array): this;
55
+ /** Every geometry of this batch's own, one per model it has drawn. */
56
+ batchGeometries(): THREE.BufferGeometry[];
57
+ override copy(source: InstanceBatch<TMaterial>, recursive?: boolean): this;
58
+ /**
59
+ * Release the batch's buffers. Its own geometries are released with it, but not the model
60
+ * geometry's buffers, which other batches share: a disposed batch is not drawn again.
61
+ */
62
+ override dispose(): this;
63
+ }
64
+ /** Whether `object` is an `InstanceBatch`. */
65
+ declare function isInstanceBatch(object: unknown): object is InstanceBatch;
66
+ /** Whether `geometry` is one of an `InstanceBatch`'s own geometries. */
67
+ declare function isInstanceBatchGeometry(geometry: THREE.BufferGeometry): boolean;
68
+ //#endregion
69
+ //#region src/three/render-bounds.d.ts
70
+ /**
71
+ * `userData` key of a render group's bounds: a `THREE.Box3` in the frame of the group's parent
72
+ * that contains everything the group draws, now and as its parts move. A group without one is
73
+ * never left out.
74
+ */
75
+ declare const RENDER_BOUNDS: "renderBounds";
76
+ /** `userData` flag asking a group's owner to work its bounds out again (see `markRenderBoundsChanged`). */
77
+ declare const RENDER_BOUNDS_STALE: "renderBoundsStale";
78
+ /**
79
+ * `userData` flag an owner sets on its render group when it adds content to it: that content has
80
+ * no world matrices until a walk reaches it, and the renderer may be leaving the group out of the
81
+ * scene's walk. Before a shadow map draws a group it left out, the renderer brings a flagged
82
+ * group's matrices up to date and clears the flag; an owner whose group skips walks while hidden
83
+ * clears it in the walk it does make.
84
+ */
85
+ declare const RENDER_MATRICES_STALE: "renderMatricesStale";
86
+ /**
87
+ * Tell the render group above `object` that what it draws has changed size: call it after adding
88
+ * or replacing geometry inside streamed content once that content is on show (a landmark's next
89
+ * level of detail arriving, say). The group's owner works its bounds out again before the next
90
+ * frame. Does nothing for an object outside any group with bounds.
91
+ */
92
+ declare function markRenderBoundsChanged(object: THREE.Object3D): void;
93
+ /** A camera's view volume as the matrix from world to clip space, for `boxOutsideView`. */
94
+ declare function viewProjection(camera: THREE.Camera, target: THREE.Matrix4): THREE.Matrix4;
95
+ /** A camera's depth range, for `boxOutsideView`: its view matrix and the planes it draws between. */
96
+ interface ViewDepth {
97
+ view: THREE.Matrix4;
98
+ near: number;
99
+ far: number;
100
+ }
101
+ /**
102
+ * Whether a world-space box lies wholly outside a camera's view: every corner beyond the same
103
+ * side of it, or all of them behind a perspective camera. Without `depth` the near and far planes
104
+ * are not tested (ground a camera's far plane cuts is still wanted, and the test then holds for
105
+ * either depth convention). With it, a box wholly nearer than `near` or beyond `far` along the
106
+ * camera's axis is outside too, read in view space: an orthographic shadow map is a box, and
107
+ * ground far along the light's direction lines up with it without being in it. A box across a
108
+ * corner of the view can read as inside when it is not, which only costs the walk it would have
109
+ * saved.
110
+ */
111
+ declare function boxOutsideView(matrix: THREE.Matrix4, min: THREE.Vector3, max: THREE.Vector3, depth?: ViewDepth): boolean;
112
+ /**
113
+ * Grow `bounds` (in `frame`'s own coordinates) to hold everything `object` draws: each mesh's
114
+ * bounding box where it has one already (an instanced mesh's own, over its instances), and
115
+ * otherwise the box round its bounding sphere, which three works out for its own culling anyway.
116
+ * Nothing is measured from vertices that three would not measure too: a box computed here for
117
+ * every building's geometry was a pass over a dense tile's half a million vertices, 5 ms of the
118
+ * job that published it. An object marked `userData.dynamicTransform` may turn about its own
119
+ * origin, so it and what is under it count as the sphere they can sweep there; one that travels
120
+ * needs its owner to state bounds for the whole of its way. Local matrices are read as they stand
121
+ * (static content has them frozen), so the object need not have been drawn or even attached.
122
+ * `padding` is added round each part.
123
+ */
124
+ declare function expandRenderBounds(bounds: THREE.Box3, object: THREE.Object3D, frame: THREE.Object3D, padding?: number): THREE.Box3;
125
+ //#endregion
126
+ export { expandRenderBounds as a, INSTANCE_BATCH_COLOR as c, InstanceMatrixAttribute as d, isInstanceBatch as f, boxOutsideView as i, INSTANCE_BATCH_MATRIX_COLUMNS as l, RENDER_BOUNDS_STALE as n, markRenderBoundsChanged as o, isInstanceBatchGeometry as p, RENDER_MATRICES_STALE as r, viewProjection as s, RENDER_BOUNDS as t, InstanceBatch as u };
@@ -0,0 +1,151 @@
1
+ import * as THREE from "three";
2
+ //#region src/three/render-bounds.ts
3
+ /**
4
+ * `userData` key of a render group's bounds: a `THREE.Box3` in the frame of the group's parent
5
+ * that contains everything the group draws, now and as its parts move. A group without one is
6
+ * never left out.
7
+ */
8
+ const RENDER_BOUNDS = "renderBounds";
9
+ /** `userData` flag asking a group's owner to work its bounds out again (see `markRenderBoundsChanged`). */
10
+ const RENDER_BOUNDS_STALE = "renderBoundsStale";
11
+ /**
12
+ * `userData` flag an owner sets on its render group when it adds content to it: that content has
13
+ * no world matrices until a walk reaches it, and the renderer may be leaving the group out of the
14
+ * scene's walk. Before a shadow map draws a group it left out, the renderer brings a flagged
15
+ * group's matrices up to date and clears the flag; an owner whose group skips walks while hidden
16
+ * clears it in the walk it does make.
17
+ */
18
+ const RENDER_MATRICES_STALE = "renderMatricesStale";
19
+ /**
20
+ * Tell the render group above `object` that what it draws has changed size: call it after adding
21
+ * or replacing geometry inside streamed content once that content is on show (a landmark's next
22
+ * level of detail arriving, say). The group's owner works its bounds out again before the next
23
+ * frame. Does nothing for an object outside any group with bounds.
24
+ */
25
+ function markRenderBoundsChanged(object) {
26
+ for (let cursor = object; cursor !== null; cursor = cursor.parent) {
27
+ if (cursor.userData["renderBounds"] === void 0) continue;
28
+ cursor.userData[RENDER_BOUNDS_STALE] = true;
29
+ return;
30
+ }
31
+ }
32
+ /** A camera's view volume as the matrix from world to clip space, for `boxOutsideView`. */
33
+ function viewProjection(camera, target) {
34
+ return target.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
35
+ }
36
+ /**
37
+ * Whether a world-space box lies wholly outside a camera's view: every corner beyond the same
38
+ * side of it, or all of them behind a perspective camera. Without `depth` the near and far planes
39
+ * are not tested (ground a camera's far plane cuts is still wanted, and the test then holds for
40
+ * either depth convention). With it, a box wholly nearer than `near` or beyond `far` along the
41
+ * camera's axis is outside too, read in view space: an orthographic shadow map is a box, and
42
+ * ground far along the light's direction lines up with it without being in it. A box across a
43
+ * corner of the view can read as inside when it is not, which only costs the walk it would have
44
+ * saved.
45
+ */
46
+ function boxOutsideView(matrix, min, max, depth) {
47
+ const m = matrix.elements;
48
+ let left = true, right = true, below = true, above = true, behind = true;
49
+ if (depth !== void 0) {
50
+ const v = depth.view.elements;
51
+ let nearer = true, farther = true;
52
+ for (let corner = 0; corner < 8 && (nearer || farther); corner++) {
53
+ const along = -(v[2] * (corner & 1 ? max.x : min.x) + v[6] * (corner & 2 ? max.y : min.y) + v[10] * (corner & 4 ? max.z : min.z) + v[14]);
54
+ if (along >= depth.near) nearer = false;
55
+ if (along <= depth.far) farther = false;
56
+ }
57
+ if (nearer || farther) return true;
58
+ }
59
+ for (let corner = 0; corner < 8; corner++) {
60
+ const x = corner & 1 ? max.x : min.x, y = corner & 2 ? max.y : min.y, z = corner & 4 ? max.z : min.z;
61
+ const cx = m[0] * x + m[4] * y + m[8] * z + m[12], cy = m[1] * x + m[5] * y + m[9] * z + m[13], cw = m[3] * x + m[7] * y + m[11] * z + m[15];
62
+ if (cx >= -cw) left = false;
63
+ if (cx <= cw) right = false;
64
+ if (cy >= -cw) below = false;
65
+ if (cy <= cw) above = false;
66
+ if (cw > 0) behind = false;
67
+ if (!(left || right || below || above || behind)) return false;
68
+ }
69
+ return true;
70
+ }
71
+ const corner = new THREE.Vector3();
72
+ const local = new THREE.Box3();
73
+ const IDENTITY = new THREE.Matrix4();
74
+ /**
75
+ * Grow `bounds` (in `frame`'s own coordinates) to hold everything `object` draws: each mesh's
76
+ * bounding box where it has one already (an instanced mesh's own, over its instances), and
77
+ * otherwise the box round its bounding sphere, which three works out for its own culling anyway.
78
+ * Nothing is measured from vertices that three would not measure too: a box computed here for
79
+ * every building's geometry was a pass over a dense tile's half a million vertices, 5 ms of the
80
+ * job that published it. An object marked `userData.dynamicTransform` may turn about its own
81
+ * origin, so it and what is under it count as the sphere they can sweep there; one that travels
82
+ * needs its owner to state bounds for the whole of its way. Local matrices are read as they stand
83
+ * (static content has them frozen), so the object need not have been drawn or even attached.
84
+ * `padding` is added round each part.
85
+ */
86
+ function expandRenderBounds(bounds, object, frame, padding = 0) {
87
+ const chain = [];
88
+ for (let cursor = object; cursor !== null && cursor !== frame; cursor = cursor.parent) chain.push(cursor);
89
+ const placement = new THREE.Matrix4();
90
+ for (let i = chain.length - 1; i >= 0; i--) {
91
+ const part = chain[i];
92
+ if (part.matrixAutoUpdate) part.updateMatrix();
93
+ placement.multiply(part.matrix);
94
+ }
95
+ expand(bounds, object, placement, padding, false, 0);
96
+ return bounds;
97
+ }
98
+ /** One placement matrix per depth of the walk, reused: a tile's content is thousands of parts. */
99
+ const placements = [];
100
+ /** `placement` is the object's own, in the frame `bounds` is measured in. */
101
+ function expand(bounds, object, placement, padding, swept, depth) {
102
+ if (!swept && object.userData.dynamicTransform === true) {
103
+ const reach = new THREE.Box3();
104
+ expand(reach, object, IDENTITY, 0, true, depth);
105
+ if (reach.isEmpty()) return;
106
+ let radius = 0;
107
+ for (let i = 0; i < 8; i++) {
108
+ corner.set(i & 1 ? reach.max.x : reach.min.x, i & 2 ? reach.max.y : reach.min.y, i & 4 ? reach.max.z : reach.min.z);
109
+ radius = Math.max(radius, corner.length());
110
+ }
111
+ radius = radius * placement.getMaxScaleOnAxis() + padding;
112
+ corner.setFromMatrixPosition(placement);
113
+ bounds.expandByPoint(local.min.copy(corner).addScalar(-radius));
114
+ bounds.expandByPoint(local.max.copy(corner).addScalar(radius));
115
+ return;
116
+ }
117
+ const mesh = object;
118
+ if (mesh.isMesh || object.isLine || object.isPoints) {
119
+ const instanced = object;
120
+ const source = instanced.isInstancedMesh ? instanced : mesh.geometry;
121
+ const box = source.boundingBox;
122
+ if (box !== null) {
123
+ if (!box.isEmpty()) {
124
+ local.copy(box).applyMatrix4(placement);
125
+ if (padding > 0) local.expandByScalar(padding);
126
+ bounds.union(local);
127
+ }
128
+ } else {
129
+ if (source.boundingSphere === null) source.computeBoundingSphere();
130
+ const sphere = source.boundingSphere;
131
+ if (sphere !== null && sphere.radius >= 0) {
132
+ const radius = sphere.radius * placement.getMaxScaleOnAxis() + padding;
133
+ corner.copy(sphere.center).applyMatrix4(placement);
134
+ bounds.expandByPoint(local.min.copy(corner).addScalar(-radius));
135
+ bounds.expandByPoint(local.max.copy(corner).addScalar(radius));
136
+ }
137
+ }
138
+ }
139
+ if (object.children.length === 0) return;
140
+ let next = placements[depth];
141
+ if (next === void 0) {
142
+ next = new THREE.Matrix4();
143
+ placements[depth] = next;
144
+ }
145
+ for (const child of object.children) {
146
+ if (child.matrixAutoUpdate) child.updateMatrix();
147
+ expand(bounds, child, next.multiplyMatrices(placement, child.matrix), padding, swept, depth + 1);
148
+ }
149
+ }
150
+ //#endregion
151
+ export { expandRenderBounds as a, boxOutsideView as i, RENDER_BOUNDS_STALE as n, markRenderBoundsChanged as o, RENDER_MATRICES_STALE as r, viewProjection as s, RENDER_BOUNDS as t };
@@ -33,10 +33,26 @@ interface SceneAdmission {
33
33
  /** Jobs waiting, where the queue can say, so optional work can hold off behind a backlog. */
34
34
  readonly pending?: number;
35
35
  }
36
+ /**
37
+ * A larger frame budget for work that is backing up. Once the oldest waiting job (not a
38
+ * background one) has waited `afterMs`, the frame's time and byte budgets grow with its wait and
39
+ * reach these at twice that; a limit left out, or below the ordinary one, stays as it is. A fixed
40
+ * small budget protects the frame rate of a view that keeps up and starves one that does not: a
41
+ * city streaming in under an aircraft asked for more than twice the work 2 ms a frame could
42
+ * publish, each job waited 3 s (21 s at worst) for each of the several turns a tile's layer
43
+ * takes, and the ground ahead stayed bare while the queue used a twentieth of the main thread.
44
+ */
45
+ interface AdmissionBacklog {
46
+ afterMs: number;
47
+ maxMilliseconds?: number;
48
+ maxBytes?: number;
49
+ }
36
50
  interface FrameAdmissionOptions {
37
51
  maxMilliseconds?: number;
38
52
  maxBytes?: number;
39
53
  maxJobs?: number;
54
+ /** See `AdmissionBacklog`; none by default. */
55
+ backlog?: AdmissionBacklog | undefined;
40
56
  /**
41
57
  * How long a background job waits (ms, default 750) before the lane takes turns with the others,
42
58
  * and how many other jobs run between its turns (default 8). In flight normal work never runs
@@ -70,6 +86,7 @@ declare class FrameAdmissionQueue implements SceneAdmission {
70
86
  private maxMs;
71
87
  private maxBytes;
72
88
  private maxJobs;
89
+ private backlog;
73
90
  private urgentStreak;
74
91
  private orderedStreak;
75
92
  /** Jobs from the other lanes since the background lane last ran one. */
@@ -81,9 +98,16 @@ declare class FrameAdmissionQueue implements SceneAdmission {
81
98
  constructor(options?: FrameAdmissionOptions);
82
99
  /**
83
100
  * Change the per-frame budget from the next frame on; omitted limits keep their values. A host
84
- * can admit more when frames have time to spare (an adaptive quality tier, say).
101
+ * can admit more when frames have time to spare (an adaptive quality tier, say). `backlog` is
102
+ * replaced when the key is present: `undefined` takes the backlog budget away.
85
103
  */
86
- setLimits(limits: Pick<FrameAdmissionOptions, "maxMilliseconds" | "maxBytes" | "maxJobs">): void;
104
+ setLimits(limits: Pick<FrameAdmissionOptions, "maxMilliseconds" | "maxBytes" | "maxJobs" | "backlog">): void;
105
+ /**
106
+ * How far into its backlog budget the queue is, 0 to 1: by how long the oldest job outside the
107
+ * background lane has waited. Urgent jobs sit ahead of the others, each kind in arrival order
108
+ * but for the ordered jobs taken from among them, so the oldest is the first of either kind.
109
+ */
110
+ private pressure;
87
111
  run<T>(task: () => T, options?: AdmissionOptions): Promise<T>;
88
112
  /**
89
113
  * Callers keep the promise (preparation caches do, keyed by long-lived resources); the job holds
@@ -118,8 +142,9 @@ declare class FrameAdmissionQueue implements SceneAdmission {
118
142
  */
119
143
  flush(): void;
120
144
  /**
121
- * This frame's work allowance: the fixed budget, or for sustained software-rendering frames the
122
- * same share of the shortest recent one. One long frame (a hitch) changes nothing.
145
+ * This frame's work allowance: the budget (`maxMs`, the ordinary one or what a backlog has grown
146
+ * it to), or for sustained software-rendering frames the same share of the shortest recent one.
147
+ * One long frame (a hitch) changes nothing.
123
148
  */
124
149
  private frameBudget;
125
150
  dispose(): void;
@@ -640,6 +665,8 @@ interface InitializedRenderer {
640
665
  optimizer?: WebGpuSceneOptimizer;
641
666
  reflectionFilter?: SkyReflectionFilter;
642
667
  clouds?: CloudBackend;
668
+ /** The WebGPU adapter is a fallback (software) adapter; see Renderer.softwareRasterizer. */
669
+ softwareAdapter?: boolean;
643
670
  }
644
671
  interface RendererOptions {
645
672
  /** Shared procedural sky/ground reflections for PBR materials. Default false; Earth viewers enable it. */
@@ -660,6 +687,12 @@ interface RendererOptions {
660
687
  backendProbeTimeoutMs?: number;
661
688
  /** Persistent instance buffers and managed tile command caches. Defaults to true on WebGPU. */
662
689
  optimizeWebGpu?: boolean;
690
+ /**
691
+ * WebGL: leave render groups that state their bounds (see `createRenderGroup`) out of each
692
+ * scene walk they cannot be seen in, and out of each shadow map they cannot cast into. Default
693
+ * true; false walks every group every frame, for comparison.
694
+ */
695
+ cullRenderGroups?: boolean;
663
696
  /** Device loss requires a new viewer/canvas. Auto fallback applies during initialization. */
664
697
  onDeviceLost?: (reason: string) => void;
665
698
  canvas?: HTMLCanvasElement | OffscreenCanvas;
@@ -739,7 +772,21 @@ declare class Renderer {
739
772
  /** Per material, one prepared mesh of each kind it draws; see `prepareMaterialChange`. */
740
773
  private readonly materialMeshes;
741
774
  /** The scene's visible lights for warm-up builds, gathered once between rendered frames. */
775
+ /**
776
+ * WebGL render groups, for `cullRenderGroups`. Held weakly: a group is made before its owner
777
+ * attaches it (a tile's, several frames before) and may never be, and one its owner has let
778
+ * go of must not be kept alive here.
779
+ */
780
+ private readonly renderGroups;
781
+ /** Groups left out of the scene walk under way, to show again when it ends. */
782
+ private readonly culledGroups;
783
+ private cullGroups;
784
+ private releaseShadowCulling;
742
785
  private preparationLights;
786
+ /** Every light the last walk of the scene found on show, and when it was (see `sceneLights`). */
787
+ private foundLights;
788
+ private foundLightsChildren;
789
+ private foundLightsAt;
743
790
  /**
744
791
  * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
745
792
  * `prepareVariants`.
@@ -756,6 +803,15 @@ declare class Renderer {
756
803
  readonly backend: RendererBackend;
757
804
  private fallback;
758
805
  get fallbackReason(): string | undefined;
806
+ private software;
807
+ /**
808
+ * Whether this device draws through a software rasterizer: SwiftShader (headless and
809
+ * blocklisted-GPU Chromium), Mesa's llvmpipe or lavapipe, Windows' Basic Render Driver, or a
810
+ * WebGPU fallback adapter. Every pixel and vertex then costs CPU time, so a host that sizes its
811
+ * work to the device starts at its lowest tier. Read once, from the WebGL context's unmasked
812
+ * renderer string (false where the browser hides it) or the WebGPU adapter's fallback flag.
813
+ */
814
+ get softwareRasterizer(): boolean;
759
815
  readonly scene: THREE.Scene;
760
816
  /** World-space objects live here so the renderer can rebase them near the camera. */
761
817
  readonly worldRoot: THREE.Group;
@@ -978,7 +1034,16 @@ declare class Renderer {
978
1034
  * mid-frame (130 ms in flight).
979
1035
  */
980
1036
  private compileWebGl;
981
- /** The scene's visible lights, gathered once between rendered frames for warm-up builds. */
1037
+ /**
1038
+ * The scene's visible lights, for warm-up builds, as of this frame. Finding them is a walk of
1039
+ * the whole visible scene, and made once between rendered frames that was 1.2 ms of every frame
1040
+ * that prepared anything over a streamed city (two lights among nine thousand objects), which
1041
+ * in flight is all of them. So the lights found stand for `LIGHTS_REFRESH_MS`, or until the
1042
+ * scene's own children change, and each frame only checks which of them are still on show. A
1043
+ * light that appears deeper in the scene counts from the next walk: until then a warm-up is
1044
+ * built, and remembered, for the lights before it, so it is prepared again rather than taken
1045
+ * for ready.
1046
+ */
982
1047
  private sceneLights;
983
1048
  /**
984
1049
  * What a lit program is built for besides its material and mesh: the scene's lights and which
@@ -1002,6 +1067,24 @@ declare class Renderer {
1002
1067
  private hideReflectedAmbient;
1003
1068
  private renderScene;
1004
1069
  /**
1070
+ * Hide, for the scene walk about to start, every render group whose bounds lie wholly outside
1071
+ * the camera's view: three then skips it and everything under it when it brings world matrices
1072
+ * up to date, updates levels of detail and gathers what to draw, none of which can draw
1073
+ * anything from it. Shown again when the render ends (see `renderScene`), so nothing outside the
1074
+ * render sees a group hidden. Shadow maps are walked on their own terms (`installShadowCulling`).
1075
+ */
1076
+ private cullOutOfView;
1077
+ /**
1078
+ * Walk each shadow map's casters without the render groups that cannot cast into it. A map is
1079
+ * drawn from its light, so what counts is the light's own view, not the camera's: groups hidden
1080
+ * for the camera come back for a light that reaches them (with their world matrices and levels
1081
+ * of detail brought up to date, which the scene's walk skipped), and groups the camera sees stay
1082
+ * out of a map that ends short of them. The sun's focused map covers a few hundred meters of a
1083
+ * view tens of kilometers deep, and three walked every object of that view for it. Lights
1084
+ * other than directional ones keep every group, as before.
1085
+ */
1086
+ private installShadowCulling;
1087
+ /**
1005
1088
  * Once WebGL sun shadows draw, a frame of degenerate casters (one plain and one instanced mesh
1006
1089
  * per side): the shadow pass builds a depth program for each kind of caster the first time it
1007
1090
  * draws one, and the first double-sided caster in view held a mid-flight frame 10 ms. The
@@ -1025,7 +1108,12 @@ declare class Renderer {
1025
1108
  suspendAmbientOcclusion(suspended: boolean): void;
1026
1109
  /** The occlusion pass for the current camera, building one in the background when needed. */
1027
1110
  private currentOcclusion;
1028
- /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
1111
+ /**
1112
+ * Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands.
1113
+ * WebGL leaves a group out of the scene walks it cannot be seen in, once its owner states its
1114
+ * bounds in `userData.renderBounds` (see `RENDER_BOUNDS`) and keeps them true as its content
1115
+ * changes (`expandRenderBounds`, `markRenderBoundsChanged`): see `cullRenderGroups`.
1116
+ */
1029
1117
  createRenderGroup(): THREE.Group;
1030
1118
  /** Last completed visible frame, excluding offscreen resource preparation. */
1031
1119
  stats(): {
@@ -1037,4 +1125,4 @@ declare class Renderer {
1037
1125
  dispose(): void;
1038
1126
  }
1039
1127
  //#endregion
1040
- export { SkyReflectionFilter as A, SkyVisualOptions as C, evaluateEarthSky as D, EarthSkyState as E, AdmissionOptions as F, AdmissionSample as I, FrameAdmissionOptions as L, SkyReflections as M, createWebGlSkyReflectionFilter as N, skyTimeMs as O, reflectionStateFromLights as P, FrameAdmissionQueue as R, SkyVisual as S, CelestialPosition as T, WeatherVisual as _, RendererBackendPreference as a, SkyFrame as b, TopDownOrtho as c, ShadowFocus as d, ShadowQuality as f, FarShadowInfo as g, createGpuFrameTimer as h, RendererBackend as i, SkyReflectionState as j, starDirection as k, nextWorldOrigin as l, GpuFrameTimerOptions as m, CameraPose as n, RendererOptions as o, GpuFrameTimer as p, Renderer as r, ThreeRenderer as s, AutoWorldOriginOptions as t, orthoFrustum as u, WeatherVisualOptions as v, defaultSkyPalette as w, SkyStar as x, CloudQuality as y, SceneAdmission as z };
1128
+ export { SkyReflectionFilter as A, SceneAdmission as B, SkyVisualOptions as C, evaluateEarthSky as D, EarthSkyState as E, AdmissionBacklog as F, AdmissionOptions as I, AdmissionSample as L, SkyReflections as M, createWebGlSkyReflectionFilter as N, skyTimeMs as O, reflectionStateFromLights as P, FrameAdmissionOptions as R, SkyVisual as S, CelestialPosition as T, WeatherVisual as _, RendererBackendPreference as a, SkyFrame as b, TopDownOrtho as c, ShadowFocus as d, ShadowQuality as f, FarShadowInfo as g, createGpuFrameTimer as h, RendererBackend as i, SkyReflectionState as j, starDirection as k, nextWorldOrigin as l, GpuFrameTimerOptions as m, CameraPose as n, RendererOptions as o, GpuFrameTimer as p, Renderer as r, ThreeRenderer as s, AutoWorldOriginOptions as t, orthoFrustum as u, WeatherVisualOptions as v, defaultSkyPalette as w, SkyStar as x, CloudQuality as y, FrameAdmissionQueue as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/molen-client",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -87,8 +87,8 @@
87
87
  "NOTICE.md"
88
88
  ],
89
89
  "dependencies": {
90
- "@bendyline/molen-materials": "0.0.12",
91
- "@bendyline/molen-schema": "0.0.11",
90
+ "@bendyline/molen-materials": "0.0.13",
91
+ "@bendyline/molen-schema": "0.0.12",
92
92
  "zod": "^4.6.5"
93
93
  },
94
94
  "peerDependencies": {
@@ -1,69 +0,0 @@
1
- import * as THREE from "three";
2
-
3
- //#region src/three/instance-batch.d.ts
4
- /** The geometry attributes a batch's instance matrices are read through, one matrix column each. */
5
- declare const INSTANCE_BATCH_MATRIX_COLUMNS: readonly string[];
6
- /** The geometry attribute a batch's instance colors are read through, when it has colors. */
7
- declare const INSTANCE_BATCH_COLOR = "instanceColor";
8
- /**
9
- * A batch's instance matrices: one interleaved buffer that WebGL reads as a `mat4` attribute and
10
- * WebGPU as four `vec4` columns, so either backend uploads it once. It keeps the `version` and
11
- * `usage` an `InstancedBufferAttribute` reports, which its buffer holds.
12
- */
13
- declare class InstanceMatrixAttribute extends THREE.InterleavedBufferAttribute {
14
- readonly isInstanceMatrixAttribute = true;
15
- constructor(buffer: THREE.InstancedInterleavedBuffer);
16
- get version(): number;
17
- get usage(): THREE.Usage;
18
- setUsage(usage: THREE.Usage): this;
19
- get updateRanges(): {
20
- start: number;
21
- count: number;
22
- }[];
23
- addUpdateRange(start: number, count: number): void;
24
- clearUpdateRanges(): void;
25
- }
26
- /**
27
- * An `InstancedMesh` whose instances live in a geometry of its own, so WebGPU builds its shaders
28
- * once for every batch of the same material and model layout instead of once per batch.
29
- *
30
- * Three's WebGPU renderer keys an instanced mesh's node build by the mesh, since its instance
31
- * matrices are a node bound to that mesh's buffer: every batch streamed in paid a build of its own,
32
- * about 10 ms of main thread each, which was most of a flight's streaming work. A batch instead
33
- * carries its matrices and colors as instanced vertex attributes of an `InstancedBufferGeometry`
34
- * that shares the model geometry's buffers, and the WebGPU driver reads them by name, the way it
35
- * reads `position`: one build serves every batch, and each draw binds its own batch's vertex
36
- * buffers, which a recorded render bundle replays as recorded. WebGL draws it as the
37
- * `InstancedMesh` it is, with no setup, through three's own instancing.
38
- *
39
- * It keeps `InstancedMesh`'s API: `count`, `setMatrixAt`, `setColorAt`, bounds, raycasting and
40
- * `dispose`. Assigning `geometry` selects the model it draws (a level of detail can swap it each
41
- * frame without a new build, as long as the models share an attribute layout); `geometry` then reads
42
- * back as the batch's own geometry and `sourceGeometry` as the model. Set colors before the first
43
- * draw: a batch drawn without colors keeps its build. Models with morph targets are not supported.
44
- */
45
- declare class InstanceBatch<TMaterial extends THREE.Material | THREE.Material[] = THREE.Material | THREE.Material[]> extends THREE.InstancedMesh<THREE.BufferGeometry, TMaterial> {
46
- readonly isInstanceBatch: true;
47
- constructor(geometry: THREE.BufferGeometry, material: TMaterial, count: number);
48
- /** The model geometry this batch draws (what `geometry` was last set to). */
49
- get sourceGeometry(): THREE.BufferGeometry;
50
- /**
51
- * Draw the instances in `matrices`, sixteen floats each as `Matrix4.elements` lays them out.
52
- * The batch takes the array over; set `count` to match.
53
- */
54
- setInstanceMatrices(matrices: Float32Array): this;
55
- /** Every geometry of this batch's own, one per model it has drawn. */
56
- batchGeometries(): THREE.BufferGeometry[];
57
- override copy(source: InstanceBatch<TMaterial>, recursive?: boolean): this;
58
- /**
59
- * Release the batch's buffers. Its own geometries are released with it, but not the model
60
- * geometry's buffers, which other batches share: a disposed batch is not drawn again.
61
- */
62
- override dispose(): this;
63
- }
64
- /** Whether `object` is an `InstanceBatch`. */
65
- declare function isInstanceBatch(object: unknown): object is InstanceBatch;
66
- /** Whether `geometry` is one of an `InstanceBatch`'s own geometries. */
67
- declare function isInstanceBatchGeometry(geometry: THREE.BufferGeometry): boolean;
68
- //#endregion
69
- export { isInstanceBatch as a, InstanceMatrixAttribute as i, INSTANCE_BATCH_MATRIX_COLUMNS as n, isInstanceBatchGeometry as o, InstanceBatch as r, INSTANCE_BATCH_COLOR as t };