@bendyline/molen-client 0.0.10 → 0.0.11

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/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { n as nlerp4, t as lerp3 } from "./math-ev_jEkRe.mjs";
2
2
  import { r as readModelSignals, t as createModelSignalVisual } from "./model-signals-DLgvjBeZ.mjs";
3
- import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-BVZjf4T-.mjs";
3
+ import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-BliZYUY1.mjs";
4
+ import { n as liveryGraphicTexture, t as applyLivery } from "./livery-C0abgthY.mjs";
4
5
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
5
6
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
6
7
  import * as THREE from "three";
@@ -154,10 +155,11 @@ var AdaptiveQualityController = class {
154
155
  const memory = this.memorySamples > 0 ? this.memoryTotal / this.memorySamples : 0;
155
156
  const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0);
156
157
  const measured = this.cpuSamples > 0 || this.gpuSamples > 0;
158
+ const measuredBoth = this.cpuSamples > 0 && this.gpuSamples > 0;
157
159
  const loading = this.loading;
158
160
  this.resetWindow();
159
161
  const overloaded = mean > this.targetFrameMs * 1.18 || this.p90FrameMs > this.targetFrameMs * 1.5 && this.slowFrameRatio >= .25;
160
- const headroom = !loading && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
162
+ const headroom = (!loading || measuredBoth) && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
161
163
  const renderBound = !loading || !measured || work > this.targetFrameMs * .75;
162
164
  this.overloadMs = overloaded && renderBound ? this.overloadMs + elapsed : 0;
163
165
  this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
@@ -678,6 +680,7 @@ var SceneMirror = class {
678
680
  backend.updateRenderable(id, renderable);
679
681
  this.bound.set(id, key);
680
682
  }
683
+ backend.setLivery?.(id, comps?.livery);
681
684
  if (backend.setModelSignals) {
682
685
  const spec = comps?.["model.signals"];
683
686
  backend.setModelSignals(id, spec, readModelSignals(spec?.sources, (name) => comps?.[name]));
@@ -1388,7 +1391,7 @@ var StaticMeshBatches = class {
1388
1391
  const entries = [];
1389
1392
  object.traverseVisible((child) => {
1390
1393
  const mesh = child;
1391
- if (!mesh.isMesh || mesh.isSkinnedMesh || mesh.isInstancedMesh || mesh.morphTargetInfluences || mesh.onBeforeRender !== THREE.Object3D.prototype.onBeforeRender || mesh.onAfterRender !== THREE.Object3D.prototype.onAfterRender) return;
1394
+ if (!mesh.isMesh || mesh.children.some((child) => child.userData.liveryMarking === true) || mesh.isSkinnedMesh || mesh.isInstancedMesh || mesh.morphTargetInfluences || mesh.onBeforeRender !== THREE.Object3D.prototype.onBeforeRender || mesh.onAfterRender !== THREE.Object3D.prototype.onAfterRender) return;
1392
1395
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
1393
1396
  if (materials.some((m) => m.transparent || !m.depthWrite || !m.depthTest || m.transmission > 0 || m.isShaderMaterial || m.isNodeMaterial || m.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile)) return;
1394
1397
  const matrix = new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld);
@@ -1574,6 +1577,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1574
1577
  animationTickRate = 30;
1575
1578
  objects = /* @__PURE__ */ new Map();
1576
1579
  gltf = /* @__PURE__ */ new Map();
1580
+ liveries = /* @__PURE__ */ new Map();
1577
1581
  modelSignals = /* @__PURE__ */ new Map();
1578
1582
  identities = /* @__PURE__ */ new Map();
1579
1583
  lights = /* @__PURE__ */ new Map();
@@ -1803,6 +1807,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1803
1807
  return;
1804
1808
  }
1805
1809
  group.add(instance);
1810
+ this.bindLivery(id, instance);
1806
1811
  binding.clips = clips;
1807
1812
  this.bindModelSignals(id, instance);
1808
1813
  this.applyAnimation(id, binding, instance);
@@ -1871,6 +1876,30 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1871
1876
  this.create(id, renderable);
1872
1877
  }
1873
1878
  /** Latest mirrored values are retained while the model loads. No simulation state is changed. */
1879
+ setLivery(id, data) {
1880
+ const previous = this.liveries.get(id);
1881
+ const key = data === void 0 ? void 0 : JSON.stringify(data);
1882
+ if (previous?.key === key) return;
1883
+ this.batches?.remove(id);
1884
+ this.batchDirty.add(id);
1885
+ previous?.visual?.dispose();
1886
+ this.liveries.delete(id);
1887
+ if (data !== void 0) {
1888
+ this.liveries.set(id, {
1889
+ key,
1890
+ data
1891
+ });
1892
+ const instance = this.gltf.has(id) ? this.objects.get(id)?.children[0] : void 0;
1893
+ if (instance) this.bindLivery(id, instance);
1894
+ }
1895
+ }
1896
+ bindLivery(id, instance) {
1897
+ const state = this.liveries.get(id);
1898
+ if (!state) return;
1899
+ state.visual = applyLivery(instance, state.data);
1900
+ for (const warning of state.visual.warnings) console.warn(`[molen] entity "${id}": livery ${warning}`);
1901
+ }
1902
+ /** Latest mirrored values are retained while the model loads. No simulation state is changed. */
1874
1903
  setModelSignals(id, spec, signals) {
1875
1904
  const previous = this.modelSignals.get(id);
1876
1905
  const key = spec === void 0 ? void 0 : JSON.stringify(spec);
@@ -1916,6 +1945,8 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1916
1945
  state?.visual?.update(state.signals, this.animationTick / this.animationTickRate);
1917
1946
  }
1918
1947
  destroy(id) {
1948
+ this.liveries.get(id)?.visual?.dispose();
1949
+ this.liveries.delete(id);
1919
1950
  this.modelSignals.delete(id);
1920
1951
  this.batches?.remove(id);
1921
1952
  this.batchDirty.delete(id);
@@ -2238,6 +2269,8 @@ var FrameAdmissionQueue = class {
2238
2269
  maxMs;
2239
2270
  maxBytes;
2240
2271
  maxJobs;
2272
+ /** Recent work time per label (ms, smoothed): what the next job of that kind will likely take. */
2273
+ expected = /* @__PURE__ */ new Map();
2241
2274
  constructor(options = {}) {
2242
2275
  this.options = options;
2243
2276
  this.clock = options.now ?? (() => performance.now());
@@ -2248,11 +2281,20 @@ var FrameAdmissionQueue = class {
2248
2281
  this.maxMs = options.maxMilliseconds ?? 2;
2249
2282
  this.maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
2250
2283
  this.maxJobs = options.maxJobs ?? 32;
2251
- if (![
2252
- this.maxMs,
2253
- this.maxBytes,
2254
- this.maxJobs
2255
- ].every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2284
+ this.setLimits({});
2285
+ }
2286
+ /**
2287
+ * Change the per-frame budget from the next frame on; omitted limits keep their values. A host
2288
+ * can admit more when frames have time to spare (an adaptive quality tier, say).
2289
+ */
2290
+ setLimits(limits) {
2291
+ const next = [
2292
+ limits.maxMilliseconds ?? this.maxMs,
2293
+ limits.maxBytes ?? this.maxBytes,
2294
+ limits.maxJobs ?? this.maxJobs
2295
+ ];
2296
+ if (!next.every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2297
+ [this.maxMs, this.maxBytes, this.maxJobs] = next;
2256
2298
  }
2257
2299
  run(task, options = {}) {
2258
2300
  if (this.disposed || options.signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
@@ -2276,7 +2318,11 @@ var FrameAdmissionQueue = class {
2276
2318
  }
2277
2319
  };
2278
2320
  options.signal?.addEventListener("abort", job.abort, { once: true });
2279
- (options.priority === "background" ? this.background : this.jobs).push(job);
2321
+ if (options.priority === "background") this.background.push(job);
2322
+ else if (options.priority === "urgent") {
2323
+ const after = this.jobs.findIndex((queued) => queued.options.priority !== "urgent");
2324
+ this.jobs.splice(after < 0 ? this.jobs.length : after, 0, job);
2325
+ } else this.jobs.push(job);
2280
2326
  this.request();
2281
2327
  });
2282
2328
  if (options.priority === "background") {
@@ -2334,7 +2380,8 @@ var FrameAdmissionQueue = class {
2334
2380
  const next = lane[0];
2335
2381
  if (next === void 0) break;
2336
2382
  const cost = next.options.bytes ?? 0;
2337
- if (count > 0 && (count >= this.maxJobs || this.clock() - start >= this.maxMs || bytes + cost > this.maxBytes)) break;
2383
+ const label = next.options.label ?? "admission";
2384
+ if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > this.maxMs || bytes + cost > this.maxBytes)) break;
2338
2385
  lane.shift();
2339
2386
  this.forget(next);
2340
2387
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
@@ -2349,10 +2396,12 @@ var FrameAdmissionQueue = class {
2349
2396
  next.reject(error);
2350
2397
  }
2351
2398
  const workMs = this.clock() - began;
2399
+ const previous = this.expected.get(label);
2400
+ this.expected.set(label, previous === void 0 ? workMs : previous + (workMs - previous) * .25);
2352
2401
  count++;
2353
2402
  bytes += cost;
2354
2403
  this.options.onSample?.({
2355
- label: next.options.label ?? "admission",
2404
+ label,
2356
2405
  queueMs: began - next.queued,
2357
2406
  workMs,
2358
2407
  bytes: cost,
@@ -2575,6 +2624,8 @@ function starDirection(rightAscensionDeg, declinationDeg, state) {
2575
2624
  //#endregion
2576
2625
  //#region src/sky/visual.ts
2577
2626
  const RAD$1 = Math.PI / 180;
2627
+ /** Sky motion (radians) before the dome and stars redraw: about half a pixel at 70 degrees. */
2628
+ const SKY_REDRAW_ANGLE = 4e-4;
2578
2629
  const clamp$3 = (x) => Math.max(0, Math.min(1, x));
2579
2630
  const rgb$1 = (color) => [
2580
2631
  color.r,
@@ -2642,6 +2693,13 @@ var SkyVisual = class {
2642
2693
  catalog;
2643
2694
  palette;
2644
2695
  lastTime;
2696
+ /**
2697
+ * What the dome's colors and the stars were last written for. The sun and the sky turn a
2698
+ * quarter of a degree a minute: rewriting the dome and every star each second cost a frame
2699
+ * 3-5 ms for changes far below a pixel, so they are rewritten once those changes could show.
2700
+ */
2701
+ drawnDome;
2702
+ drawnStars;
2645
2703
  cloudAttenuation = 0;
2646
2704
  currentFrame;
2647
2705
  currentReflections;
@@ -2720,6 +2778,10 @@ var SkyVisual = class {
2720
2778
  const data = this.data;
2721
2779
  const time = data.mode === "earth" ? Math.floor(skyTimeMs(data.time, simulationSeconds) / 1e3) * 1e3 : 0;
2722
2780
  if (time === this.lastTime) return this.currentFrame;
2781
+ if (this.lastTime === void 0) {
2782
+ this.drawnDome = void 0;
2783
+ this.drawnStars = void 0;
2784
+ }
2723
2785
  this.lastTime = time;
2724
2786
  const earth = data.mode === "earth" ? evaluateEarthSky(time, data.observer) : void 0;
2725
2787
  const sunDirection = earth?.sun.direction ?? skyDirection(data.mode === "custom" ? data.sunBody.direction : [
@@ -2767,6 +2829,13 @@ var SkyVisual = class {
2767
2829
  this.ambientLight.color.copy(this.palette.nightHorizon).lerp(this.palette.dayHorizon, daylight);
2768
2830
  this.ambientLight.groundColor.copy(this.palette.ground);
2769
2831
  this.ambientLight.intensity = (light?.nightAmbient ?? .025) * (1 - daylight) + (light?.dayAmbient ?? .6) * daylight;
2832
+ const reference = light?.referenceElevation;
2833
+ if (reference !== void 0 && altitude > reference) {
2834
+ const level = (degrees) => this.ambientLight.intensity + this.sunLight.intensity * Math.sin(degrees * RAD$1);
2835
+ const scale = level(reference) / level(altitude);
2836
+ this.sunLight.intensity *= scale;
2837
+ this.ambientLight.intensity *= scale;
2838
+ }
2770
2839
  this.sunLight.intensity *= 1 - this.cloudAttenuation * .92;
2771
2840
  this.moonLight.intensity *= 1 - this.cloudAttenuation * .9;
2772
2841
  this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
@@ -2823,6 +2892,12 @@ var SkyVisual = class {
2823
2892
  ]), 200);
2824
2893
  }
2825
2894
  updateDome(altitude, sun, daylight) {
2895
+ const drawn = this.drawnDome;
2896
+ if (drawn !== void 0 && drawn.sun.distanceToSquared(sun) < SKY_REDRAW_ANGLE ** 2 && Math.abs(drawn.daylight - daylight) < .001) return;
2897
+ this.drawnDome = {
2898
+ sun: sun.clone(),
2899
+ daylight
2900
+ };
2826
2901
  const colors = this.dome.geometry.getAttribute("color");
2827
2902
  const positions = this.dome.geometry.getAttribute("position");
2828
2903
  const horizon = this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight);
@@ -2890,6 +2965,13 @@ var SkyVisual = class {
2890
2965
  updateStars(rotation, visibility, moon, moonDiameter) {
2891
2966
  this.stars.visible = visibility > 0 && this.catalog.length > 0;
2892
2967
  if (!this.stars.visible) return;
2968
+ const drawn = this.drawnStars;
2969
+ if (drawn !== void 0 && Math.abs(drawn.visibility - visibility) < .001 && drawn.rotation.elements.every((value, i) => Math.abs(value - rotation.elements[i]) < SKY_REDRAW_ANGLE) && (moon === void 0 ? drawn.moon === void 0 : drawn.moon !== void 0 && drawn.moon.distanceToSquared(moon) < SKY_REDRAW_ANGLE ** 2)) return;
2970
+ this.drawnStars = {
2971
+ rotation: rotation.clone(),
2972
+ visibility,
2973
+ moon: moon?.clone()
2974
+ };
2893
2975
  const positions = this.stars.geometry.getAttribute("position");
2894
2976
  const colors = this.stars.geometry.getAttribute("color");
2895
2977
  const d = new THREE.Vector3(), right = new THREE.Vector3(), up = new THREE.Vector3(), p = new THREE.Vector3();
@@ -3601,6 +3683,10 @@ var Renderer = class Renderer {
3601
3683
  warmupMaterial;
3602
3684
  warmedPrograms = /* @__PURE__ */ new WeakMap();
3603
3685
  warmedMeshes = /* @__PURE__ */ new WeakMap();
3686
+ /** Per material, one prepared mesh of each kind it draws; see `prepareMaterialChange`. */
3687
+ materialMeshes = /* @__PURE__ */ new WeakMap();
3688
+ /** The scene's visible lights for warm-up builds, gathered once between rendered frames. */
3689
+ preparationLights;
3604
3690
  /**
3605
3691
  * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
3606
3692
  * `prepareVariants`.
@@ -3651,8 +3737,12 @@ var Renderer = class Renderer {
3651
3737
  occlusion;
3652
3738
  occlusionLoad;
3653
3739
  occlusionSuspended = false;
3654
- /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
3655
- webgpuShadowLights = /* @__PURE__ */ new WeakSet();
3740
+ /** Sun lights that have cast shadows: 'off' parks their maps; see setShadowQuality. */
3741
+ shadowLights = /* @__PURE__ */ new WeakSet();
3742
+ /** Kinds of shadow caster prepared so far (WebGL); see noteShadowCaster. */
3743
+ casterVariants = /* @__PURE__ */ new Set();
3744
+ /** Whether the shadow pass has drawn shadowCasterWarmup's casters (WebGL). */
3745
+ shadowCastersWarmed = false;
3656
3746
  reflectionClearColor = Object.assign(new THREE.Color(), { a: 1 });
3657
3747
  starCatalog;
3658
3748
  activeWeather;
@@ -3685,17 +3775,33 @@ var Renderer = class Renderer {
3685
3775
  radius: focus.radius
3686
3776
  };
3687
3777
  }
3688
- /** Turn sun shadows on at a map resolution, or off, without rebuilding the environment. */
3778
+ /**
3779
+ * Turn sun shadows on at a map resolution, or off, without rebuilding the environment. Once a
3780
+ * light has cast shadows, 'off' stops redrawing its map and fades it out, so every lit shader
3781
+ * keeps the shadow inputs it was built with: a host that turns shadows on once before its first
3782
+ * frame can then switch them freely (adaptive quality tiers do) without rebuilding a shader.
3783
+ */
3689
3784
  setShadowQuality(quality) {
3690
3785
  const enabled = quality !== "off";
3786
+ let parked = false;
3691
3787
  for (const light of this.sunLights()) {
3692
- if (this.backend === "webgpu" && this.webgpuShadowLights.has(light)) {
3788
+ if (this.backend === "webgpu" && this.shadowLights.has(light)) {
3693
3789
  light.shadow.autoUpdate = enabled;
3694
3790
  light.shadow.intensity = enabled ? 1 : 0;
3695
3791
  continue;
3696
3792
  }
3697
- light.castShadow = enabled;
3698
- if (!enabled) continue;
3793
+ if (!enabled) {
3794
+ if (this.shadowLights.has(light)) {
3795
+ light.shadow.autoUpdate = false;
3796
+ light.shadow.intensity = 0;
3797
+ parked = true;
3798
+ } else light.castShadow = false;
3799
+ continue;
3800
+ }
3801
+ if (!light.castShadow) this.shadowCastersWarmed = false;
3802
+ light.castShadow = true;
3803
+ light.shadow.autoUpdate = true;
3804
+ light.shadow.intensity = 1;
3699
3805
  const size = SHADOW_MAP_SIZE[quality];
3700
3806
  if (light.shadow.mapSize.x !== size) {
3701
3807
  light.shadow.mapSize.set(size, size);
@@ -3704,9 +3810,10 @@ var Renderer = class Renderer {
3704
3810
  light.shadow.map = null;
3705
3811
  }
3706
3812
  }
3707
- if (this.backend === "webgpu") this.webgpuShadowLights.add(light);
3813
+ this.shadowLights.add(light);
3708
3814
  }
3709
3815
  if (this.backend === "webgpu" && this.three.shadowMap.enabled) return;
3816
+ if (parked && this.three.shadowMap.enabled) return;
3710
3817
  this.three.shadowMap.enabled = enabled;
3711
3818
  this.three.shadowMap.type = quality === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
3712
3819
  }
@@ -4011,28 +4118,34 @@ var Renderer = class Renderer {
4011
4118
  * other levels afterwards in the background, so publication waits only for what can be seen.
4012
4119
  * Queued work is cancelled once every caller waiting for it has aborted, and background work
4013
4120
  * once its mesh or geometry is disposed.
4121
+ *
4122
+ * `root.userData.admissionPriority` admits the root's own work as `'urgent'` (ahead of normal
4123
+ * work) or `'background'` (only in budget normal work leaves: content nobody waits on yet).
4014
4124
  */
4015
4125
  async prepareObject(root, signal, parent) {
4016
4126
  if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
4017
4127
  updateDetachedWorldMatrix(root, parent);
4018
4128
  const lods = parent === void 0 ? void 0 : unselectedLodLevels(root, this.camera);
4019
4129
  const deferredLevels = lods === void 0 ? void 0 : new Set([...lods.values()].flat());
4020
- const foreground = createLane(false);
4130
+ const priority = root.userData.admissionPriority;
4131
+ const foreground = createLane(priority === "background", priority === "urgent");
4021
4132
  const background = createLane(true);
4133
+ const state = this.programState();
4022
4134
  const interest = signal === void 0 ? "pinned" : new WarmupInterest(this.cancel);
4023
4135
  const deferred = [];
4024
4136
  const switching = [];
4025
4137
  root.traverse((object) => {
4026
4138
  const mesh = object;
4027
4139
  if (!mesh.isMesh) return;
4140
+ this.noteShadowCaster(mesh);
4028
4141
  if (mesh.userData.materialVariants !== void 0) switching.push(mesh);
4029
4142
  if (deferredLevels !== void 0 && withinAny(mesh, root, deferredLevels)) deferred.push(mesh);
4030
- else this.prepareMesh(mesh, foreground, interest);
4143
+ else this.prepareMesh(mesh, foreground, interest, state);
4031
4144
  });
4032
4145
  this.flushWebGlBatches(foreground);
4033
4146
  const deferredInterests = deferred.map((mesh) => {
4034
4147
  const meshInterest = new WarmupInterest(this.cancel);
4035
- this.prepareMesh(mesh, background, meshInterest);
4148
+ this.prepareMesh(mesh, background, meshInterest, state);
4036
4149
  return meshInterest;
4037
4150
  });
4038
4151
  this.flushWebGlBatches(background);
@@ -4060,7 +4173,30 @@ var Renderer = class Renderer {
4060
4173
  const failure = results.find((result) => result.status === "rejected");
4061
4174
  if (failure?.status === "rejected") throw failure.reason;
4062
4175
  }
4063
- prepareMesh(mesh, lane, interest) {
4176
+ /**
4177
+ * Build `next`'s shaders for every kind of prepared mesh that draws `current`, before the caller
4178
+ * copies `next` into `current`: a progressive material upgrading its placeholder in place once a
4179
+ * texture bake lands. Three shares a program between materials built alike, so the upgraded
4180
+ * placeholder draws with it at once. Otherwise every mesh showing the placeholder built its new
4181
+ * shaders in the next frame, together: seconds of frozen flight shortly after loading. The work
4182
+ * runs in the background lane. Keep `next` alive while `current` uses the shared program.
4183
+ */
4184
+ async prepareMaterialChange(current, next) {
4185
+ if (this.disposed) return;
4186
+ const builds = [];
4187
+ for (const ref of this.materialMeshes.get(current)?.values() ?? []) {
4188
+ const mesh = ref.deref();
4189
+ if (mesh === void 0) continue;
4190
+ const warmup = this.warmup(() => this.compileMesh(mesh, next), createLane(true), {
4191
+ label: "shader-upgrade",
4192
+ bytes: 0
4193
+ });
4194
+ warmup.pinned = true;
4195
+ builds.push(warmup.promise);
4196
+ }
4197
+ await Promise.allSettled(builds);
4198
+ }
4199
+ prepareMesh(mesh, lane, interest, state) {
4064
4200
  const need = (promise) => {
4065
4201
  lane.jobs.add(promise);
4066
4202
  const warmup = this.warmups.get(promise);
@@ -4070,7 +4206,7 @@ var Renderer = class Renderer {
4070
4206
  if (!lane.background) this.admission.promote(promise);
4071
4207
  };
4072
4208
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
4073
- const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}`;
4209
+ const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.instanceColor)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}/${Object.keys(mesh.geometry.morphAttributes).sort().join(",")}`;
4074
4210
  const variants = [];
4075
4211
  for (const material of materials) {
4076
4212
  for (const value of Object.values(material)) {
@@ -4087,12 +4223,18 @@ var Renderer = class Renderer {
4087
4223
  this.rememberPreparation([value], upload);
4088
4224
  need(upload.promise);
4089
4225
  }
4226
+ let meshes = this.materialMeshes.get(material);
4227
+ if (!meshes) {
4228
+ meshes = /* @__PURE__ */ new Map();
4229
+ this.materialMeshes.set(material, meshes);
4230
+ }
4231
+ if (meshes.get(key)?.deref() === void 0) meshes.set(key, new WeakRef(mesh));
4090
4232
  let map = this.warmedPrograms.get(material);
4091
4233
  if (!map) {
4092
4234
  map = /* @__PURE__ */ new Map();
4093
4235
  this.warmedPrograms.set(material, map);
4094
4236
  }
4095
- const variantKey = `${material.version}/${key}`;
4237
+ const variantKey = `${material.version}/${key}/${state}`;
4096
4238
  const existing = map.get(variantKey);
4097
4239
  if (existing) need(existing);
4098
4240
  else variants.push({
@@ -4232,7 +4374,7 @@ var Renderer = class Renderer {
4232
4374
  const promise = this.admission.run(task, {
4233
4375
  ...options,
4234
4376
  signal: controller.signal,
4235
- priority: lane.background ? "background" : "normal"
4377
+ priority: lane.background ? "background" : lane.urgent ? "urgent" : "normal"
4236
4378
  });
4237
4379
  const warmup = {
4238
4380
  promise,
@@ -4272,6 +4414,15 @@ var Renderer = class Renderer {
4272
4414
  }
4273
4415
  /** Returns whether any level is still being prepared. */
4274
4416
  holdUnpreparedLevel(lod, shown) {
4417
+ if (lod.levels.length === 0) {
4418
+ let pending = false;
4419
+ for (const child of lod.children) {
4420
+ if (!this.pendingWithin(child, child.visible)) continue;
4421
+ pending = true;
4422
+ child.visible = false;
4423
+ }
4424
+ return pending;
4425
+ }
4275
4426
  const ready = lod.levels.map((level) => !this.pendingWithin(level.object, false));
4276
4427
  if (ready.every(Boolean)) return false;
4277
4428
  const wanted = lod.getCurrentLevel();
@@ -4314,6 +4465,35 @@ var Renderer = class Renderer {
4314
4465
  warmup.forget.push(forget);
4315
4466
  promise.catch(forget);
4316
4467
  }
4468
+ /**
4469
+ * While WebGL shadows are parked the shadow pass never runs, so no depth program is built for
4470
+ * the casters arriving meanwhile, and the first frame with shadows back built every one of them
4471
+ * at once (an adaptive tier change, mid-flight). A caster of a kind the map has not drawn yet
4472
+ * asks the parked map for one render, which builds its depth program as it streams in. The
4473
+ * kinds follow three's shadow pass: one depth material, cloned for alpha-tested maps,
4474
+ * displacement or clipping, built per mesh kind and side.
4475
+ */
4476
+ noteShadowCaster(mesh) {
4477
+ if (this.backend !== "webgl" || !mesh.castShadow) return;
4478
+ const kind = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.morphAttributes).sort().join(",")}`;
4479
+ let fresh = false;
4480
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
4481
+ const textured = material;
4482
+ const variant = mesh.customDepthMaterial !== void 0 ? `custom:${mesh.customDepthMaterial.uuid}` : [
4483
+ kind,
4484
+ material.alphaTest > 0 && (textured.map != null || textured.alphaMap != null),
4485
+ textured.displacementMap != null && textured.displacementScale !== 0,
4486
+ material.alphaToCoverage,
4487
+ material.clipShadows && (material.clippingPlanes?.length ?? 0) > 0,
4488
+ material.shadowSide ?? material.side
4489
+ ].join("/");
4490
+ if (this.casterVariants.has(variant)) continue;
4491
+ this.casterVariants.add(variant);
4492
+ fresh = true;
4493
+ }
4494
+ if (!fresh) return;
4495
+ for (const light of this.sunLights()) if (this.shadowLights.has(light) && !light.shadow.autoUpdate) light.shadow.needsUpdate = true;
4496
+ }
4317
4497
  /** Build `mesh` for the frame's draw target, drawn with `material` when given. */
4318
4498
  compileMesh(mesh, material) {
4319
4499
  const load = this.occlusionOptions !== void 0 ? this.occlusionLoad : void 0;
@@ -4326,14 +4506,85 @@ var Renderer = class Renderer {
4326
4506
  mesh.visible = true;
4327
4507
  mesh.frustumCulled = false;
4328
4508
  if (material !== void 0) mesh.material = material;
4509
+ const traverse = this.scene.traverseVisible;
4510
+ const ownTraverse = Object.hasOwn(this.scene, "traverseVisible");
4329
4511
  try {
4330
- return occlusion !== void 0 ? occlusion.compile(mesh) : this.three.compileAsync(mesh, this.camera, this.scene);
4512
+ if (this.scene.onBeforeRender === THREE.Object3D.prototype.onBeforeRender) {
4513
+ const lights = this.sceneLights();
4514
+ this.scene.traverseVisible = (visit) => {
4515
+ for (const light of lights) visit(light);
4516
+ };
4517
+ }
4518
+ if (occlusion !== void 0) return occlusion.compile(mesh);
4519
+ if (this.backend === "webgl") return this.compileWebGl(mesh);
4520
+ return this.three.compileAsync(mesh, this.camera, this.scene);
4331
4521
  } finally {
4522
+ if (ownTraverse) this.scene.traverseVisible = traverse;
4523
+ else delete this.scene.traverseVisible;
4332
4524
  mesh.visible = visible;
4333
4525
  mesh.frustumCulled = culled;
4334
4526
  mesh.material = shown;
4335
4527
  }
4336
4528
  }
4529
+ /**
4530
+ * Three's compileAsync, but waiting for the programs built for this mesh. Three polls each
4531
+ * material's current program, which the next frame resets for whatever it drew last: a
4532
+ * material shared with drawn meshes (every building's wall) reported its ready program while
4533
+ * the instanced variant was still linking, and that variant's first draw waited for the link
4534
+ * mid-frame (130 ms in flight).
4535
+ */
4536
+ compileWebGl(mesh) {
4537
+ const renderer = this.three;
4538
+ const all = () => renderer.info.programs ?? [];
4539
+ const known = new Set(all());
4540
+ const programs = /* @__PURE__ */ new Set();
4541
+ for (const material of renderer.compile(mesh, this.camera, this.scene)) {
4542
+ const program = renderer.properties.get(material).currentProgram;
4543
+ if (program !== void 0) programs.add(program);
4544
+ }
4545
+ for (const program of all()) if (!known.has(program)) programs.add(program);
4546
+ return new Promise((resolve) => {
4547
+ const check = () => {
4548
+ for (const program of programs) if (program.program === void 0 || program.isReady()) programs.delete(program);
4549
+ if (programs.size === 0) resolve();
4550
+ else setTimeout(check, 10);
4551
+ };
4552
+ check();
4553
+ });
4554
+ }
4555
+ /** The scene's visible lights, gathered once between rendered frames for warm-up builds. */
4556
+ sceneLights() {
4557
+ this.preparationLights ??= (() => {
4558
+ const lights = [];
4559
+ THREE.Object3D.prototype.traverseVisible.call(this.scene, (object) => {
4560
+ if (object.isLight) lights.push(object);
4561
+ });
4562
+ return lights;
4563
+ })();
4564
+ return this.preparationLights;
4565
+ }
4566
+ /**
4567
+ * What a lit program is built for besides its material and mesh: the scene's lights and which
4568
+ * cast shadows, the shadow map, fog, environment and output. Warm-ups are remembered under it.
4569
+ * Without it a material built before the sky's sun, its shadows or its reflections existed
4570
+ * counted as prepared, and the next tile drawing it built the real program mid-frame.
4571
+ */
4572
+ programState() {
4573
+ let lights = "";
4574
+ for (const light of this.sceneLights()) lights += `${light.type}${light.castShadow ? "*" : ""},`;
4575
+ const fog = this.scene.fog;
4576
+ const environment = this.scene.environment;
4577
+ const image = environment?.image;
4578
+ return [
4579
+ lights,
4580
+ this.three.shadowMap.enabled,
4581
+ this.three.shadowMap.type,
4582
+ fog === null ? "" : fog.isFogExp2 ? "exp2" : "linear",
4583
+ environment === null ? "" : `${environment.mapping}:${image?.height ?? ""}`,
4584
+ this.three.toneMapping,
4585
+ this.three.outputColorSpace
4586
+ ].join("/");
4587
+ }
4337
4588
  prepareWebGlGeometries(meshes) {
4338
4589
  const renderer = this.three;
4339
4590
  this.warmupTarget ??= new THREE.WebGLRenderTarget(1, 1);
@@ -4367,6 +4618,7 @@ var Renderer = class Renderer {
4367
4618
  }
4368
4619
  }
4369
4620
  render() {
4621
+ this.preparationLights = void 0;
4370
4622
  if (this.disposed) throw new Error("Renderer has been disposed");
4371
4623
  if (this.deviceLossReason !== void 0) throw new Error(`WebGPU device lost: ${this.deviceLossReason}. Recreate the viewer, or reload with WebGL.`);
4372
4624
  if (this.backend === "webgpu") this.three.info.reset();
@@ -4458,6 +4710,7 @@ var Renderer = class Renderer {
4458
4710
  hideReflectedAmbient(light) {
4459
4711
  const hidden = this.hiddenAmbient;
4460
4712
  if (hidden !== void 0 && hidden.light !== light) {
4713
+ if (hidden.light.visible !== hidden.visible) this.shadowCastersWarmed = false;
4461
4714
  hidden.light.visible = hidden.visible;
4462
4715
  this.hiddenAmbient = void 0;
4463
4716
  }
@@ -4466,10 +4719,67 @@ var Renderer = class Renderer {
4466
4719
  light,
4467
4720
  visible: light.visible
4468
4721
  };
4722
+ if (light.visible) this.shadowCastersWarmed = false;
4469
4723
  light.visible = false;
4470
4724
  }
4471
4725
  renderScene() {
4472
- this.optimized(() => this.three.render(this.scene, this.camera));
4726
+ const warmup = this.shadowCasterWarmup();
4727
+ if (warmup !== void 0) this.scene.add(warmup);
4728
+ try {
4729
+ this.optimized(() => this.three.render(this.scene, this.camera));
4730
+ } finally {
4731
+ if (warmup !== void 0) {
4732
+ warmup.removeFromParent();
4733
+ for (const child of warmup.children) {
4734
+ const mesh = child;
4735
+ mesh.geometry.dispose();
4736
+ mesh.material.dispose();
4737
+ }
4738
+ }
4739
+ }
4740
+ }
4741
+ /**
4742
+ * Once WebGL sun shadows draw, a frame of degenerate casters (one plain and one instanced mesh
4743
+ * per side): the shadow pass builds a depth program for each kind of caster the first time it
4744
+ * draws one, and the first double-sided caster in view held a mid-flight frame 10 ms. The
4745
+ * shadow pass keeps its depth materials, so the programs stay built; three keys them by the
4746
+ * scene's light counts too, so a light the renderer shows or hides warms them again.
4747
+ */
4748
+ shadowCasterWarmup() {
4749
+ if (this.shadowCastersWarmed || this.backend !== "webgl" || !this.three.shadowMap.enabled) return void 0;
4750
+ if (!this.sunLights().some((light) => light.castShadow && light.shadow.intensity > 0)) return void 0;
4751
+ this.shadowCastersWarmed = true;
4752
+ const group = new THREE.Group();
4753
+ group.name = "molen:shadow-caster-warmup";
4754
+ for (const side of [
4755
+ THREE.FrontSide,
4756
+ THREE.BackSide,
4757
+ THREE.DoubleSide
4758
+ ]) for (const instanced of [false, true]) {
4759
+ const geometry = new THREE.BufferGeometry();
4760
+ geometry.setAttribute("position", new THREE.Float32BufferAttribute(new Array(9).fill(0), 3));
4761
+ geometry.setAttribute("normal", new THREE.Float32BufferAttribute([
4762
+ 0,
4763
+ 1,
4764
+ 0,
4765
+ 0,
4766
+ 1,
4767
+ 0,
4768
+ 0,
4769
+ 1,
4770
+ 0
4771
+ ], 3));
4772
+ const material = new THREE.MeshBasicMaterial({
4773
+ side,
4774
+ colorWrite: false,
4775
+ depthWrite: false
4776
+ });
4777
+ const mesh = instanced ? new THREE.InstancedMesh(geometry, material, 1) : new THREE.Mesh(geometry, material);
4778
+ mesh.castShadow = true;
4779
+ mesh.frustumCulled = false;
4780
+ group.add(mesh);
4781
+ }
4782
+ return group;
4473
4783
  }
4474
4784
  optimized(draw) {
4475
4785
  if (this.optimizer === void 0) {
@@ -4610,9 +4920,10 @@ var WarmupInterest = class {
4610
4920
  return [...this.joined].map((warmup) => warmup.promise);
4611
4921
  }
4612
4922
  };
4613
- function createLane(background) {
4923
+ function createLane(background, urgent = false) {
4614
4924
  return {
4615
4925
  background,
4926
+ urgent,
4616
4927
  jobs: /* @__PURE__ */ new Set(),
4617
4928
  glAttributes: /* @__PURE__ */ new Set(),
4618
4929
  glBatches: []
@@ -4639,6 +4950,11 @@ function unselectedLodLevels(root, camera) {
4639
4950
  const lod = object;
4640
4951
  if (!lod.isLOD || !lod.autoUpdate) return;
4641
4952
  lod.update(camera);
4953
+ if (lod.levels.length === 0) {
4954
+ const hidden = lod.children.filter((child) => !child.visible);
4955
+ if (hidden.length > 0) unselected.set(lod, hidden);
4956
+ return;
4957
+ }
4642
4958
  if (lod.levels.length < 2) return;
4643
4959
  const selected = lod.getCurrentLevel();
4644
4960
  unselected.set(lod, lod.levels.filter((_, index) => index !== selected).map((level) => level.object));
@@ -5193,4 +5509,4 @@ function decodeStarCatalog(input) {
5193
5509
  }));
5194
5510
  }
5195
5511
  //#endregion
5196
- export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, InputMap, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, lerp3, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };
5512
+ export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, InputMap, 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, lerp3, liveryGraphicTexture, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };