@bendyline/molen-client 0.0.11 → 0.0.12

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,7 +1,9 @@
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
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
+ import { createGlassVisual } from "./glass.mjs";
5
+ import { n as liveryGraphicTexture, t as applyLivery } from "./livery-qcDLzbU9.mjs";
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";
5
7
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
6
8
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
7
9
  import * as THREE from "three";
@@ -578,6 +580,10 @@ function readTransform(components) {
578
580
  }
579
581
  function readRenderable(components) {
580
582
  const r = components.renderable;
583
+ if (r === void 0 && components.glass !== void 0) return {
584
+ kind: "glass",
585
+ ref: "glass"
586
+ };
581
587
  if (r?.kind === void 0 || r.ref === void 0) return void 0;
582
588
  return r;
583
589
  }
@@ -681,6 +687,7 @@ var SceneMirror = class {
681
687
  this.bound.set(id, key);
682
688
  }
683
689
  backend.setLivery?.(id, comps?.livery);
690
+ backend.setGlass?.(id, comps?.glass, comps?.glassState);
684
691
  if (backend.setModelSignals) {
685
692
  const spec = comps?.["model.signals"];
686
693
  backend.setModelSignals(id, spec, readModelSignals(spec?.sources, (name) => comps?.[name]));
@@ -803,6 +810,7 @@ function createClientCore(opts) {
803
810
  let bufferTickRate;
804
811
  let awaitingKeyframe = false;
805
812
  let playbackPaused;
813
+ let active = true;
806
814
  const delayTicks = opts.interpolationDelayTicks;
807
815
  const nowMs = opts.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
808
816
  const eventHandlers = /* @__PURE__ */ new Map();
@@ -936,6 +944,10 @@ function createClientCore(opts) {
936
944
  sendCommand,
937
945
  command: (type, payload = {}) => sendCommand(localCommand(seq++, type, payload)),
938
946
  control: (action) => {
947
+ if (action.action === "set-active") {
948
+ if (action.active && !active) buffer?.resumeClock(nowMs());
949
+ active = action.active;
950
+ }
939
951
  if (action.action === "resume") {
940
952
  if (playbackPaused !== false) buffer?.resumeClock(nowMs());
941
953
  playbackPaused = false;
@@ -969,6 +981,49 @@ function describeLinkFailure(kind, ev) {
969
981
  return "kernel link error (no detail; the worker may have failed to load)";
970
982
  }
971
983
  //#endregion
984
+ //#region src/page-activity.ts
985
+ /** Observe whether the page is both visible and focused; reports the initial state immediately. */
986
+ function observePageActivity(onChange) {
987
+ if (typeof document === "undefined") return () => {};
988
+ const doc = document;
989
+ const win = doc.defaultView ?? (typeof window !== "undefined" ? window : void 0);
990
+ let focused = doc.hasFocus?.() ?? true;
991
+ let previous;
992
+ const update = () => {
993
+ const active = !doc.hidden && focused;
994
+ if (active === previous) return;
995
+ previous = active;
996
+ onChange(active);
997
+ };
998
+ const focus = () => {
999
+ focused = true;
1000
+ update();
1001
+ };
1002
+ const blur = () => {
1003
+ focused = false;
1004
+ update();
1005
+ };
1006
+ const visibility = () => {
1007
+ focused = doc.hasFocus?.() ?? focused;
1008
+ update();
1009
+ };
1010
+ win?.addEventListener?.("focus", focus);
1011
+ win?.addEventListener?.("blur", blur);
1012
+ doc.addEventListener("visibilitychange", visibility);
1013
+ const dispose = () => {
1014
+ win?.removeEventListener?.("focus", focus);
1015
+ win?.removeEventListener?.("blur", blur);
1016
+ doc.removeEventListener("visibilitychange", visibility);
1017
+ };
1018
+ try {
1019
+ update();
1020
+ } catch (error) {
1021
+ dispose();
1022
+ throw error;
1023
+ }
1024
+ return dispose;
1025
+ }
1026
+ //#endregion
972
1027
  //#region src/scene-bindings.ts
973
1028
  /**
974
1029
  * Apply a scene's `camera` block. `fixed` and `free-fly` pose the perspective camera (free-fly
@@ -1364,6 +1419,84 @@ var MaterialResolver = class {
1364
1419
  }
1365
1420
  };
1366
1421
  //#endregion
1422
+ //#region src/weather/cloud-shadows.ts
1423
+ function createCloudShadowUniforms(map) {
1424
+ return {
1425
+ molenCloudMap: { value: map },
1426
+ molenCloudShadow: { value: new THREE.Vector4(0, 0, 1, 0) },
1427
+ molenCloudField: { value: new THREE.Vector4() },
1428
+ molenCloudMix: { value: new THREE.Vector4() },
1429
+ molenCloudFit: { value: new THREE.Vector4(.15, 0, .35, 0) }
1430
+ };
1431
+ }
1432
+ const GLSL = `
1433
+ uniform sampler2D molenCloudMap;
1434
+ uniform vec4 molenCloudShadow;
1435
+ uniform vec4 molenCloudField;
1436
+ uniform vec4 molenCloudMix;
1437
+ uniform vec4 molenCloudFit;
1438
+ // Sunlight let through the cloud deck to a view-space point, toward a view-space light.
1439
+ float molenCloudShadowAt(vec3 viewPosition, vec3 viewLight) {
1440
+ if (molenCloudShadow.x <= 0.0) return 1.0;
1441
+ vec3 world = cameraPosition + (vec4(viewPosition, 0.0) * viewMatrix).xyz;
1442
+ vec3 light = (vec4(viewLight, 0.0) * viewMatrix).xyz;
1443
+ if (light.y <= 0.0) return 1.0;
1444
+ float base = molenCloudShadow.y;
1445
+ float top = molenCloudShadow.z;
1446
+ float castFrom = mix(base, top, molenCloudFit.z);
1447
+ vec2 xz = world.xz + light.xz * (max(castFrom - world.y, 0.0) / max(light.y, 0.05));
1448
+ vec4 w = textureLod(molenCloudMap, xz * molenCloudField.x + molenCloudField.yz, 0.0);
1449
+ float soft = molenCloudFit.x;
1450
+ float field = dot(w, molenCloudMix);
1451
+ float cover = clamp((field + molenCloudField.w * (1.0 + soft) - 1.0) / soft, 0.0, 1.0);
1452
+ cover *= 1.0 - molenCloudFit.w * (1.0 - field);
1453
+ // Above the layer there is nothing left to cast it.
1454
+ float below = 1.0 - smoothstep(base, top, world.y);
1455
+ return mix(1.0, exp(-cover * molenCloudFit.y), molenCloudShadow.x * below);
1456
+ }
1457
+ `;
1458
+ const TARGET = "getDirectionalLightInfo( directionalLight, directLight );";
1459
+ /** Add cloud shadows to a WebGL shader built from three's lighting chunks; false if none. */
1460
+ function injectCloudShadows(shader, uniforms) {
1461
+ const include = "#include <lights_fragment_begin>";
1462
+ const chunk = THREE.ShaderChunk.lights_fragment_begin;
1463
+ if (!shader.fragmentShader.includes(include) || !chunk.includes(TARGET)) return false;
1464
+ shader.fragmentShader = `${GLSL}\n${shader.fragmentShader.replace(include, chunk.replace(TARGET, `${TARGET}\n\t\tdirectLight.color *= molenCloudShadowAt( geometryPosition, directionalLight.direction );`))}`;
1465
+ Object.assign(shader.uniforms, uniforms);
1466
+ return true;
1467
+ }
1468
+ const registered = /* @__PURE__ */ new WeakMap();
1469
+ let original;
1470
+ /**
1471
+ * Give every lit shader `renderer` builds from now on the cloud shadow. Call before its first
1472
+ * frame. Returns a function that unregisters it.
1473
+ */
1474
+ function installWebGlCloudShadows(renderer, uniforms) {
1475
+ if (original === void 0) {
1476
+ const previous = THREE.Material.prototype.onBeforeCompile;
1477
+ original = previous;
1478
+ const hook = function(shader, target) {
1479
+ previous.call(this, shader, target);
1480
+ const own = registered.get(target);
1481
+ if (own !== void 0) injectCloudShadows(shader, own);
1482
+ };
1483
+ hook.toString = () => previous.toString();
1484
+ THREE.Material.prototype.onBeforeCompile = hook;
1485
+ }
1486
+ registered.set(renderer, uniforms);
1487
+ return () => {
1488
+ registered.delete(renderer);
1489
+ };
1490
+ }
1491
+ /**
1492
+ * Whether a material builds its own shader variations, beyond the renderer-wide cloud-shadow
1493
+ * hook every lit material shares.
1494
+ */
1495
+ function hasShaderHook(material) {
1496
+ const hook = material.onBeforeCompile;
1497
+ return hook !== THREE.Material.prototype.onBeforeCompile && hook !== original;
1498
+ }
1499
+ //#endregion
1367
1500
  //#region src/three/static-batches.ts
1368
1501
  /** Only renderer-owned, opaque, nonanimated meshes are admitted. Originals retain entity identity. */
1369
1502
  var StaticMeshBatches = class {
@@ -1393,7 +1526,7 @@ var StaticMeshBatches = class {
1393
1526
  const mesh = child;
1394
1527
  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;
1395
1528
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
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;
1529
+ if (materials.some((m) => m.transparent || !m.depthWrite || !m.depthTest || m.transmission > 0 || m.isShaderMaterial || m.isNodeMaterial || hasShaderHook(m))) return;
1397
1530
  const matrix = new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld);
1398
1531
  if (matrix.determinant() <= 0) return;
1399
1532
  const e = matrix.elements;
@@ -1579,6 +1712,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1579
1712
  gltf = /* @__PURE__ */ new Map();
1580
1713
  liveries = /* @__PURE__ */ new Map();
1581
1714
  modelSignals = /* @__PURE__ */ new Map();
1715
+ glass = /* @__PURE__ */ new Map();
1582
1716
  identities = /* @__PURE__ */ new Map();
1583
1717
  lights = /* @__PURE__ */ new Map();
1584
1718
  pointLightSlots = [];
@@ -1747,6 +1881,14 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1747
1881
  }
1748
1882
  create(id, renderable) {
1749
1883
  this.identities.set(id, this.identityOf(renderable));
1884
+ if (renderable.kind === "glass") {
1885
+ const group = new THREE.Group();
1886
+ group.name = id;
1887
+ group.visible = renderable.visible !== false;
1888
+ this.scene.add(group);
1889
+ this.objects.set(id, group);
1890
+ return;
1891
+ }
1750
1892
  if (renderable.kind !== "gltf" && renderable.kind !== "primitive") {
1751
1893
  this.createKind(id, renderable);
1752
1894
  return;
@@ -1812,6 +1954,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1812
1954
  this.bindModelSignals(id, instance);
1813
1955
  this.applyAnimation(id, binding, instance);
1814
1956
  this.applyModelSignals(id);
1957
+ this.bindGlass(id);
1815
1958
  this.batchDirty.add(id);
1816
1959
  }).catch((e) => {
1817
1960
  console.warn(`[molen] gltf "${renderable.ref}" failed to load: ${e.message}`);
@@ -1944,7 +2087,42 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1944
2087
  const state = this.modelSignals.get(id);
1945
2088
  state?.visual?.update(state.signals, this.animationTick / this.animationTickRate);
1946
2089
  }
2090
+ setGlass(id, data, state) {
2091
+ const key = data === void 0 ? void 0 : JSON.stringify(data);
2092
+ const previous = this.glass.get(id);
2093
+ if (key === previous?.key) {
2094
+ if (previous) previous.state = state;
2095
+ } else {
2096
+ previous?.visual?.dispose();
2097
+ this.glass.delete(id);
2098
+ this.batches?.remove(id);
2099
+ this.batchDirty.add(id);
2100
+ if (data) {
2101
+ this.glass.set(id, {
2102
+ key,
2103
+ data,
2104
+ state
2105
+ });
2106
+ if (!this.gltf.has(id) || this.objects.get(id)?.children.length) this.bindGlass(id);
2107
+ }
2108
+ }
2109
+ this.applyGlass(id);
2110
+ }
2111
+ bindGlass(id) {
2112
+ const binding = this.glass.get(id), object = this.objects.get(id);
2113
+ if (!binding || !object) return;
2114
+ binding.visual?.dispose();
2115
+ binding.visual = createGlassVisual(object, binding.data);
2116
+ if (binding.visual.missingNodes.length) console.warn(`[molen] entity "${id}": glass missing nodes: ${binding.visual.missingNodes.join(", ")}`);
2117
+ this.applyGlass(id);
2118
+ }
2119
+ applyGlass(id) {
2120
+ const binding = this.glass.get(id);
2121
+ binding?.visual?.update(binding.state, this.animationTick / this.animationTickRate);
2122
+ }
1947
2123
  destroy(id) {
2124
+ this.glass.get(id)?.visual?.dispose();
2125
+ this.glass.delete(id);
1948
2126
  this.liveries.get(id)?.visual?.dispose();
1949
2127
  this.liveries.delete(id);
1950
2128
  this.modelSignals.delete(id);
@@ -1999,6 +2177,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1999
2177
  else obj.scale.set(1, 1, 1);
2000
2178
  if (changed || obj.matrixAutoUpdate) obj.updateMatrix();
2001
2179
  obj.matrixAutoUpdate = this.escaped.has(id);
2180
+ this.applyGlass(id);
2002
2181
  }
2003
2182
  const light = this.lights.get(id);
2004
2183
  if (light !== void 0) {
@@ -2067,6 +2246,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2067
2246
  if (binding) this.poseAnimation(binding);
2068
2247
  }
2069
2248
  for (const id of this.modelSignals.keys()) this.applyModelSignals(id);
2249
+ for (const id of this.glass.keys()) this.applyGlass(id);
2070
2250
  for (const handle of this.handles.values()) handle.setTick?.(tick, tickRate, void 0);
2071
2251
  if (this.pointLightSlots.length > 0 && this.renderer) this.updateLocalLights(this.renderer.camera);
2072
2252
  }
@@ -2075,11 +2255,11 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2075
2255
  for (const id of this.batchDirty) {
2076
2256
  const object = this.objects.get(id);
2077
2257
  if (!object || this.escaped.has(id) || this.handles.has(id)) continue;
2078
- if (!this.animations.has(id) && !this.modelSignals.has(id)) object.traverse((child) => {
2258
+ if (!this.animations.has(id) && !this.modelSignals.has(id) && !this.glass.has(id)) object.traverse((child) => {
2079
2259
  child.updateMatrix();
2080
2260
  child.matrixAutoUpdate = false;
2081
2261
  });
2082
- if (!this.dynamic.has(id) && !this.animations.has(id) && !this.modelSignals.has(id)) this.batches?.add(id, object);
2262
+ if (!this.dynamic.has(id) && !this.animations.has(id) && !this.modelSignals.has(id) && !this.glass.has(id)) this.batches?.add(id, object);
2083
2263
  }
2084
2264
  this.batchDirty.clear();
2085
2265
  this.batches?.flush();
@@ -2118,6 +2298,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2118
2298
  this.lastPoseTick.set(id, tick);
2119
2299
  }
2120
2300
  for (const id of this.modelSignals.keys()) if (!this.animations.has(id)) this.applyModelSignals(id);
2301
+ for (const id of this.glass.keys()) this.applyGlass(id);
2121
2302
  for (const [id, handle] of this.handles) {
2122
2303
  if (handle.setTick === void 0) continue;
2123
2304
  const object = handle.object;
@@ -2264,11 +2445,14 @@ var FrameAdmissionQueue = class {
2264
2445
  queuedBackground = /* @__PURE__ */ new WeakMap();
2265
2446
  scheduled = false;
2266
2447
  disposed = false;
2448
+ paused = false;
2267
2449
  clock;
2268
2450
  schedule;
2269
2451
  maxMs;
2270
2452
  maxBytes;
2271
2453
  maxJobs;
2454
+ urgentStreak = 0;
2455
+ orderedStreak = 0;
2272
2456
  /** Recent work time per label (ms, smoothed): what the next job of that kind will likely take. */
2273
2457
  expected = /* @__PURE__ */ new Map();
2274
2458
  constructor(options = {}) {
@@ -2362,8 +2546,13 @@ var FrameAdmissionQueue = class {
2362
2546
  get pending() {
2363
2547
  return this.jobs.length + this.background.length;
2364
2548
  }
2549
+ /** Hold queued uploads/preparation while the view is inactive; keep resources for resume. */
2550
+ setPaused(paused) {
2551
+ this.paused = paused;
2552
+ if (!paused) this.request();
2553
+ }
2365
2554
  request() {
2366
- if (this.scheduled || this.disposed || this.pending === 0) return;
2555
+ if (this.scheduled || this.disposed || this.paused || this.pending === 0) return;
2367
2556
  this.scheduled = true;
2368
2557
  this.schedule(() => {
2369
2558
  this.scheduled = false;
@@ -2372,23 +2561,37 @@ var FrameAdmissionQueue = class {
2372
2561
  }
2373
2562
  /** One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests. */
2374
2563
  flush() {
2375
- if (this.disposed) return;
2564
+ if (this.disposed || this.paused) return;
2376
2565
  const start = this.clock();
2377
2566
  let bytes = 0, count = 0;
2378
2567
  for (;;) {
2379
2568
  const lane = this.jobs.length > 0 ? this.jobs : this.background;
2380
- const next = lane[0];
2569
+ const waitingNormal = lane === this.jobs && this.urgentStreak >= 2 ? lane.findIndex((job) => job.options.priority !== "urgent") : -1;
2570
+ let index = waitingNormal >= 0 && this.clock() - lane[waitingNormal].queued >= 50 ? waitingNormal : 0;
2571
+ if (lane === this.jobs && lane[index]?.options.priority !== "urgent" && this.orderedStreak < 3) {
2572
+ let best = Number.POSITIVE_INFINITY;
2573
+ for (let i = index; i < lane.length; i++) {
2574
+ const order = lane[i]?.options.order?.() ?? Number.POSITIVE_INFINITY;
2575
+ if (order < best) {
2576
+ best = order;
2577
+ index = i;
2578
+ }
2579
+ }
2580
+ }
2581
+ const next = lane[index];
2381
2582
  if (next === void 0) break;
2382
2583
  const cost = next.options.bytes ?? 0;
2383
2584
  const label = next.options.label ?? "admission";
2384
2585
  if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > this.maxMs || bytes + cost > this.maxBytes)) break;
2385
- lane.shift();
2586
+ lane.splice(index, 1);
2386
2587
  this.forget(next);
2387
2588
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
2388
2589
  if (next.options.signal?.aborted) {
2389
2590
  next.reject(new DOMException("Admission cancelled", "AbortError"));
2390
2591
  continue;
2391
2592
  }
2593
+ this.urgentStreak = next.options.priority === "urgent" ? this.urgentStreak + 1 : 0;
2594
+ if (next.options.priority !== "urgent") this.orderedStreak = next.options.order !== void 0 && this.orderedStreak < 3 ? this.orderedStreak + 1 : 0;
2392
2595
  const began = this.clock();
2393
2596
  try {
2394
2597
  next.resolve(next.run());
@@ -2701,6 +2904,7 @@ var SkyVisual = class {
2701
2904
  drawnDome;
2702
2905
  drawnStars;
2703
2906
  cloudAttenuation = 0;
2907
+ directCloudAttenuation = 0;
2704
2908
  currentFrame;
2705
2909
  currentReflections;
2706
2910
  disposed = false;
@@ -2753,11 +2957,17 @@ var SkyVisual = class {
2753
2957
  get reflectionState() {
2754
2958
  return this.currentReflections;
2755
2959
  }
2756
- /** Diffuse cloud lighting; actual celestial occlusion comes from the cloud layer geometry. */
2757
- setCloudAttenuation(value) {
2960
+ /**
2961
+ * Diffuse cloud lighting; actual celestial occlusion comes from the cloud layer geometry.
2962
+ * `direct` dims the sun and moon (default `value`); with spatial cloud shadows it is 0, since
2963
+ * the shadows themselves take light away where clouds cover the sun.
2964
+ */
2965
+ setCloudAttenuation(value, direct = value) {
2758
2966
  const next = clamp$3(value);
2759
- if (next === this.cloudAttenuation) return;
2967
+ const nextDirect = clamp$3(direct);
2968
+ if (next === this.cloudAttenuation && nextDirect === this.directCloudAttenuation) return;
2760
2969
  this.cloudAttenuation = next;
2970
+ this.directCloudAttenuation = nextDirect;
2761
2971
  this.lastTime = void 0;
2762
2972
  }
2763
2973
  /** Move an Earth observer without rebuilding the dome, bodies or star catalog. */
@@ -2836,8 +3046,8 @@ var SkyVisual = class {
2836
3046
  this.sunLight.intensity *= scale;
2837
3047
  this.ambientLight.intensity *= scale;
2838
3048
  }
2839
- this.sunLight.intensity *= 1 - this.cloudAttenuation * .92;
2840
- this.moonLight.intensity *= 1 - this.cloudAttenuation * .9;
3049
+ this.sunLight.intensity *= 1 - this.directCloudAttenuation * .92;
3050
+ this.moonLight.intensity *= 1 - this.directCloudAttenuation * .9;
2841
3051
  this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
2842
3052
  this.ambientLight.color.lerp(new THREE.Color("#b9c2cb"), this.cloudAttenuation * daylight * .6);
2843
3053
  const radiance = this.ambientLight.intensity / Math.PI;
@@ -3028,32 +3238,36 @@ function hash(x, y, seed) {
3028
3238
  h = Math.imul(h ^ h >>> 13, 1274126177);
3029
3239
  return ((h ^ h >>> 16) >>> 0) / 4294967296;
3030
3240
  }
3031
- function noise(x, y, period, seed) {
3032
- const ix = Math.floor(x), iy = Math.floor(y);
3033
- const fx = smooth$1(0, 1, x - ix), fy = smooth$1(0, 1, y - iy);
3034
- const a = hash(wrap(ix, period), wrap(iy, period), seed);
3035
- const b = hash(wrap(ix + 1, period), wrap(iy, period), seed);
3036
- const c = hash(wrap(ix, period), wrap(iy + 1, period), seed);
3037
- const d = hash(wrap(ix + 1, period), wrap(iy + 1, period), seed);
3038
- return (a + (b - a) * fx) * (1 - fy) + (c + (d - c) * fx) * fy;
3039
- }
3040
- /** Cloud texture texels per side: about 47 m each at the explorer's 24 km cloud scale. */
3041
- const CLOUD_RESOLUTION = 512;
3042
3241
  const PARTICLE_LIMIT = 1400;
3242
+ /** Visibility below which murk veils the sky as well as the ground, meters. */
3243
+ const VEIL_VISIBILITY = 2e4;
3244
+ /** Depth of the hazy air a view looking straight up crosses, meters. */
3245
+ const HAZE_DEPTH = 1500;
3043
3246
  /**
3044
- * Lightweight layered clouds and local precipitation with standard materials on both graphics
3045
- * backends. Patterns are seeded and sampled at absolute simulation time, not integrated frames.
3046
- * Cloud layers use absolute world altitudes; particles are visual and do not accumulate or collide.
3247
+ * Volumetric clouds, a high cirrus layer and local precipitation on both graphics backends.
3248
+ * Patterns are seeded and sampled at absolute simulation time, not integrated frames. Cloud
3249
+ * layers use absolute world altitudes; particles are visual and do not accumulate or collide.
3047
3250
  */
3048
3251
  var WeatherVisual = class {
3049
3252
  object = new THREE.Group();
3050
3253
  fog = new THREE.Fog("#c1c9cd", 0, 5e4);
3051
3254
  state;
3052
- cloudNoise;
3053
- cloudTexture;
3054
- cloudLayers = [];
3055
- cloudKey = "";
3056
- noiseSeed;
3255
+ textures;
3256
+ ownsTextures;
3257
+ createCloudMaterial;
3258
+ noiseBudgetMs;
3259
+ uniforms = new CloudUniforms();
3260
+ quality;
3261
+ cloudMaterial;
3262
+ deck;
3263
+ shells;
3264
+ deckReady = false;
3265
+ cirrus;
3266
+ cirrusCoverage;
3267
+ backend;
3268
+ /** Murk over the sky in poor visibility; see updateVeil. */
3269
+ veil;
3270
+ veilVisibility;
3057
3271
  particles;
3058
3272
  particleTexture;
3059
3273
  cameraPosition = new THREE.Vector3();
@@ -3061,9 +3275,15 @@ var WeatherVisual = class {
3061
3275
  up = new THREE.Vector3();
3062
3276
  color = new THREE.Color();
3063
3277
  disposed = false;
3064
- constructor(data) {
3278
+ constructor(data, options = {}) {
3065
3279
  this.state = resolveWeather$1(weatherSchema.parse(data));
3066
3280
  this.object.name = "molen:weather";
3281
+ this.ownsTextures = options.textures === void 0;
3282
+ this.textures = options.textures ?? new CloudTextures(cloudNoise());
3283
+ this.createCloudMaterial = options.createCloudMaterial;
3284
+ this.quality = options.quality ?? "medium";
3285
+ this.noiseBudgetMs = options.noiseBudgetMs ?? 3;
3286
+ this.backend = options.backend ?? "webgl";
3067
3287
  }
3068
3288
  /** Resolved copy; editing it does not change the visual. */
3069
3289
  get data() {
@@ -3077,9 +3297,32 @@ var WeatherVisual = class {
3077
3297
  get cloudAttenuation() {
3078
3298
  return this.state.clouds.coverage * this.state.clouds.density;
3079
3299
  }
3300
+ /** Per-pixel cloud work. Uniform-driven: changing it rebuilds nothing. */
3301
+ setCloudQuality(quality) {
3302
+ this.quality = quality;
3303
+ }
3304
+ get cloudQuality() {
3305
+ return this.quality;
3306
+ }
3307
+ /**
3308
+ * Whether lit surfaces get spatial cloud shadows this frame: from 'high' quality, once the
3309
+ * clouds have appeared. While they do, direct light needs no uniform cloud dimming.
3310
+ */
3311
+ get shadowsActive() {
3312
+ return cloudQualitySettings(this.quality).shadows && this.deckVisible() && this.deckReady;
3313
+ }
3314
+ /** Write this frame's cloud shadow into a renderer's lit-shader uniforms. */
3315
+ writeShadows(uniforms, active = this.shadowsActive) {
3316
+ const u = this.uniforms;
3317
+ uniforms.molenCloudShadow.value.set(active ? 1 : 0, u.slab.x, u.slab.y, 0);
3318
+ uniforms.molenCloudField.value.copy(u.field);
3319
+ uniforms.molenCloudMix.value.copy(u.mix);
3320
+ uniforms.molenCloudFit.value.set(u.erode.z, u.shadowDepth, .35, u.relief.x);
3321
+ }
3322
+ /** Cloud layers drawn (the volumetric layer and cirrus) and precipitation particles. */
3080
3323
  get stats() {
3081
3324
  return {
3082
- cloudLayers: this.cloudLayers.filter((layer) => layer.visible).length,
3325
+ cloudLayers: Number(this.deck?.visible === true || this.shells?.visible === true) + Number(this.cirrus?.visible === true),
3083
3326
  particles: this.particles?.visible ? this.particles.geometry.drawRange.count / 6 : 0
3084
3327
  };
3085
3328
  }
@@ -3092,16 +3335,21 @@ var WeatherVisual = class {
3092
3335
  this.right.setFromMatrixColumn(camera.matrixWorld, 0).normalize();
3093
3336
  this.up.setFromMatrixColumn(camera.matrixWorld, 1).normalize();
3094
3337
  const daylight = sky?.daylight ?? 1;
3095
- this.updateClouds(seconds, camera, origin, daylight, sky?.sunDirection ?? [
3096
- .3,
3097
- .8,
3098
- .2
3099
- ]);
3338
+ this.updateClouds(seconds, camera, origin, daylight, sky);
3100
3339
  this.updateParticles(seconds, origin, daylight);
3101
3340
  this.object.updateMatrixWorld(true);
3102
3341
  }
3103
- /** Combine weather visibility with an authored/streaming fog limit without mutating it. */
3342
+ /**
3343
+ * Combine weather visibility with an authored/streaming fog limit without mutating it. The
3344
+ * clouds are fogged with the result (see CloudUniforms.setFog).
3345
+ */
3104
3346
  fogFor(base, sky) {
3347
+ const fog = this.limitFog(base, sky);
3348
+ this.veil?.material.color.copy(fog.color);
3349
+ this.uniforms.setFog(fog, 1 - smooth$1(.5, .9, this.cloudAttenuation));
3350
+ return fog;
3351
+ }
3352
+ limitFog(base, sky) {
3105
3353
  const visibility = this.state.visibility;
3106
3354
  if (base instanceof THREE.Fog && base.far <= visibility) return base;
3107
3355
  if (base instanceof THREE.FogExp2 && base.density >= 2 / visibility) return base;
@@ -3110,19 +3358,115 @@ var WeatherVisual = class {
3110
3358
  this.fog.near = Math.min(this.fog.near, this.fog.far * .1);
3111
3359
  if (base) this.fog.color.copy(base.color);
3112
3360
  else this.fog.color.set("#0b1220").lerp(this.color.set("#c1c9cd"), sky?.daylight ?? 1);
3361
+ const overcast = smooth$1(.5, .9, this.cloudAttenuation);
3362
+ if (overcast > 0) {
3363
+ const { r, g, b } = this.fog.color;
3364
+ const grey = (r * .2126 + g * .7152 + b * .0722) * .85;
3365
+ this.fog.color.lerp(this.color.setRGB(grey, grey, grey), overcast * .8);
3366
+ }
3113
3367
  return this.fog;
3114
3368
  }
3115
- buildClouds() {
3116
- const texture = new THREE.DataTexture(new Uint8Array(CLOUD_RESOLUTION ** 2 * 4), CLOUD_RESOLUTION, CLOUD_RESOLUTION);
3117
- texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
3118
- texture.magFilter = THREE.LinearFilter;
3119
- texture.minFilter = THREE.LinearMipmapLinearFilter;
3120
- texture.anisotropy = 16;
3121
- texture.generateMipmaps = true;
3122
- texture.colorSpace = THREE.LinearSRGBColorSpace;
3123
- this.cloudTexture = texture;
3124
- for (let i = 0; i < 2; i++) {
3125
- const geometry = new THREE.PlaneGeometry(1, 1, 24, 24);
3369
+ deckVisible() {
3370
+ const { coverage, density } = this.state.clouds;
3371
+ return coverage > 0 && density > 0;
3372
+ }
3373
+ buildDeck() {
3374
+ const material = this.createCloudMaterial?.(this.uniforms, this.textures) ?? createWebGlCloudMaterial(this.uniforms, this.textures);
3375
+ this.cloudMaterial = material;
3376
+ this.deck = new THREE.Mesh(cloudDeckGeometry(), material);
3377
+ this.deck.name = "molen:cloud-deck";
3378
+ this.shells = new THREE.Mesh(cloudShellGeometry(), material);
3379
+ this.shells.name = "molen:cloud-shells";
3380
+ for (const mesh of [this.deck, this.shells]) {
3381
+ mesh.frustumCulled = false;
3382
+ mesh.visible = false;
3383
+ this.object.add(mesh);
3384
+ }
3385
+ }
3386
+ updateClouds(seconds, camera, origin, daylight, sky) {
3387
+ const { clouds } = this.state;
3388
+ const deck = this.deckVisible();
3389
+ const wanted = [...deck ? [
3390
+ "weather",
3391
+ "shape",
3392
+ "detail"
3393
+ ] : [], ...clouds.cirrus > 0 ? ["cirrus"] : []];
3394
+ if (wanted.length > 0) this.textures.noise.build(wanted, this.noiseBudgetMs);
3395
+ this.deckReady = this.textures.sync();
3396
+ const far = camera instanceof THREE.PerspectiveCamera || camera instanceof THREE.OrthographicCamera ? camera.far : 5e4;
3397
+ this.uniforms.update(this.state, seconds, origin, far, this.quality, sky);
3398
+ if (deck && this.deckReady && !this.deck) this.buildDeck();
3399
+ if (this.deck && this.shells) {
3400
+ const shown = deck && this.deckReady;
3401
+ const altitude = this.cameraPosition.y + origin[1];
3402
+ const top = clouds.baseAltitude + clouds.thickness;
3403
+ const inside = altitude > clouds.baseAltitude && altitude < top;
3404
+ this.deck.visible = shown && !inside;
3405
+ this.shells.visible = shown && inside;
3406
+ const slab = this.uniforms.slab;
3407
+ this.deck.position.set(this.cameraPosition.x, altitude <= clouds.baseAltitude ? slab.x : slab.y, this.cameraPosition.z);
3408
+ this.deck.scale.set(2 * slab.w, 1, 2 * slab.w);
3409
+ this.shells.position.copy(this.cameraPosition);
3410
+ }
3411
+ this.updateCirrus(seconds, origin, far, daylight, sky?.sunDirection ?? [
3412
+ .3,
3413
+ .8,
3414
+ .2
3415
+ ]);
3416
+ this.updateVeil(far);
3417
+ }
3418
+ /**
3419
+ * In fog, rain or snow the murk hides the sky too, not only the ground: a camera-centred
3420
+ * dome in the fog color, behind everything nearer, opaque toward the horizon and thinner
3421
+ * overhead, where a view crosses less hazy air. Clouds draw over it, and a fully hazed cloud
3422
+ * shows it. Absent in clear air (visibility from 20 km).
3423
+ */
3424
+ updateVeil(far) {
3425
+ const visibility = this.state.visibility;
3426
+ const shown = visibility < VEIL_VISIBILITY;
3427
+ if (this.veil) this.veil.visible = shown;
3428
+ if (!shown) return;
3429
+ if (!this.veil) {
3430
+ const geometry = new THREE.SphereGeometry(1, 32, 16);
3431
+ geometry.setAttribute("color", new THREE.BufferAttribute(new Float32Array(geometry.getAttribute("position").count * 4), 4));
3432
+ this.veil = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
3433
+ vertexColors: true,
3434
+ transparent: true,
3435
+ depthWrite: false,
3436
+ side: THREE.BackSide,
3437
+ fog: false,
3438
+ toneMapped: this.backend === "webgpu"
3439
+ }));
3440
+ this.veil.name = "molen:visibility-veil";
3441
+ this.veil.renderOrder = -1;
3442
+ this.veil.frustumCulled = false;
3443
+ this.object.add(this.veil);
3444
+ }
3445
+ if (visibility !== this.veilVisibility) {
3446
+ this.veilVisibility = visibility;
3447
+ const positions = this.veil.geometry.getAttribute("position");
3448
+ const colors = this.veil.geometry.getAttribute("color");
3449
+ const strength = smooth$1(VEIL_VISIBILITY, VEIL_VISIBILITY * .4, visibility);
3450
+ for (let i = 0; i < positions.count; i++) {
3451
+ const path = HAZE_DEPTH / Math.max(Math.abs(positions.getY(i)), .03);
3452
+ colors.setXYZW(i, 1, 1, 1, (1 - Math.exp(-3 * path / visibility)) * strength);
3453
+ }
3454
+ colors.needsUpdate = true;
3455
+ }
3456
+ this.veil.scale.setScalar(Math.min(far * .9, Math.max(1500, visibility * 2)));
3457
+ this.veil.position.copy(this.cameraPosition);
3458
+ }
3459
+ /**
3460
+ * Cirrus are thin ice streaks combed out by the jet stream, so this layer is a flat sheet: a
3461
+ * stretched texture turned to lie along the wind, at the cirrus altitude.
3462
+ */
3463
+ updateCirrus(seconds, origin, far, daylight, sun) {
3464
+ const { clouds, atmosphere } = this.state;
3465
+ const ready = clouds.cirrus > 0 && this.textures.noise.has("cirrus");
3466
+ if (this.cirrus) this.cirrus.visible = ready;
3467
+ if (!ready) return;
3468
+ if (!this.cirrus) {
3469
+ const geometry = new THREE.PlaneGeometry(1, 1, 16, 16);
3126
3470
  geometry.rotateX(-Math.PI / 2);
3127
3471
  const positions = geometry.getAttribute("position");
3128
3472
  const colors = new Float32Array(positions.count * 4);
@@ -3132,83 +3476,52 @@ var WeatherVisual = class {
3132
3476
  1,
3133
3477
  1,
3134
3478
  1,
3135
- 1 - smooth$1(.6, 1, r)
3479
+ 1 - smooth$1(.55, 1, r)
3136
3480
  ], j * 4);
3137
3481
  }
3138
3482
  geometry.setAttribute("color", new THREE.BufferAttribute(colors, 4));
3139
- const map = i === 0 ? texture : texture.clone();
3140
- const material = new THREE.MeshBasicMaterial({
3141
- map,
3483
+ this.cirrus = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
3484
+ map: this.textures.cirrus,
3142
3485
  vertexColors: true,
3143
3486
  transparent: true,
3144
3487
  side: THREE.DoubleSide,
3145
- depthWrite: false,
3146
- fog: false
3147
- });
3148
- const layer = new THREE.Mesh(geometry, material);
3149
- layer.name = `molen:cloud-layer-${i}`;
3150
- layer.frustumCulled = false;
3151
- this.cloudLayers.push(layer);
3152
- this.object.add(layer);
3153
- }
3154
- }
3155
- updateClouds(seconds, camera, origin, daylight, sun) {
3156
- const { clouds, seed, atmosphere } = this.state;
3157
- const visible = clouds.coverage > 0 && clouds.density > 0;
3158
- if (visible && !this.cloudTexture) this.buildClouds();
3159
- for (const layer of this.cloudLayers) layer.visible = visible;
3160
- if (!visible) return;
3161
- if (seed !== this.noiseSeed) {
3162
- this.noiseSeed = seed;
3163
- this.cloudKey = "";
3164
- this.cloudNoise = new Float32Array(CLOUD_RESOLUTION ** 2);
3165
- for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
3166
- let value = 0, weight = 0;
3167
- for (let octave = 0; octave < 5; octave++) {
3168
- const frequency = 8 * 2 ** octave, amplitude = .52 ** octave;
3169
- value += noise(x / CLOUD_RESOLUTION * frequency, y / CLOUD_RESOLUTION * frequency, frequency, seed + octave) * amplitude;
3170
- weight += amplitude;
3171
- }
3172
- this.cloudNoise[y * CLOUD_RESOLUTION + x] = value / weight;
3173
- }
3174
- }
3175
- const key = `${clouds.coverage},${clouds.density},${sun.map((v) => Math.round(v * 20)).join(",")}`;
3176
- if (key !== this.cloudKey && this.cloudTexture && this.cloudNoise) {
3177
- this.cloudKey = key;
3178
- const pixels = this.cloudTexture.image.data;
3179
- const field = this.cloudNoise;
3180
- const threshold = .78 - clouds.coverage * .62;
3181
- for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
3182
- const i = y * CLOUD_RESOLUTION + x, n = field[i] ?? 0;
3183
- const dx = (field[y * CLOUD_RESOLUTION + (x + 1) % CLOUD_RESOLUTION] ?? n) - n;
3184
- const dz = (field[(y + 1) % CLOUD_RESOLUTION * CLOUD_RESOLUTION + x] ?? n) - n;
3185
- const shade = clamp$2(.56 + (1 - smooth$1(threshold, threshold + .25, n)) * .3 + (dx * sun[0] + dz * sun[2]) * 4 - clouds.density * .15);
3186
- const alpha = smooth$1(threshold - .075, threshold + .075, n) * (1 - Math.exp(-clouds.density * 6));
3187
- pixels.set([
3188
- shade * 255,
3189
- shade * 255,
3190
- shade * 255,
3191
- alpha * 255
3192
- ], i * 4);
3488
+ depthWrite: false
3489
+ }));
3490
+ this.cirrus.name = "molen:cirrus";
3491
+ this.cirrus.frustumCulled = false;
3492
+ this.object.add(this.cirrus);
3493
+ }
3494
+ if (clouds.cirrus !== this.cirrusCoverage) {
3495
+ this.cirrusCoverage = clouds.cirrus;
3496
+ const noise = this.textures.noise.cirrus;
3497
+ const pixels = this.textures.cirrus.image.data;
3498
+ const threshold = 1 - clouds.cirrus;
3499
+ for (let i = 0; i < 256 ** 2; i++) {
3500
+ const alpha = smooth$1(threshold - .1, threshold + .35, (noise[i] ?? 0) / 255);
3501
+ pixels[i * 4] = pixels[i * 4 + 1] = pixels[i * 4 + 2] = 255;
3502
+ pixels[i * 4 + 3] = Math.round(alpha * 200);
3193
3503
  }
3194
- for (const layer of this.cloudLayers) if (layer.material.map) layer.material.map.needsUpdate = true;
3504
+ this.textures.cirrus.needsUpdate = true;
3195
3505
  }
3196
- const far = camera instanceof THREE.PerspectiveCamera || camera instanceof THREE.OrthographicCamera ? camera.far : 5e4;
3506
+ const layer = this.cirrus;
3197
3507
  const size = Math.max(2e3, Math.min(16e4, far * 1.4));
3198
- const absoluteX = this.cameraPosition.x + origin[0], absoluteZ = this.cameraPosition.z + origin[2];
3199
- this.color.set("#101829").lerp(new THREE.Color("#e4e9ee"), daylight);
3200
- const sunset = (1 - smooth$1(0, .3, Math.abs(sun[1]))) * smooth$1(-.15, .05, sun[1]);
3201
- this.color.lerp(new THREE.Color("#f6b88d"), sunset * .55);
3202
- this.color.multiplyScalar(1 + daylight * 1.8);
3203
- for (const [i, layer] of this.cloudLayers.entries()) {
3204
- layer.position.set(this.cameraPosition.x, clouds.baseAltitude + i * clouds.thickness - origin[1], this.cameraPosition.z);
3205
- layer.scale.set(size, 1, size);
3206
- layer.material.color.copy(this.color);
3207
- const map = layer.material.map;
3208
- const scale = clouds.scale * (1 + i * .35);
3209
- map.repeat.set(size / scale, size / scale);
3210
- map.offset.set(wrap((absoluteX - atmosphere.windVelocity[0] * seconds) / scale - size / scale / 2 + i * .31, 1), wrap(-(absoluteZ - atmosphere.windVelocity[2] * seconds) / scale - size / scale / 2 + i * .47, 1));
3211
- }
3508
+ const wind = atmosphere.windVelocity;
3509
+ const angle = Math.hypot(wind[0], wind[2]) > .01 ? Math.atan2(-wind[2], wind[0]) : 0;
3510
+ layer.rotation.y = angle;
3511
+ layer.position.set(this.cameraPosition.x, clouds.cirrusAltitude - origin[1], this.cameraPosition.z);
3512
+ layer.scale.set(size, 1, size);
3513
+ const cos = Math.cos(angle), sin = Math.sin(angle);
3514
+ const ax = this.cameraPosition.x + origin[0] - wind[0] * 2.5 * seconds;
3515
+ const az = this.cameraPosition.z + origin[2] - wind[2] * 2.5 * seconds;
3516
+ const scale = clouds.scale * 1.6;
3517
+ const map = layer.material.map;
3518
+ map.repeat.set(size / scale, size / scale);
3519
+ map.offset.set(wrap((ax * cos - az * sin) / scale - size / scale / 2, 1), wrap((-ax * sin - az * cos) / scale - size / scale / 2, 1));
3520
+ this.color.set("#101829").lerp(new THREE.Color("#eef2f6"), daylight);
3521
+ const sunset = (1 - smooth$1(0, .3, Math.abs(sun[1]))) * smooth$1(-.2, .05, sun[1]);
3522
+ this.color.lerp(new THREE.Color("#ffb48f"), sunset * .7);
3523
+ this.color.multiplyScalar(1 + daylight * 1.6);
3524
+ layer.material.color.copy(this.color);
3212
3525
  }
3213
3526
  buildParticles() {
3214
3527
  const geometry = new THREE.BufferGeometry();
@@ -3298,11 +3611,14 @@ var WeatherVisual = class {
3298
3611
  dispose() {
3299
3612
  if (this.disposed) return;
3300
3613
  this.disposed = true;
3301
- for (const layer of this.cloudLayers) {
3302
- layer.geometry.dispose();
3303
- layer.material.map?.dispose();
3304
- layer.material.dispose();
3305
- }
3614
+ this.deck?.geometry.dispose();
3615
+ this.shells?.geometry.dispose();
3616
+ this.cloudMaterial?.dispose();
3617
+ this.cirrus?.geometry.dispose();
3618
+ this.cirrus?.material.dispose();
3619
+ this.veil?.geometry.dispose();
3620
+ this.veil?.material.dispose();
3621
+ if (this.ownsTextures) this.textures.dispose();
3306
3622
  this.particles?.geometry.dispose();
3307
3623
  this.particles?.material.dispose();
3308
3624
  this.particleTexture?.dispose();
@@ -3434,33 +3750,56 @@ const SHADOW_MAP_SIZE = {
3434
3750
  high: 4096
3435
3751
  };
3436
3752
  const UP = new THREE.Vector3(0, 1, 0);
3753
+ const VERTICAL_UP = new THREE.Vector3(1, 0, 0);
3754
+ const shadowRadii = /* @__PURE__ */ new WeakMap();
3437
3755
  const scratchCenter = new THREE.Vector3();
3438
3756
  const scratchRight = new THREE.Vector3();
3439
3757
  const scratchUp = new THREE.Vector3();
3440
3758
  const scratchForward = new THREE.Vector3();
3759
+ /** Keep the projection fixed through small altitude/zoom changes, including at a bucket edge. */
3760
+ function stableRadius(light, requested) {
3761
+ const previous = shadowRadii.get(light);
3762
+ if (previous !== void 0 && requested <= previous && requested >= previous * .8) return previous;
3763
+ const step = 2 ** Math.floor(Math.log2(requested)) / 8;
3764
+ const radius = Math.ceil(requested / step) * step;
3765
+ shadowRadii.set(light, radius);
3766
+ return radius;
3767
+ }
3441
3768
  /**
3442
3769
  * Aim `light`'s shadow at `center` (scene coordinates, after rebasing) from `direction` (a unit
3443
- * vector toward the sun), covering ±`radius`. The light and its target move; the direction of
3770
+ * vector toward the sun), covering at least ±`radius`. The light and its target move; the direction of
3444
3771
  * the light is unchanged.
3445
3772
  */
3446
- function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false) {
3773
+ function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false, worldOrigin = [
3774
+ 0,
3775
+ 0,
3776
+ 0
3777
+ ]) {
3778
+ radius = stableRadius(light, radius);
3447
3779
  const toSun = scratchForward.copy(direction).normalize();
3448
3780
  const size = light.shadow.mapSize.x || 2048;
3449
3781
  const texel = 2 * radius / size;
3450
- const right = scratchRight.crossVectors(Math.abs(toSun.y) > .999 ? new THREE.Vector3(1, 0, 0) : UP, toSun);
3782
+ const camera = light.shadow.camera;
3783
+ camera.up.copy(Math.abs(toSun.y) > .999 ? VERTICAL_UP : UP);
3784
+ const right = scratchRight.crossVectors(camera.up, toSun);
3451
3785
  right.normalize();
3452
3786
  const up = scratchUp.crossVectors(toSun, right).normalize();
3453
3787
  const snapped = scratchCenter.copy(center);
3788
+ snapped.x += worldOrigin[0];
3789
+ snapped.y += worldOrigin[1];
3790
+ snapped.z += worldOrigin[2];
3454
3791
  const along = snapped.dot(toSun);
3455
3792
  const x = Math.round(snapped.dot(right) / texel) * texel;
3456
3793
  const y = Math.round(snapped.dot(up) / texel) * texel;
3457
3794
  snapped.copy(right).multiplyScalar(x).addScaledVector(up, y).addScaledVector(toSun, along);
3795
+ snapped.x -= worldOrigin[0];
3796
+ snapped.y -= worldOrigin[1];
3797
+ snapped.z -= worldOrigin[2];
3458
3798
  const distance = radius * 2 + 1e3;
3459
3799
  light.target.position.copy(snapped);
3460
3800
  light.position.copy(snapped).addScaledVector(toSun, distance);
3461
3801
  light.target.updateMatrixWorld();
3462
3802
  light.updateMatrixWorld();
3463
- const camera = light.shadow.camera;
3464
3803
  if (camera.left !== -radius || camera.top !== radius || camera.far !== distance + radius * 2 + 1e3) {
3465
3804
  camera.left = -radius;
3466
3805
  camera.right = radius;
@@ -3470,8 +3809,10 @@ function focusDirectionalShadow(light, direction, center, radius, biasAddsToward
3470
3809
  camera.far = distance + radius * 2 + 1e3;
3471
3810
  camera.updateProjectionMatrix();
3472
3811
  }
3473
- light.shadow.bias = biasAddsTowardLight ? 4e-4 : -4e-4;
3812
+ const bias = texel * .25 / (camera.far - camera.near);
3813
+ light.shadow.bias = biasAddsTowardLight ? bias : -bias;
3474
3814
  light.shadow.normalBias = texel * 1.2;
3815
+ light.shadow.radius = .5;
3475
3816
  }
3476
3817
  //#endregion
3477
3818
  //#region src/three/sky-reflections.ts
@@ -3747,6 +4088,13 @@ var Renderer = class Renderer {
3747
4088
  starCatalog;
3748
4089
  activeWeather;
3749
4090
  weatherTimeOverride;
4091
+ /** Cloud textures and the cloud-shadow uniforms every lit shader reads, for the renderer's life. */
4092
+ cloudTextures = new CloudTextures(cloudNoise());
4093
+ cloudShadows = createCloudShadowUniforms(this.cloudTextures.shadow);
4094
+ cloudBackend;
4095
+ releaseCloudShadows;
4096
+ cloudQualityLevel = "medium";
4097
+ cloudShadowMapVersion = -1;
3750
4098
  weatherLightIntensities = /* @__PURE__ */ new WeakMap();
3751
4099
  /** The hemisphere the sky reflection map stands in for, and its authored visibility. */
3752
4100
  hiddenAmbient;
@@ -3764,7 +4112,7 @@ var Renderer = class Renderer {
3764
4112
  return this.activeSky;
3765
4113
  }
3766
4114
  /**
3767
- * Aim the sun's shadow at a focus (absolute world coordinates) covering ±`radius` meters, or
4115
+ * Aim the sun's shadow at a focus (absolute world coordinates) covering at least ±`radius` meters, or
3768
4116
  * `undefined` for the environment's own fixed box. Call whenever what the camera frames
3769
4117
  * moves: an orbit target, a walker, a car. Shadows must be on (`setShadowQuality`).
3770
4118
  */
@@ -3785,7 +4133,7 @@ var Renderer = class Renderer {
3785
4133
  const enabled = quality !== "off";
3786
4134
  let parked = false;
3787
4135
  for (const light of this.sunLights()) {
3788
- if (this.backend === "webgpu" && this.shadowLights.has(light)) {
4136
+ if (this.backend === "webgpu" && this.shadowLights.has(light) && light.shadow.map !== null) {
3789
4137
  light.shadow.autoUpdate = enabled;
3790
4138
  light.shadow.intensity = enabled ? 1 : 0;
3791
4139
  continue;
@@ -3802,6 +4150,7 @@ var Renderer = class Renderer {
3802
4150
  light.castShadow = true;
3803
4151
  light.shadow.autoUpdate = true;
3804
4152
  light.shadow.intensity = 1;
4153
+ if (light.shadow.map === null) light.shadow.needsUpdate = true;
3805
4154
  const size = SHADOW_MAP_SIZE[quality];
3806
4155
  if (light.shadow.mapSize.x !== size) {
3807
4156
  light.shadow.mapSize.set(size, size);
@@ -3837,18 +4186,35 @@ var Renderer = class Renderer {
3837
4186
  const center = this.shadowCenter.set(focus.center[0] - this.worldOrigin[0], focus.center[1] - this.worldOrigin[1], focus.center[2] - this.worldOrigin[2]);
3838
4187
  for (const light of this.sunLights()) {
3839
4188
  if (!light.castShadow) continue;
3840
- focusDirectionalShadow(light, light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection), center, focus.radius, this.backend === "webgl" && this.webglReversedPcfShadows());
4189
+ focusDirectionalShadow(light, light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection), center, focus.radius, this.backend === "webgl" && this.webglReversedPcfShadows(), this.worldOrigin);
3841
4190
  }
3842
4191
  }
3843
4192
  /** Active weather effects; physical weather data is also available in the simulation component. */
3844
4193
  get weather() {
3845
4194
  return this.activeWeather;
3846
4195
  }
4196
+ /**
4197
+ * Per-pixel cloud work, default 'medium': ray-march steps and light samples, erosion detail
4198
+ * from 'high', and from 'high' also cloud shadows on every lit surface. Takes effect on the
4199
+ * next frame without rebuilding any shader, so adaptive quality tiers may change it freely.
4200
+ */
4201
+ setCloudQuality(quality) {
4202
+ this.cloudQualityLevel = quality;
4203
+ this.activeWeather?.setCloudQuality(quality);
4204
+ }
4205
+ get cloudQuality() {
4206
+ return this.cloudQualityLevel;
4207
+ }
3847
4208
  /** Apply the singleton weather component without rebuilding the sky or moving the camera. */
3848
4209
  setWeather(data) {
3849
4210
  if (data && this.activeWeather) this.activeWeather.setData(data);
3850
4211
  else {
3851
- const next = data ? new WeatherVisual(data) : void 0;
4212
+ const next = data ? new WeatherVisual(data, {
4213
+ textures: this.cloudTextures,
4214
+ quality: this.cloudQualityLevel,
4215
+ backend: this.backend,
4216
+ ...this.cloudBackend ? { createCloudMaterial: this.cloudBackend.material } : {}
4217
+ }) : void 0;
3852
4218
  this.activeWeather?.dispose();
3853
4219
  this.activeWeather = next;
3854
4220
  if (next) this.scene.add(next.object);
@@ -3909,9 +4275,14 @@ var Renderer = class Renderer {
3909
4275
  });
3910
4276
  try {
3911
4277
  const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-Cup4Yvzs.mjs"))).WebGpuSceneOptimizer(three);
4278
+ const clouds = await import("./webgpu-clouds-H03g7ID1.mjs");
3912
4279
  return new Renderer(opts, {
3913
4280
  three,
3914
4281
  backend: "webgpu",
4282
+ clouds: {
4283
+ material: clouds.createWebGpuCloudMaterial,
4284
+ installShadows: (uniforms) => clouds.installWebGpuCloudShadows(three, uniforms)
4285
+ },
3915
4286
  ...optimizer ? { optimizer } : {},
3916
4287
  ...opts.reflections === true ? { reflectionFilter: (await import("./webgpu-sky-reflections-CymGEes-.mjs")).createWebGpuSkyReflectionFilter(three) } : {}
3917
4288
  });
@@ -3953,6 +4324,7 @@ var Renderer = class Renderer {
3953
4324
  this.pixelRatio = pixelRatio;
3954
4325
  this.backend = initialized?.backend ?? "webgl";
3955
4326
  this.optimizer = initialized?.optimizer;
4327
+ this.cloudBackend = initialized?.clouds;
3956
4328
  this.three = initialized?.three ?? createWebGlRenderer({
3957
4329
  canvas: opts.canvas,
3958
4330
  antialias: opts.antialias ?? false,
@@ -3962,6 +4334,8 @@ var Renderer = class Renderer {
3962
4334
  logarithmicDepthBuffer: opts.logarithmicDepthBuffer ?? false
3963
4335
  });
3964
4336
  this.three.setPixelRatio(pixelRatio);
4337
+ if (this.cloudBackend) this.cloudBackend.installShadows(this.cloudShadows);
4338
+ else this.releaseCloudShadows = installWebGlCloudShadows(this.three, this.cloudShadows);
3965
4339
  if (this.backend === "webgpu") this.three.onDeviceLost = (info) => {
3966
4340
  if (this.disposed) return;
3967
4341
  this.deviceLossReason = info.message;
@@ -4121,6 +4495,7 @@ var Renderer = class Renderer {
4121
4495
  *
4122
4496
  * `root.userData.admissionPriority` admits the root's own work as `'urgent'` (ahead of normal
4123
4497
  * work) or `'background'` (only in budget normal work leaves: content nobody waits on yet).
4498
+ * `root.userData.admissionOrder` supplies live normal-lane order (lower first).
4124
4499
  */
4125
4500
  async prepareObject(root, signal, parent) {
4126
4501
  if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
@@ -4129,6 +4504,7 @@ var Renderer = class Renderer {
4129
4504
  const deferredLevels = lods === void 0 ? void 0 : new Set([...lods.values()].flat());
4130
4505
  const priority = root.userData.admissionPriority;
4131
4506
  const foreground = createLane(priority === "background", priority === "urgent");
4507
+ if (typeof root.userData.admissionOrder === "function") foreground.order = root.userData.admissionOrder;
4132
4508
  const background = createLane(true);
4133
4509
  const state = this.programState();
4134
4510
  const interest = signal === void 0 ? "pinned" : new WarmupInterest(this.cancel);
@@ -4374,7 +4750,8 @@ var Renderer = class Renderer {
4374
4750
  const promise = this.admission.run(task, {
4375
4751
  ...options,
4376
4752
  signal: controller.signal,
4377
- priority: lane.background ? "background" : lane.urgent ? "urgent" : "normal"
4753
+ priority: lane.background ? "background" : lane.urgent ? "urgent" : "normal",
4754
+ ...lane.order ? { order: lane.order } : {}
4378
4755
  });
4379
4756
  const warmup = {
4380
4757
  promise,
@@ -4624,7 +5001,10 @@ var Renderer = class Renderer {
4624
5001
  if (this.backend === "webgpu") this.three.info.reset();
4625
5002
  const sky = this.activeSky;
4626
5003
  const weather = this.activeWeather;
4627
- sky?.setCloudAttenuation(weather?.cloudAttenuation ?? 0);
5004
+ const cloudAttenuation = weather?.cloudAttenuation ?? 0;
5005
+ const cloudShadowed = weather?.shadowsActive ?? false;
5006
+ const directAttenuation = cloudShadowed ? 0 : cloudAttenuation;
5007
+ sky?.setCloudAttenuation(cloudAttenuation, directAttenuation);
4628
5008
  sky?.update(this.environmentTimeOverride ?? this.environmentSeconds);
4629
5009
  findEnvironmentRig(this.scene)?.traverse((object) => {
4630
5010
  if (!(object instanceof THREE.Light)) return;
@@ -4640,9 +5020,16 @@ var Renderer = class Renderer {
4640
5020
  base = object.intensity;
4641
5021
  this.weatherLightIntensities.set(object, base);
4642
5022
  }
4643
- object.intensity = base * (1 - (weather?.cloudAttenuation ?? 0) * (object instanceof THREE.DirectionalLight ? .92 : .2));
5023
+ object.intensity = base * (object instanceof THREE.DirectionalLight ? 1 - directAttenuation * .92 : 1 - cloudAttenuation * .2);
4644
5024
  });
4645
5025
  weather?.update(this.weatherTimeOverride ?? this.environmentSeconds, this.camera, this.worldOrigin, sky?.frame);
5026
+ if (weather) weather.writeShadows(this.cloudShadows, cloudShadowed);
5027
+ else this.cloudShadows.molenCloudShadow.value.x = 0;
5028
+ const shadowMap = this.cloudShadows.molenCloudMap.value;
5029
+ if (weather && shadowMap.version !== this.cloudShadowMapVersion) {
5030
+ this.cloudShadowMapVersion = shadowMap.version;
5031
+ this.three.initTexture(shadowMap);
5032
+ }
4646
5033
  let reflectedAmbient;
4647
5034
  if (this.reflections) {
4648
5035
  const rig = findEnvironmentRig(this.scene);
@@ -4690,6 +5077,7 @@ var Renderer = class Renderer {
4690
5077
  this.applyShadowFocus();
4691
5078
  this.renderScene();
4692
5079
  }
5080
+ if (this.backend === "webgl") opaqueDrawingBuffer(this.three);
4693
5081
  const info = this.three.info.render;
4694
5082
  this.lastRenderStats.drawCalls = "drawCalls" in info ? info.drawCalls : info.calls;
4695
5083
  this.lastRenderStats.triangles = info.triangles;
@@ -4875,6 +5263,8 @@ var Renderer = class Renderer {
4875
5263
  this.activeSky = void 0;
4876
5264
  this.activeWeather?.dispose();
4877
5265
  this.activeWeather = void 0;
5266
+ this.releaseCloudShadows?.();
5267
+ this.cloudTextures.dispose();
4878
5268
  this.reflections?.dispose();
4879
5269
  this.hideReflectedAmbient(void 0);
4880
5270
  findEnvironmentRig(this.scene)?.traverse((object) => {
@@ -4996,6 +5386,23 @@ function createWebGlRenderer(options) {
4996
5386
  }
4997
5387
  return renderer;
4998
5388
  }
5389
+ /**
5390
+ * Three r184 always asks for an alpha drawing buffer and keeps the canvas opaque by having opaque
5391
+ * materials write alpha 1. Alpha-to-coverage materials (frayed pavement edges, leaf cards) write
5392
+ * their coverage as alpha instead, so pixels they only partly covered left the canvas translucent
5393
+ * and the page behind it showed through: pale speckle along curbs and in canopies, plainest at
5394
+ * night. A clear of the alpha channel alone makes the finished frame opaque again.
5395
+ */
5396
+ function opaqueDrawingBuffer(renderer) {
5397
+ if (renderer.getRenderTarget() !== null) return;
5398
+ const gl = renderer.getContext();
5399
+ const color = renderer.state.buffers.color;
5400
+ color.setMask(true);
5401
+ color.setClear(0, 0, 0, 1, false);
5402
+ gl.colorMask(false, false, false, true);
5403
+ gl.clear(gl.COLOR_BUFFER_BIT);
5404
+ gl.colorMask(true, true, true, true);
5405
+ }
4999
5406
  function textureBytes(texture) {
5000
5407
  const image = texture.image;
5001
5408
  return image?.data?.byteLength ?? Math.ceil((image?.width ?? 1) * (image?.height ?? 1) * 4 * 4 / 3);
@@ -5076,6 +5483,7 @@ function createClientWithRenderer(link, opts, renderer) {
5076
5483
  const backend = new ThreeSceneBackend(renderer.worldRoot, assets, renderer, materials, opts.sceneOptimization);
5077
5484
  for (const kind of opts.kinds ?? []) backend.registerKind(kind);
5078
5485
  let disposeCore;
5486
+ let removeActivity;
5079
5487
  let raf;
5080
5488
  try {
5081
5489
  const core = createClientCore({
@@ -5101,11 +5509,15 @@ function createClientWithRenderer(link, opts, renderer) {
5101
5509
  renderer.render();
5102
5510
  }
5103
5511
  let disposed = false;
5512
+ let inactive = false;
5513
+ let activityKnown = false;
5514
+ let stopped = false;
5515
+ let requestFrame = () => {};
5104
5516
  if (opts.frameLoop !== "manual") {
5105
5517
  let consecutiveFailures = 0;
5106
5518
  const loop = () => {
5107
5519
  raf = void 0;
5108
- if (disposed) return;
5520
+ if (disposed || inactive || stopped) return;
5109
5521
  let stop = false;
5110
5522
  try {
5111
5523
  renderFrame();
@@ -5113,17 +5525,35 @@ function createClientWithRenderer(link, opts, renderer) {
5113
5525
  } catch (error) {
5114
5526
  consecutiveFailures++;
5115
5527
  stop = renderer.deviceLost !== void 0 || consecutiveFailures >= MAX_CONSECUTIVE_FRAME_FAILURES;
5528
+ stopped = stop;
5116
5529
  core.reportError({
5117
5530
  source: "frame",
5118
5531
  message: stop ? `frame loop stopped after ${consecutiveFailures} failed frame(s): ${describeError(error)}` : `render frame failed: ${describeError(error)}`,
5119
5532
  cause: error
5120
5533
  });
5121
5534
  } finally {
5122
- if (!stop && !disposed && renderer.deviceLost === void 0) raf = requestAnimationFrame(loop);
5535
+ if (!stop) requestFrame();
5123
5536
  }
5124
5537
  };
5125
- raf = requestAnimationFrame(loop);
5538
+ requestFrame = () => {
5539
+ if (raf === void 0 && !disposed && !inactive && !stopped && renderer.deviceLost === void 0) raf = requestAnimationFrame(loop);
5540
+ };
5126
5541
  }
5542
+ if (opts.pauseWhenInactive ?? opts.frameLoop !== "manual") removeActivity = observePageActivity((active) => {
5543
+ if (activityKnown && inactive === !active) return;
5544
+ activityKnown = true;
5545
+ inactive = !active;
5546
+ core.control({
5547
+ action: "set-active",
5548
+ active
5549
+ });
5550
+ renderer.admission.setPaused(inactive);
5551
+ if (inactive) {
5552
+ if (raf !== void 0) cancelAnimationFrame(raf);
5553
+ raf = void 0;
5554
+ } else requestFrame();
5555
+ });
5556
+ requestFrame();
5127
5557
  link.postMessage({
5128
5558
  type: "control",
5129
5559
  control: { action: "request-keyframe" }
@@ -5157,6 +5587,7 @@ function createClientWithRenderer(link, opts, renderer) {
5157
5587
  dispose: () => {
5158
5588
  if (disposed) return;
5159
5589
  disposed = true;
5590
+ removeActivity?.();
5160
5591
  if (raf !== void 0) cancelAnimationFrame(raf);
5161
5592
  core.dispose();
5162
5593
  backend.dispose();
@@ -5165,6 +5596,7 @@ function createClientWithRenderer(link, opts, renderer) {
5165
5596
  }
5166
5597
  };
5167
5598
  } catch (error) {
5599
+ removeActivity?.();
5168
5600
  if (raf !== void 0) cancelAnimationFrame(raf);
5169
5601
  disposeCore?.();
5170
5602
  backend.dispose();
@@ -5330,19 +5762,17 @@ function mountClient(opts, client) {
5330
5762
  });
5331
5763
  const map = input;
5332
5764
  disposers.push(() => map.dispose());
5333
- if (typeof document !== "undefined") {
5765
+ if (opts.pauseWhenInactive ?? opts.frameLoop !== "manual") {
5334
5766
  let resume;
5335
- const visibility = () => {
5336
- if (document.hidden) resume ??= map.suspend();
5767
+ const removeActivity = observePageActivity((active) => {
5768
+ if (!active) resume ??= map.suspend();
5337
5769
  else {
5338
5770
  resume?.();
5339
5771
  resume = void 0;
5340
5772
  }
5341
- };
5342
- document.addEventListener("visibilitychange", visibility);
5343
- visibility();
5773
+ });
5344
5774
  disposers.push(() => {
5345
- document.removeEventListener("visibilitychange", visibility);
5775
+ removeActivity();
5346
5776
  resume?.();
5347
5777
  });
5348
5778
  }
@@ -5509,4 +5939,4 @@ function decodeStarCatalog(input) {
5509
5939
  }));
5510
5940
  }
5511
5941
  //#endregion
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 };
5942
+ 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, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };