@bendyline/molen-client 0.0.12 → 0.0.15

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,10 +1,12 @@
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-BliZYUY1.mjs";
3
+ import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-CzlS1f2N.mjs";
4
4
  import { createGlassVisual } from "./glass.mjs";
5
5
  import { n as liveryGraphicTexture, t as applyLivery } from "./livery-qcDLzbU9.mjs";
6
6
  import { a as cloudShellGeometry, i as cloudQualitySettings, n as CloudUniforms, o as createWebGlCloudMaterial, r as cloudDeckGeometry, s as cloudNoise, t as CloudTextures } from "./clouds-DmASLVoe.mjs";
7
+ import { a as createSnowCoverUniforms, f as writeSnowCover, s as injectSnowCover } from "./snow-cover-Bh0woabf.mjs";
7
8
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
9
+ import { a as isInstanceBatch, i as InstanceMatrixAttribute, n as INSTANCE_BATCH_MATRIX_COLUMNS, o as isInstanceBatchGeometry, r as InstanceBatch, t as INSTANCE_BATCH_COLOR } from "./instance-batch-Ds-oKQW4.mjs";
8
10
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
9
11
  import * as THREE from "three";
10
12
  import * as SkeletonUtils from "three/addons/utils/SkeletonUtils.js";
@@ -37,6 +39,12 @@ var AdaptiveQualityController = class {
37
39
  increaseDelayMs;
38
40
  cooldownMs;
39
41
  pauseFrameMs;
42
+ pauseRepeatMs;
43
+ upgradeWorkFraction;
44
+ strainDelayMs;
45
+ lastPauseMs = Number.NEGATIVE_INFINITY;
46
+ strained = false;
47
+ strainMs = 0;
40
48
  frames = [];
41
49
  frameCursor = 0;
42
50
  clockMs = 0;
@@ -75,6 +83,9 @@ var AdaptiveQualityController = class {
75
83
  this.increaseDelayMs = positive(options.increaseDelayMs ?? 1e4, "increaseDelayMs");
76
84
  this.cooldownMs = positive(options.cooldownMs ?? 2e3, "cooldownMs", true);
77
85
  this.pauseFrameMs = positive(options.pauseFrameMs ?? 1e3, "pauseFrameMs");
86
+ this.pauseRepeatMs = positive(options.pauseRepeatMs ?? 6e4, "pauseRepeatMs", true);
87
+ this.upgradeWorkFraction = positive(options.upgradeWorkFraction ?? .9, "upgradeWorkFraction");
88
+ this.strainDelayMs = positive(options.strainDelayMs ?? 1e4, "strainDelayMs", true);
78
89
  }
79
90
  /** No allocation in the usual per-frame path. A change object is returned only on a step. */
80
91
  sample(frameMs, sample = {}) {
@@ -85,8 +96,14 @@ var AdaptiveQualityController = class {
85
96
  }
86
97
  if (!Number.isFinite(frameMs) || frameMs <= 0) return;
87
98
  if (frameMs > this.pauseFrameMs && !this.previousPause) {
99
+ const repeated = this.clockMs - this.lastPauseMs < this.pauseRepeatMs;
100
+ this.lastPauseMs = this.clockMs;
88
101
  this.resetMeasurements();
89
102
  this.previousPause = true;
103
+ if (repeated && this.level > this.minLevel) {
104
+ this.lastPauseMs = Number.NEGATIVE_INFINITY;
105
+ return this.change(this.level - 1, "frame-time");
106
+ }
90
107
  return;
91
108
  }
92
109
  this.previousPause = frameMs > this.pauseFrameMs;
@@ -97,6 +114,7 @@ var AdaptiveQualityController = class {
97
114
  if (this.frames.length < 512) this.frames.push(elapsed);
98
115
  else this.frames[this.frameCursor++ % 512] = elapsed;
99
116
  this.loading ||= sample.loading === true;
117
+ this.strained ||= sample.strained === true;
100
118
  if (Number.isFinite(sample.cpuFrameMs) && (sample.cpuFrameMs ?? 0) > 0) {
101
119
  this.cpuTotalMs += sample.cpuFrameMs ?? 0;
102
120
  this.cpuSamples++;
@@ -159,17 +177,20 @@ var AdaptiveQualityController = class {
159
177
  const measured = this.cpuSamples > 0 || this.gpuSamples > 0;
160
178
  const measuredBoth = this.cpuSamples > 0 && this.gpuSamples > 0;
161
179
  const loading = this.loading;
180
+ const strained = this.strained;
162
181
  this.resetWindow();
163
182
  const overloaded = mean > this.targetFrameMs * 1.18 || this.p90FrameMs > this.targetFrameMs * 1.5 && this.slowFrameRatio >= .25;
164
- const headroom = (!loading || measuredBoth) && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
183
+ const headroom = (!loading || measuredBoth) && !strained && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * this.upgradeWorkFraction;
165
184
  const renderBound = !loading || !measured || work > this.targetFrameMs * .75;
166
185
  this.overloadMs = overloaded && renderBound ? this.overloadMs + elapsed : 0;
167
186
  this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
187
+ this.strainMs = strained ? this.strainMs + elapsed : 0;
168
188
  if (this.warmupElapsedMs < this.warmupMs) return;
169
189
  const memorySettling = loading && this.reason === "memory-pressure" && this.clockMs - this.lastChangeMs < this.increaseDelayMs;
170
190
  if (memory > 1 && this.level > this.minLevel && !memorySettling) return this.change(this.level - 1, "memory-pressure");
171
191
  if (this.clockMs - this.lastChangeMs < this.cooldownMs) return;
172
192
  if (overloaded && this.overloadMs >= this.decreaseDelayMs && this.level > this.minLevel) return this.change(this.level - 1, "frame-time");
193
+ if (strained && this.strainMs >= this.strainDelayMs && this.level > this.minLevel) return this.change(this.level - 1, "streaming");
173
194
  if (headroom && this.headroomMs >= this.increaseDelayMs * this.recoveryMultiplier && this.level < this.maxLevel) return this.change(this.level + 1, "headroom");
174
195
  }
175
196
  change(level, reason) {
@@ -185,6 +206,7 @@ var AdaptiveQualityController = class {
185
206
  this.lastChangeMs = this.clockMs;
186
207
  this.overloadMs = 0;
187
208
  this.headroomMs = 0;
209
+ this.strainMs = 0;
188
210
  return {
189
211
  previousLevel,
190
212
  level,
@@ -196,6 +218,7 @@ var AdaptiveQualityController = class {
196
218
  this.frameCursor = 0;
197
219
  this.windowMs = 0;
198
220
  this.loading = false;
221
+ this.strained = false;
199
222
  this.cpuTotalMs = 0;
200
223
  this.cpuSamples = 0;
201
224
  this.gpuTotalMs = 0;
@@ -208,6 +231,7 @@ var AdaptiveQualityController = class {
208
231
  this.warmupElapsedMs = 0;
209
232
  this.overloadMs = 0;
210
233
  this.headroomMs = 0;
234
+ this.strainMs = 0;
211
235
  this.smoothedFrameMs = void 0;
212
236
  this.p90FrameMs = void 0;
213
237
  this.slowFrameRatio = 0;
@@ -1210,7 +1234,7 @@ function applyEnvironment(renderer, env) {
1210
1234
  }
1211
1235
  scene.add(rig);
1212
1236
  renderer.three.shadowMap.enabled = shadows !== "off";
1213
- renderer.three.shadowMap.type = shadows === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
1237
+ renderer.three.shadowMap.type = shadows === "low" || renderer.backend === "webgl" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
1214
1238
  renderer.three.setClearColor(env.background !== void 0 ? new THREE.Color(env.background) : renderer.defaultClearColor, 1);
1215
1239
  scene.fog = env.fog !== void 0 ? new THREE.Fog(new THREE.Color(env.fog.color), env.fog.near ?? 1, env.fog.far ?? 1e3) : null;
1216
1240
  renderer.three.toneMapping = env.toneMapping === "aces" ? THREE.ACESFilmicToneMapping : env.toneMapping === "agx" ? THREE.AgXToneMapping : env.toneMapping === "neutral" ? THREE.NeutralToneMapping : THREE.NoToneMapping;
@@ -1468,22 +1492,26 @@ function injectCloudShadows(shader, uniforms) {
1468
1492
  const registered = /* @__PURE__ */ new WeakMap();
1469
1493
  let original;
1470
1494
  /**
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.
1495
+ * Give every lit shader `renderer` builds from now on the cloud shadow, and then whatever `also`
1496
+ * adds to it for the material being built (the sun's far shadow map, three/far-shadow.ts, and
1497
+ * lying snow, weather/snow-cover.ts). Call before its first frame.
1498
+ * Returns a function that unregisters it.
1473
1499
  */
1474
- function installWebGlCloudShadows(renderer, uniforms) {
1500
+ function installWebGlCloudShadows(renderer, uniforms, also) {
1475
1501
  if (original === void 0) {
1476
1502
  const previous = THREE.Material.prototype.onBeforeCompile;
1477
1503
  original = previous;
1478
1504
  const hook = function(shader, target) {
1479
1505
  previous.call(this, shader, target);
1480
- const own = registered.get(target);
1481
- if (own !== void 0) injectCloudShadows(shader, own);
1506
+ registered.get(target)?.(shader, this);
1482
1507
  };
1483
1508
  hook.toString = () => previous.toString();
1484
1509
  THREE.Material.prototype.onBeforeCompile = hook;
1485
1510
  }
1486
- registered.set(renderer, uniforms);
1511
+ registered.set(renderer, (shader, material) => {
1512
+ injectCloudShadows(shader, uniforms);
1513
+ also?.(shader, material);
1514
+ });
1487
1515
  return () => {
1488
1516
  registered.delete(renderer);
1489
1517
  };
@@ -2438,6 +2466,17 @@ function createGltfLoader(renderer, config = {}) {
2438
2466
  }
2439
2467
  //#endregion
2440
2468
  //#region src/frame-admission.ts
2469
+ /** The frame length per-frame budgets are set for: 60 frames a second. */
2470
+ const NOMINAL_FRAME_MS = 1e3 / 60;
2471
+ /**
2472
+ * Frames at least this long, `SLOW_FRAMES` in a row while work waits, are software rendering
2473
+ * (200 ms to a second a frame), not a device to keep interactive: there the budget is the same
2474
+ * share of the frame as of one at 60 a second. Interactive rates keep the fixed budget, which a
2475
+ * busy frame cannot spare (see earthAdmission). A fixed 2 ms of a 450 ms frame left streaming
2476
+ * under half a percent of the time, and a town's layers spent their two-minute deadline queued.
2477
+ */
2478
+ const SLOW_FRAME_MS = 100;
2479
+ const SLOW_FRAMES = 3;
2441
2480
  var FrameAdmissionQueue = class {
2442
2481
  options;
2443
2482
  jobs = [];
@@ -2446,6 +2485,14 @@ var FrameAdmissionQueue = class {
2446
2485
  scheduled = false;
2447
2486
  disposed = false;
2448
2487
  paused = false;
2488
+ /** Milliseconds past its budget the last flush ran, repaid from the frames after it. */
2489
+ overrunMs = 0;
2490
+ /** When the last flush finished, so a repaying frame knows how long it was. */
2491
+ lastFlushEnd;
2492
+ /** The last flush left work waiting, so the time since it ended is a frame, not idle time. */
2493
+ continuing = false;
2494
+ /** Frame lengths outside the queue while work waited, newest last, at most SLOW_FRAMES. */
2495
+ recentFrames = [];
2449
2496
  clock;
2450
2497
  schedule;
2451
2498
  maxMs;
@@ -2453,6 +2500,10 @@ var FrameAdmissionQueue = class {
2453
2500
  maxJobs;
2454
2501
  urgentStreak = 0;
2455
2502
  orderedStreak = 0;
2503
+ /** Jobs from the other lanes since the background lane last ran one. */
2504
+ foregroundStreak = 0;
2505
+ backgroundWaitMs;
2506
+ backgroundShare;
2456
2507
  /** Recent work time per label (ms, smoothed): what the next job of that kind will likely take. */
2457
2508
  expected = /* @__PURE__ */ new Map();
2458
2509
  constructor(options = {}) {
@@ -2465,6 +2516,9 @@ var FrameAdmissionQueue = class {
2465
2516
  this.maxMs = options.maxMilliseconds ?? 2;
2466
2517
  this.maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
2467
2518
  this.maxJobs = options.maxJobs ?? 32;
2519
+ this.backgroundWaitMs = options.backgroundWaitMs ?? 750;
2520
+ this.backgroundShare = options.backgroundShare ?? 8;
2521
+ if (!(this.backgroundWaitMs >= 0) || !(this.backgroundShare >= 1)) throw new RangeError("Background admission needs a nonnegative wait and a share of 1 or more");
2468
2522
  this.setLimits({});
2469
2523
  }
2470
2524
  /**
@@ -2549,6 +2603,7 @@ var FrameAdmissionQueue = class {
2549
2603
  /** Hold queued uploads/preparation while the view is inactive; keep resources for resume. */
2550
2604
  setPaused(paused) {
2551
2605
  this.paused = paused;
2606
+ if (paused) this.continuing = false;
2552
2607
  if (!paused) this.request();
2553
2608
  }
2554
2609
  request() {
@@ -2559,13 +2614,37 @@ var FrameAdmissionQueue = class {
2559
2614
  this.flush();
2560
2615
  });
2561
2616
  }
2562
- /** One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests. */
2617
+ /**
2618
+ * One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests.
2619
+ *
2620
+ * A job cannot be split, so one can take several frames' budget by itself, and a queue of them
2621
+ * would hold every frame at that length however small the budget. A frame that overruns repays
2622
+ * the excess from the frames after it, so the budget holds on average: a 20 ms shader build
2623
+ * every third frame, rather than every frame at half the frame rate, for the same throughput.
2624
+ *
2625
+ * The budget is a share of a frame at 60 a second. A frame that comes later than that repays
2626
+ * the same share of its own length: under software rendering a frame takes 200 ms or more, and
2627
+ * a job that waits on the GPU once is charged for a whole such frame, so repaying 2 ms a frame
2628
+ * left the queue idle for minutes. At 60 frames a second and faster nothing changes. Sustained
2629
+ * frames that slow also run that share of themselves (see SLOW_FRAME_MS).
2630
+ */
2563
2631
  flush() {
2564
2632
  if (this.disposed || this.paused) return;
2633
+ const sinceLast = this.lastFlushEnd === void 0 ? 0 : this.clock() - this.lastFlushEnd;
2634
+ const budget = this.frameBudget(sinceLast);
2635
+ if (this.overrunMs > 0) {
2636
+ const repaid = Math.max(this.maxMs, sinceLast * this.maxMs / NOMINAL_FRAME_MS);
2637
+ this.overrunMs = Math.max(0, this.overrunMs - repaid);
2638
+ this.lastFlushEnd = this.clock();
2639
+ this.continuing = this.pending > 0;
2640
+ this.request();
2641
+ return;
2642
+ }
2565
2643
  const start = this.clock();
2566
2644
  let bytes = 0, count = 0;
2567
2645
  for (;;) {
2568
- const lane = this.jobs.length > 0 ? this.jobs : this.background;
2646
+ const overdue = this.jobs.length > 0 && this.foregroundStreak >= this.backgroundShare && this.background.length > 0 && this.clock() - this.background[0].queued >= this.backgroundWaitMs;
2647
+ const lane = this.jobs.length > 0 && !overdue ? this.jobs : this.background;
2569
2648
  const waitingNormal = lane === this.jobs && this.urgentStreak >= 2 ? lane.findIndex((job) => job.options.priority !== "urgent") : -1;
2570
2649
  let index = waitingNormal >= 0 && this.clock() - lane[waitingNormal].queued >= 50 ? waitingNormal : 0;
2571
2650
  if (lane === this.jobs && lane[index]?.options.priority !== "urgent" && this.orderedStreak < 3) {
@@ -2582,7 +2661,7 @@ var FrameAdmissionQueue = class {
2582
2661
  if (next === void 0) break;
2583
2662
  const cost = next.options.bytes ?? 0;
2584
2663
  const label = next.options.label ?? "admission";
2585
- if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > this.maxMs || bytes + cost > this.maxBytes)) break;
2664
+ if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > budget || bytes + cost > this.maxBytes)) break;
2586
2665
  lane.splice(index, 1);
2587
2666
  this.forget(next);
2588
2667
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
@@ -2590,6 +2669,7 @@ var FrameAdmissionQueue = class {
2590
2669
  next.reject(new DOMException("Admission cancelled", "AbortError"));
2591
2670
  continue;
2592
2671
  }
2672
+ this.foregroundStreak = lane === this.background ? 0 : this.foregroundStreak + 1;
2593
2673
  this.urgentStreak = next.options.priority === "urgent" ? this.urgentStreak + 1 : 0;
2594
2674
  if (next.options.priority !== "urgent") this.orderedStreak = next.options.order !== void 0 && this.orderedStreak < 3 ? this.orderedStreak + 1 : 0;
2595
2675
  const began = this.clock();
@@ -2612,8 +2692,25 @@ var FrameAdmissionQueue = class {
2612
2692
  background: next.options.priority === "background"
2613
2693
  });
2614
2694
  }
2695
+ this.overrunMs = this.pending > 0 ? Math.max(0, this.clock() - start - budget) : 0;
2696
+ this.lastFlushEnd = this.clock();
2697
+ this.continuing = this.pending > 0;
2615
2698
  this.request();
2616
2699
  }
2700
+ /**
2701
+ * This frame's work allowance: the fixed budget, or for sustained software-rendering frames the
2702
+ * same share of the shortest recent one. One long frame (a hitch) changes nothing.
2703
+ */
2704
+ frameBudget(sinceLast) {
2705
+ if (!this.continuing) this.recentFrames.length = 0;
2706
+ else {
2707
+ this.recentFrames.push(sinceLast);
2708
+ if (this.recentFrames.length > SLOW_FRAMES) this.recentFrames.shift();
2709
+ }
2710
+ if (this.recentFrames.length < SLOW_FRAMES) return this.maxMs;
2711
+ const shortest = Math.min(...this.recentFrames);
2712
+ return shortest >= SLOW_FRAME_MS ? Math.max(this.maxMs, shortest * this.maxMs / NOMINAL_FRAME_MS) : this.maxMs;
2713
+ }
2617
2714
  dispose() {
2618
2715
  this.disposed = true;
2619
2716
  for (const job of [...this.jobs, ...this.background]) {
@@ -2829,6 +2926,16 @@ function starDirection(rightAscensionDeg, declinationDeg, state) {
2829
2926
  const RAD$1 = Math.PI / 180;
2830
2927
  /** Sky motion (radians) before the dome and stars redraw: about half a pixel at 70 degrees. */
2831
2928
  const SKY_REDRAW_ANGLE = 4e-4;
2929
+ /** The dome's vertex grid, which `domeColor` samples. */
2930
+ const DOME_COLUMNS = 96;
2931
+ const DOME_ROWS = 48;
2932
+ /** How far the Sun's glare reaches, in Sun disk radii. */
2933
+ const GLARE_SPREAD = 16;
2934
+ /**
2935
+ * The Sun's color multiplier, past what tone mapping can show. WebGPU blends before tone mapping,
2936
+ * so the glare needs it too: at plain Sun color it would top out grey around a white disk.
2937
+ */
2938
+ const SUN_RADIANCE = 2.5;
2832
2939
  const clamp$3 = (x) => Math.max(0, Math.min(1, x));
2833
2940
  const rgb$1 = (color) => [
2834
2941
  color.r,
@@ -2863,6 +2970,28 @@ function mesh(geometry, order, transparent = false) {
2863
2970
  result.frustumCulled = false;
2864
2971
  return result;
2865
2972
  }
2973
+ /**
2974
+ * The Sun's glare, which is what makes the real disk look far larger than its half degree: a unit
2975
+ * disk facing +Z whose vertex alpha falls with the inverse square of the angle, as veiling glare
2976
+ * does in the eye, windowed to reach zero at the rim. The material sets its color and strength.
2977
+ * It draws over the disk, which would otherwise tone map dimmer than the glare around it, and
2978
+ * under the Moon, which can cover it.
2979
+ */
2980
+ function sunGlare() {
2981
+ const glare = mesh(new THREE.RingGeometry(0, 1, 32, 16), -65, true);
2982
+ glare.material.blending = THREE.AdditiveBlending;
2983
+ const positions = glare.geometry.getAttribute("position");
2984
+ const colors = glare.geometry.getAttribute("color");
2985
+ for (let i = 0; i < positions.count; i++) {
2986
+ const x = positions.getX(i);
2987
+ const y = positions.getY(i);
2988
+ const ring = Math.hypot(x, y);
2989
+ const r = ring * ring;
2990
+ positions.setXY(i, x * ring, y * ring);
2991
+ colors.setXYZW(i, 1, 1, 1, (1 - r * r) ** 2 / (1 + (r / .12) ** 2));
2992
+ }
2993
+ return glare;
2994
+ }
2866
2995
  /** Seven vertices per star (a centre and six rim points), fanned into six triangles. */
2867
2996
  function starGeometry(count) {
2868
2997
  const geometry = new THREE.BufferGeometry();
@@ -2889,8 +3018,9 @@ var SkyVisual = class {
2889
3018
  moonLight = new THREE.DirectionalLight();
2890
3019
  ambientLight = new THREE.HemisphereLight();
2891
3020
  data;
2892
- dome = mesh(new THREE.SphereGeometry(2, 96, 48), -100);
3021
+ dome = mesh(new THREE.SphereGeometry(2, DOME_COLUMNS, DOME_ROWS), -100);
2893
3022
  sun = mesh(new THREE.SphereGeometry(1, 32, 16), -70, true);
3023
+ glare = sunGlare();
2894
3024
  moon = mesh(new THREE.SphereGeometry(1, 64, 32), -60, true);
2895
3025
  stars;
2896
3026
  catalog;
@@ -2921,13 +3051,14 @@ var SkyVisual = class {
2921
3051
  this.scene.name = "molen:sky";
2922
3052
  this.lights.name = "molen:sky-lights";
2923
3053
  this.dome.name = "molen:sky-dome";
3054
+ this.glare.name = "molen:sky-sun-glare";
2924
3055
  this.sun.name = "molen:sky-sun";
2925
3056
  this.moon.name = "molen:sky-moon";
2926
3057
  this.catalog = this.catalogFrom(options.stars);
2927
3058
  this.stars = mesh(starGeometry(this.catalog.length), -80, true);
2928
3059
  this.stars.material.blending = THREE.AdditiveBlending;
2929
3060
  this.stars.name = "molen:sky-stars";
2930
- this.scene.add(this.dome, this.stars, this.sun, this.moon);
3061
+ this.scene.add(this.dome, this.stars, this.sun, this.glare, this.moon);
2931
3062
  this.lights.add(this.ambientLight, this.sunLight, this.sunLight.target, this.moonLight, this.moonLight.target);
2932
3063
  const shadows = options.shadows ?? "off";
2933
3064
  if (shadows !== "off" && data.lighting?.castShadow !== false) {
@@ -3021,6 +3152,7 @@ var SkyVisual = class {
3021
3152
  this.updateDome(altitude, sunVector, daylight);
3022
3153
  this.updateBody(this.sun, sunVector, sunDiameterDeg * (data.sun?.size ?? 1), sunVector, false);
3023
3154
  this.sun.visible = data.sun?.visible !== false && this.sun.visible;
3155
+ this.updateGlare(sunVector, altitude);
3024
3156
  this.moon.visible = false;
3025
3157
  if (moonVector && data.moon?.visible !== false) this.updateBody(this.moon, moonVector, moonDiameterDeg * (data.moon?.size ?? 1), sunVector, true);
3026
3158
  const rotation = new THREE.Matrix4();
@@ -3135,17 +3267,73 @@ var SkyVisual = class {
3135
3267
  body.visible = direction.y + radius > 0;
3136
3268
  const positions = body.geometry.getAttribute("position");
3137
3269
  const colors = body.geometry.getAttribute("color");
3138
- const base = lunar ? this.palette.moon : this.palette.sun.clone().lerp(this.palette.twilight, 1 - smooth$2(0, .2, direction.y));
3270
+ const base = lunar ? this.palette.moon : this.sunColor(direction);
3271
+ const earthshine = (this.data.moon?.earthshine ?? .025) * (1 - this.currentFrame.daylight);
3139
3272
  const normal = new THREE.Vector3();
3273
+ const toward = new THREE.Vector3();
3274
+ const behind = new THREE.Color(0, 0, 0);
3140
3275
  for (let i = 0; i < positions.count; i++) {
3141
3276
  normal.fromBufferAttribute(positions, i).normalize();
3142
- const illumination = lunar ? (this.data.moon?.earthshine ?? .025) + Math.max(0, normal.dot(sun)) * .975 : 2.5;
3277
+ const illumination = lunar ? earthshine + Math.max(0, normal.dot(sun)) * .975 : SUN_RADIANCE;
3143
3278
  const albedo = lunar ? .85 + .15 * Math.sin(normal.x * 27 + Math.sin(normal.y * 19) * 2) * Math.sin(normal.z * 21) : 1;
3144
- colors.setXYZW(i, base.r * illumination * albedo, base.g * illumination * albedo, base.b * illumination * albedo, smooth$2(-3e-4, 3e-4, direction.y + normal.y * radius));
3279
+ if (lunar) {
3280
+ toward.copy(direction).addScaledVector(normal, radius).normalize();
3281
+ this.domeColor(toward, behind);
3282
+ }
3283
+ colors.setXYZW(i, behind.r + base.r * illumination * albedo, behind.g + base.g * illumination * albedo, behind.b + base.b * illumination * albedo, smooth$2(-3e-4, 3e-4, direction.y + normal.y * radius));
3145
3284
  }
3146
3285
  colors.needsUpdate = true;
3147
3286
  body.material.side = THREE.FrontSide;
3148
3287
  }
3288
+ sunColor(direction) {
3289
+ return this.palette.sun.clone().lerp(this.palette.twilight, 1 - smooth$2(0, .2, direction.y));
3290
+ }
3291
+ updateGlare(sun, altitude) {
3292
+ this.glare.visible = this.sun.visible;
3293
+ this.glare.position.copy(sun);
3294
+ this.glare.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), sun);
3295
+ this.glare.scale.setScalar(this.sun.scale.x * GLARE_SPREAD);
3296
+ this.glare.material.color.copy(this.sunColor(sun)).multiplyScalar(SUN_RADIANCE);
3297
+ this.glare.material.opacity = smooth$2(-2, 5, altitude);
3298
+ }
3299
+ /** The drawn dome's color toward a unit direction, interpolated across its vertex grid. */
3300
+ domeColor(direction, target) {
3301
+ const colors = this.dome.geometry.getAttribute("color");
3302
+ const across = (Math.atan2(direction.z, -direction.x) / (2 * Math.PI) + 1) % 1 * DOME_COLUMNS;
3303
+ const down = Math.acos(Math.max(-1, Math.min(1, direction.y))) / Math.PI * DOME_ROWS;
3304
+ const column = Math.floor(across);
3305
+ const row = Math.min(DOME_ROWS - 1, Math.floor(down));
3306
+ const right = across - column;
3307
+ const lower = down - row;
3308
+ target.setRGB(0, 0, 0);
3309
+ for (const [dx, dy, weight] of [
3310
+ [
3311
+ 0,
3312
+ 0,
3313
+ (1 - right) * (1 - lower)
3314
+ ],
3315
+ [
3316
+ 1,
3317
+ 0,
3318
+ right * (1 - lower)
3319
+ ],
3320
+ [
3321
+ 0,
3322
+ 1,
3323
+ (1 - right) * lower
3324
+ ],
3325
+ [
3326
+ 1,
3327
+ 1,
3328
+ right * lower
3329
+ ]
3330
+ ]) {
3331
+ const vertex = (row + dy) * 97 + column + dx;
3332
+ target.r += colors.getX(vertex) * weight;
3333
+ target.g += colors.getY(vertex) * weight;
3334
+ target.b += colors.getZ(vertex) * weight;
3335
+ }
3336
+ }
3149
3337
  /**
3150
3338
  * Replace the star catalog, e.g. once a catalog loaded from a content pack arrives. `undefined`
3151
3339
  * removes the stars. Takes effect on the next update.
@@ -3209,6 +3397,7 @@ var SkyVisual = class {
3209
3397
  for (const object of [
3210
3398
  this.dome,
3211
3399
  this.sun,
3400
+ this.glare,
3212
3401
  this.moon,
3213
3402
  this.stars
3214
3403
  ]) {
@@ -3627,6 +3816,294 @@ var WeatherVisual = class {
3627
3816
  }
3628
3817
  };
3629
3818
  //#endregion
3819
+ //#region src/three/shadow-focus.ts
3820
+ const SHADOW_MAP_SIZE = {
3821
+ low: 1024,
3822
+ medium: 2048,
3823
+ high: 4096
3824
+ };
3825
+ const UP = new THREE.Vector3(0, 1, 0);
3826
+ const VERTICAL_UP = new THREE.Vector3(1, 0, 0);
3827
+ const shadowRadii = /* @__PURE__ */ new WeakMap();
3828
+ const scratchCenter = new THREE.Vector3();
3829
+ const scratchRight = new THREE.Vector3();
3830
+ const scratchUp = new THREE.Vector3();
3831
+ const scratchForward = new THREE.Vector3();
3832
+ /** Keep the projection fixed through small altitude/zoom changes, including at a bucket edge. */
3833
+ function stableRadius(light, requested) {
3834
+ const previous = shadowRadii.get(light);
3835
+ if (previous !== void 0 && requested <= previous && requested >= previous * .8) return previous;
3836
+ const step = 2 ** Math.floor(Math.log2(requested)) / 8;
3837
+ const radius = Math.ceil(requested / step) * step;
3838
+ shadowRadii.set(light, radius);
3839
+ return radius;
3840
+ }
3841
+ /**
3842
+ * Aim `light`'s shadow at `center` (scene coordinates, after rebasing) from `direction` (a unit
3843
+ * vector toward the sun), covering at least ±`radius`. The light and its target move; the direction of
3844
+ * the light is unchanged.
3845
+ */
3846
+ function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false, worldOrigin = [
3847
+ 0,
3848
+ 0,
3849
+ 0
3850
+ ]) {
3851
+ radius = stableRadius(light, radius);
3852
+ const toSun = scratchForward.copy(direction).normalize();
3853
+ const size = light.shadow.mapSize.x || 2048;
3854
+ const texel = 2 * radius / size;
3855
+ const camera = light.shadow.camera;
3856
+ camera.up.copy(Math.abs(toSun.y) > .999 ? VERTICAL_UP : UP);
3857
+ const right = scratchRight.crossVectors(camera.up, toSun);
3858
+ right.normalize();
3859
+ const up = scratchUp.crossVectors(toSun, right).normalize();
3860
+ const snapped = scratchCenter.copy(center);
3861
+ snapped.x += worldOrigin[0];
3862
+ snapped.y += worldOrigin[1];
3863
+ snapped.z += worldOrigin[2];
3864
+ const along = snapped.dot(toSun);
3865
+ const x = Math.round(snapped.dot(right) / texel) * texel;
3866
+ const y = Math.round(snapped.dot(up) / texel) * texel;
3867
+ snapped.copy(right).multiplyScalar(x).addScaledVector(up, y).addScaledVector(toSun, along);
3868
+ snapped.x -= worldOrigin[0];
3869
+ snapped.y -= worldOrigin[1];
3870
+ snapped.z -= worldOrigin[2];
3871
+ const distance = radius * 2 + 1e3;
3872
+ light.target.position.copy(snapped);
3873
+ light.position.copy(snapped).addScaledVector(toSun, distance);
3874
+ light.target.updateMatrixWorld();
3875
+ light.updateMatrixWorld();
3876
+ if (camera.left !== -radius || camera.top !== radius || camera.far !== distance + radius * 2 + 1e3) {
3877
+ camera.left = -radius;
3878
+ camera.right = radius;
3879
+ camera.top = radius;
3880
+ camera.bottom = -radius;
3881
+ camera.near = 1;
3882
+ camera.far = distance + radius * 2 + 1e3;
3883
+ camera.updateProjectionMatrix();
3884
+ }
3885
+ const bias = texel * .25 / (camera.far - camera.near);
3886
+ light.shadow.bias = biasAddsTowardLight ? bias : -bias;
3887
+ light.shadow.normalBias = texel * 1.2;
3888
+ light.shadow.radius = .5;
3889
+ }
3890
+ //#endregion
3891
+ //#region src/three/far-shadow.ts
3892
+ /** Where the focused map starts handing over to the far one, as a share of its half-width. */
3893
+ const HANDOVER = .8;
3894
+ /** Redraw once the wanted center is this share of the radius from the drawn one. */
3895
+ const DRIFT = .125;
3896
+ /** Redraw for scenery that arrived since, ms. */
3897
+ const REFRESH_MS = 1e3;
3898
+ /** Redraw once the sun has moved this far, radians (0.2 degrees). */
3899
+ const SUN_TURN = .0035;
3900
+ const PARS_VERTEX = `
3901
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
3902
+ uniform mat4 molenFarShadowMatrix;
3903
+ uniform vec4 molenFarShadow;
3904
+ varying vec4 vMolenFarShadowCoord;
3905
+ #endif
3906
+ `;
3907
+ const VERTEX = `
3908
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
3909
+ vMolenFarShadowCoord = molenFarShadowMatrix * ( worldPosition + vec4( shadowWorldNormal * molenFarShadow.z, 0.0 ) );
3910
+ #endif
3911
+ `;
3912
+ const PARS_FRAGMENT = `
3913
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
3914
+ uniform vec4 molenFarShadow;
3915
+ varying vec4 vMolenFarShadowCoord;
3916
+ #if defined( SHADOWMAP_TYPE_PCF )
3917
+ uniform sampler2DShadow molenFarShadowMap;
3918
+ // Sunlight reaching this fragment by the far map: 1 outside it, fading in from its edge.
3919
+ float molenFarShadowAt() {
3920
+ vec3 coord = vMolenFarShadowCoord.xyz / vMolenFarShadowCoord.w;
3921
+ coord.z += molenFarShadow.y;
3922
+ vec2 fromCenter = abs( coord.xy - 0.5 ) * 2.0;
3923
+ float edge = max( fromCenter.x, fromCenter.y );
3924
+ if ( edge >= 1.0 || coord.z > 1.0 ) return 1.0;
3925
+ vec2 texel = vec2( 0.5 ) / vec2( textureSize( molenFarShadowMap, 0 ) );
3926
+ float lit = 0.25 * (
3927
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( - texel.x, - texel.y ), coord.z ) ) +
3928
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( texel.x, - texel.y ), coord.z ) ) +
3929
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( - texel.x, texel.y ), coord.z ) ) +
3930
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( texel.x, texel.y ), coord.z ) )
3931
+ );
3932
+ return mix( 1.0, lit, molenFarShadow.x * ( 1.0 - smoothstep( 0.8, 1.0, edge ) ) );
3933
+ }
3934
+ #endif
3935
+ // The first directional light's shadow: the focused map's, handing over to the far map
3936
+ // toward the focused map's edge and beyond it.
3937
+ float molenSunShadow( int index, float near, vec4 nearCoord ) {
3938
+ #if defined( SHADOWMAP_TYPE_PCF )
3939
+ if ( index != 0 || molenFarShadow.x <= 0.0 ) return near;
3940
+ vec2 fromCenter = abs( nearCoord.xy / nearCoord.w - 0.5 ) * 2.0;
3941
+ float handover = smoothstep( molenFarShadow.w, 1.0, max( fromCenter.x, fromCenter.y ) );
3942
+ if ( handover <= 0.0 ) return near;
3943
+ return mix( near, molenFarShadowAt(), handover );
3944
+ #else
3945
+ return near;
3946
+ #endif
3947
+ }
3948
+ #endif
3949
+ `;
3950
+ const CALL = "getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] )";
3951
+ function createFarShadowUniforms() {
3952
+ const none = new THREE.DepthTexture(1, 1);
3953
+ none.name = "molen:far-shadow-none";
3954
+ none.compareFunction = THREE.LessEqualCompare;
3955
+ none.needsUpdate = true;
3956
+ return {
3957
+ molenFarShadowMap: { value: none },
3958
+ molenFarShadowMatrix: { value: new THREE.Matrix4() },
3959
+ molenFarShadow: { value: new THREE.Vector4(0, 0, 0, HANDOVER) }
3960
+ };
3961
+ }
3962
+ /**
3963
+ * Give a WebGL shader built from three's lighting chunks the far shadow map; false if it has
3964
+ * none of them (an unlit or hand-written shader), which is then left as it was.
3965
+ */
3966
+ function injectFarShadow(shader, uniforms) {
3967
+ const parsVertex = "#include <shadowmap_pars_vertex>";
3968
+ const vertex = "#include <shadowmap_vertex>";
3969
+ const parsFragment = "#include <shadowmap_pars_fragment>";
3970
+ const lights = "#include <lights_fragment_begin>";
3971
+ let fragment = shader.fragmentShader;
3972
+ if (fragment.includes(lights)) fragment = fragment.replace(lights, THREE.ShaderChunk.lights_fragment_begin);
3973
+ if (!shader.vertexShader.includes(parsVertex) || !shader.vertexShader.includes(vertex) || !fragment.includes(parsFragment) || !fragment.includes(CALL)) return false;
3974
+ shader.vertexShader = shader.vertexShader.replace(parsVertex, `${parsVertex}\n${PARS_VERTEX}`).replace(vertex, `${vertex}\n${VERTEX}`);
3975
+ shader.fragmentShader = fragment.replace(parsFragment, `${parsFragment}\n${PARS_FRAGMENT}`).replace(CALL, `molenSunShadow( UNROLLED_LOOP_INDEX, ${CALL}, vDirectionalShadowCoord[ i ] )`);
3976
+ Object.assign(shader.uniforms, uniforms);
3977
+ return true;
3978
+ }
3979
+ /** The far map of one WebGL renderer: when to draw it, and the uniforms every lit shader reads. */
3980
+ var FarShadow = class {
3981
+ uniforms = createFarShadowUniforms();
3982
+ none = this.uniforms.molenFarShadowMap.value;
3983
+ /** Never in the scene: three's shadow pass draws for it when asked to. */
3984
+ light = new THREE.DirectionalLight();
3985
+ casters;
3986
+ scene;
3987
+ pending = false;
3988
+ drawn = false;
3989
+ drawnAt = Number.NEGATIVE_INFINITY;
3990
+ drawnRadius = 0;
3991
+ /** Absolute world coordinates. */
3992
+ drawnCenter = new THREE.Vector3();
3993
+ drawnDirection = new THREE.Vector3();
3994
+ drawnOrigin = [
3995
+ 0,
3996
+ 0,
3997
+ 0
3998
+ ];
3999
+ drawnMatrix = new THREE.Matrix4();
4000
+ origin = [
4001
+ 0,
4002
+ 0,
4003
+ 0
4004
+ ];
4005
+ wanted = new THREE.Vector3();
4006
+ shift = new THREE.Matrix4();
4007
+ release;
4008
+ draws = 0;
4009
+ lastDrawMs = 0;
4010
+ constructor(renderer) {
4011
+ this.light.name = "molen:far-shadow";
4012
+ this.light.shadow.autoUpdate = false;
4013
+ const shadowMap = renderer.shadowMap;
4014
+ const render = shadowMap.render;
4015
+ if (typeof render !== "function") {
4016
+ this.release = () => {};
4017
+ return;
4018
+ }
4019
+ shadowMap.render = (lights, scene, camera) => {
4020
+ render.call(shadowMap, lights, scene, camera);
4021
+ if (!this.pending || scene !== this.scene || this.casters === void 0) return;
4022
+ this.pending = false;
4023
+ const started = performance.now();
4024
+ this.light.shadow.needsUpdate = true;
4025
+ render.call(shadowMap, [this.light], this.casters, camera);
4026
+ this.lastDrawMs = performance.now() - started;
4027
+ const map = this.light.shadow.map;
4028
+ const depth = map?.depthTexture;
4029
+ if (map === null || depth === null || depth === void 0) return;
4030
+ this.draws++;
4031
+ this.drawn = true;
4032
+ this.drawnMatrix.copy(this.light.shadow.matrix);
4033
+ this.drawnOrigin[0] = this.origin[0];
4034
+ this.drawnOrigin[1] = this.origin[1];
4035
+ this.drawnOrigin[2] = this.origin[2];
4036
+ this.uniforms.molenFarShadowMap.value = depth;
4037
+ this.uniforms.molenFarShadowMatrix.value.copy(this.drawnMatrix);
4038
+ this.uniforms.molenFarShadow.value.set(1, this.light.shadow.bias, this.light.shadow.normalBias, HANDOVER);
4039
+ };
4040
+ this.release = () => {
4041
+ shadowMap.render = render;
4042
+ };
4043
+ }
4044
+ /** The scene whose render draws the map, and the static root it is drawn from. */
4045
+ setCasters(scene, casters) {
4046
+ this.scene = scene;
4047
+ if (this.casters === casters) return;
4048
+ this.casters = casters;
4049
+ this.drawn = false;
4050
+ }
4051
+ get info() {
4052
+ return this.drawn ? {
4053
+ radius: this.drawnRadius,
4054
+ draws: this.draws,
4055
+ lastDrawMs: this.lastDrawMs
4056
+ } : void 0;
4057
+ }
4058
+ /** Before each frame: `view` while the sun casts shadows and a far radius is wanted. */
4059
+ update(view) {
4060
+ const state = this.uniforms.molenFarShadow.value;
4061
+ if (view === void 0 || this.casters === void 0) {
4062
+ state.x = 0;
4063
+ this.pending = false;
4064
+ this.drawn = false;
4065
+ return;
4066
+ }
4067
+ const shadow = this.light.shadow;
4068
+ if (shadow.mapSize.x !== view.mapSize) {
4069
+ shadow.mapSize.set(view.mapSize, view.mapSize);
4070
+ this.disposeMap();
4071
+ }
4072
+ this.origin = view.worldOrigin;
4073
+ const wanted = this.wanted.set(view.center.x + view.worldOrigin[0], view.center.y + view.worldOrigin[1], view.center.z + view.worldOrigin[2]);
4074
+ if (!this.drawn || view.now - this.drawnAt >= REFRESH_MS || view.radius > this.drawnRadius || view.radius < this.drawnRadius * .7 || wanted.distanceTo(this.drawnCenter) > this.drawnRadius * DRIFT || view.direction.angleTo(this.drawnDirection) > SUN_TURN) {
4075
+ focusDirectionalShadow(this.light, view.direction, view.center, view.radius, view.biasAddsTowardLight, view.worldOrigin);
4076
+ this.drawnAt = view.now;
4077
+ this.drawnRadius = shadow.camera.right;
4078
+ this.drawnCenter.copy(wanted);
4079
+ this.drawnDirection.copy(view.direction);
4080
+ this.pending = true;
4081
+ }
4082
+ if (!this.drawn) {
4083
+ state.x = 0;
4084
+ return;
4085
+ }
4086
+ state.x = 1;
4087
+ this.uniforms.molenFarShadowMatrix.value.multiplyMatrices(this.drawnMatrix, this.shift.makeTranslation(view.worldOrigin[0] - this.drawnOrigin[0], view.worldOrigin[1] - this.drawnOrigin[1], view.worldOrigin[2] - this.drawnOrigin[2]));
4088
+ }
4089
+ disposeMap() {
4090
+ const map = this.light.shadow.map;
4091
+ this.uniforms.molenFarShadowMap.value = this.none;
4092
+ this.uniforms.molenFarShadow.value.x = 0;
4093
+ this.drawn = false;
4094
+ if (map === null) return;
4095
+ map.depthTexture?.dispose();
4096
+ map.dispose();
4097
+ this.light.shadow.map = null;
4098
+ }
4099
+ dispose() {
4100
+ this.release();
4101
+ this.disposeMap();
4102
+ this.none.dispose();
4103
+ this.light.dispose();
4104
+ }
4105
+ };
4106
+ //#endregion
3630
4107
  //#region src/three/gpu-frame-timer.ts
3631
4108
  /**
3632
4109
  * Optional WebGL2 timing. Reads a result only after QUERY_RESULT_AVAILABLE; never waits,
@@ -3743,78 +4220,6 @@ function createGpuFrameTimer(context, options = {}) {
3743
4220
  };
3744
4221
  }
3745
4222
  //#endregion
3746
- //#region src/three/shadow-focus.ts
3747
- const SHADOW_MAP_SIZE = {
3748
- low: 1024,
3749
- medium: 2048,
3750
- high: 4096
3751
- };
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();
3755
- const scratchCenter = new THREE.Vector3();
3756
- const scratchRight = new THREE.Vector3();
3757
- const scratchUp = new THREE.Vector3();
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
- }
3768
- /**
3769
- * Aim `light`'s shadow at `center` (scene coordinates, after rebasing) from `direction` (a unit
3770
- * vector toward the sun), covering at least ±`radius`. The light and its target move; the direction of
3771
- * the light is unchanged.
3772
- */
3773
- function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false, worldOrigin = [
3774
- 0,
3775
- 0,
3776
- 0
3777
- ]) {
3778
- radius = stableRadius(light, radius);
3779
- const toSun = scratchForward.copy(direction).normalize();
3780
- const size = light.shadow.mapSize.x || 2048;
3781
- const texel = 2 * radius / size;
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);
3785
- right.normalize();
3786
- const up = scratchUp.crossVectors(toSun, right).normalize();
3787
- const snapped = scratchCenter.copy(center);
3788
- snapped.x += worldOrigin[0];
3789
- snapped.y += worldOrigin[1];
3790
- snapped.z += worldOrigin[2];
3791
- const along = snapped.dot(toSun);
3792
- const x = Math.round(snapped.dot(right) / texel) * texel;
3793
- const y = Math.round(snapped.dot(up) / texel) * texel;
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];
3798
- const distance = radius * 2 + 1e3;
3799
- light.target.position.copy(snapped);
3800
- light.position.copy(snapped).addScaledVector(toSun, distance);
3801
- light.target.updateMatrixWorld();
3802
- light.updateMatrixWorld();
3803
- if (camera.left !== -radius || camera.top !== radius || camera.far !== distance + radius * 2 + 1e3) {
3804
- camera.left = -radius;
3805
- camera.right = radius;
3806
- camera.top = radius;
3807
- camera.bottom = -radius;
3808
- camera.near = 1;
3809
- camera.far = distance + radius * 2 + 1e3;
3810
- camera.updateProjectionMatrix();
3811
- }
3812
- const bias = texel * .25 / (camera.far - camera.near);
3813
- light.shadow.bias = biasAddsTowardLight ? bias : -bias;
3814
- light.shadow.normalBias = texel * 1.2;
3815
- light.shadow.radius = .5;
3816
- }
3817
- //#endregion
3818
4223
  //#region src/three/sky-reflections.ts
3819
4224
  const WIDTH = 256;
3820
4225
  const HEIGHT = 128;
@@ -4091,6 +4496,8 @@ var Renderer = class Renderer {
4091
4496
  /** Cloud textures and the cloud-shadow uniforms every lit shader reads, for the renderer's life. */
4092
4497
  cloudTextures = new CloudTextures(cloudNoise());
4093
4498
  cloudShadows = createCloudShadowUniforms(this.cloudTextures.shadow);
4499
+ /** The weather's lying snow, read by every material marked with `enableSnowCover`. */
4500
+ snowCover = createSnowCoverUniforms();
4094
4501
  cloudBackend;
4095
4502
  releaseCloudShadows;
4096
4503
  cloudQualityLevel = "medium";
@@ -4107,6 +4514,10 @@ var Renderer = class Renderer {
4107
4514
  shadowFocus;
4108
4515
  shadowCenter = new THREE.Vector3();
4109
4516
  shadowDirection = new THREE.Vector3();
4517
+ /** The sun's far shadow map (WebGL); see setFarShadowCasters. */
4518
+ farShadow;
4519
+ farShadowCenter = new THREE.Vector3();
4520
+ farShadowDirection = new THREE.Vector3();
4110
4521
  /** Active clear-sky visual and sampled ephemeris, when environment.sky is configured. */
4111
4522
  get sky() {
4112
4523
  return this.activeSky;
@@ -4118,12 +4529,47 @@ var Renderer = class Renderer {
4118
4529
  */
4119
4530
  setShadowFocus(focus) {
4120
4531
  if (focus !== void 0 && (!(focus.radius > 0) || !Number.isFinite(focus.radius))) throw new RangeError("Shadow focus radius must be a positive number of meters");
4532
+ const far = focus?.far;
4533
+ if (far !== void 0 && (!(far.radius > 0) || !Number.isFinite(far.radius))) throw new RangeError("Far shadow radius must be a positive number of meters");
4121
4534
  this.shadowFocus = focus === void 0 ? void 0 : {
4122
4535
  center: [...focus.center],
4123
- radius: focus.radius
4536
+ radius: focus.radius,
4537
+ ...far !== void 0 ? { far: {
4538
+ center: [...far.center],
4539
+ radius: far.radius
4540
+ } } : {}
4124
4541
  };
4125
4542
  }
4126
4543
  /**
4544
+ * The scenery that does not move (a terrain stream's object: ground, buildings, trees), for the
4545
+ * sun's far shadow map. With it and a focus that names a `far` square, surfaces past the
4546
+ * focused map are shadowed from a second, wider map instead of ending in sunlight: over a
4547
+ * city the focused map ends a few hundred meters out, and buildings gained their shadows as
4548
+ * it reached them. Only what is under `root` casts into it, and it is redrawn when the camera
4549
+ * has left its middle, when the sun has moved and about once a second for scenery that has
4550
+ * arrived, so a moving caster would leave its shadow behind. WebGL; `undefined` turns it off.
4551
+ */
4552
+ setFarShadowCasters(root) {
4553
+ this.farShadow?.setCasters(this.scene, root);
4554
+ }
4555
+ /** The far shadow map as last drawn, or `undefined` while there is none. */
4556
+ get farShadowInfo() {
4557
+ return this.farShadow?.info;
4558
+ }
4559
+ /**
4560
+ * Meters one texel of the sun's shadow map covers as of the last frame, or `undefined` while sun
4561
+ * shadows are off or parked. A focus over a wide view coarsens it: hosts use it to keep a subject
4562
+ * the map cannot resolve out of the shadow pass (`AircraftVisual.updateShadows`).
4563
+ */
4564
+ get shadowTexelSize() {
4565
+ if (!this.three.shadowMap.enabled) return void 0;
4566
+ for (const light of this.sunLights()) {
4567
+ if (!light.castShadow || light.shadow.intensity <= 0) continue;
4568
+ const camera = light.shadow.camera;
4569
+ return (camera.right - camera.left) / (light.shadow.mapSize.x || 1);
4570
+ }
4571
+ }
4572
+ /**
4127
4573
  * Turn sun shadows on at a map resolution, or off, without rebuilding the environment. Once a
4128
4574
  * light has cast shadows, 'off' stops redrawing its map and fades it out, so every lit shader
4129
4575
  * keeps the shadow inputs it was built with: a host that turns shadows on once before its first
@@ -4164,7 +4610,7 @@ var Renderer = class Renderer {
4164
4610
  if (this.backend === "webgpu" && this.three.shadowMap.enabled) return;
4165
4611
  if (parked && this.three.shadowMap.enabled) return;
4166
4612
  this.three.shadowMap.enabled = enabled;
4167
- this.three.shadowMap.type = quality === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
4613
+ this.three.shadowMap.type = quality === "low" || this.backend === "webgl" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
4168
4614
  }
4169
4615
  /** WebGL PCF shadow lookups against a reversed depth buffer; see focusDirectionalShadow. */
4170
4616
  webglReversedPcfShadows() {
@@ -4182,12 +4628,26 @@ var Renderer = class Renderer {
4182
4628
  }
4183
4629
  applyShadowFocus() {
4184
4630
  const focus = this.shadowFocus;
4185
- if (focus === void 0 || !this.three.shadowMap.enabled) return;
4186
- const center = this.shadowCenter.set(focus.center[0] - this.worldOrigin[0], focus.center[1] - this.worldOrigin[1], focus.center[2] - this.worldOrigin[2]);
4187
- for (const light of this.sunLights()) {
4188
- if (!light.castShadow) continue;
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);
4631
+ let far;
4632
+ if (focus !== void 0 && this.three.shadowMap.enabled) {
4633
+ const center = this.shadowCenter.set(focus.center[0] - this.worldOrigin[0], focus.center[1] - this.worldOrigin[1], focus.center[2] - this.worldOrigin[2]);
4634
+ const reversedPcf = this.backend === "webgl" && this.webglReversedPcfShadows();
4635
+ for (const light of this.sunLights()) {
4636
+ if (!light.castShadow) continue;
4637
+ const direction = light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection);
4638
+ focusDirectionalShadow(light, direction, center, focus.radius, reversedPcf, this.worldOrigin);
4639
+ if (far === void 0 && focus.far !== void 0 && light.shadow.autoUpdate && light.shadow.intensity > 0 && light.visible && direction.y > .02) far = {
4640
+ direction: this.farShadowDirection.copy(direction).normalize(),
4641
+ center: this.farShadowCenter.set(focus.far.center[0] - this.worldOrigin[0], focus.far.center[1] - this.worldOrigin[1], focus.far.center[2] - this.worldOrigin[2]),
4642
+ radius: focus.far.radius,
4643
+ mapSize: Math.min(2048, light.shadow.mapSize.x),
4644
+ biasAddsTowardLight: reversedPcf,
4645
+ worldOrigin: this.worldOrigin,
4646
+ now: performance.now()
4647
+ };
4648
+ }
4190
4649
  }
4650
+ this.farShadow?.update(far);
4191
4651
  }
4192
4652
  /** Active weather effects; physical weather data is also available in the simulation component. */
4193
4653
  get weather() {
@@ -4269,19 +4729,21 @@ var Renderer = class Renderer {
4269
4729
  try {
4270
4730
  if (typeof navigator === "undefined" || !("gpu" in navigator) || !navigator.gpu) throw new Error("WebGPU is unavailable in this browser or context");
4271
4731
  if (await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request") === null) throw new Error("WebGPU reported no adapter for this device");
4272
- const { createWebGpuDriver } = await import("./webgpu-driver-BQnmPRqs.mjs");
4732
+ const { createWebGpuDriver } = await import("./webgpu-driver-YWVTLOY7.mjs");
4273
4733
  const three = await withProbeTimeout(createWebGpuDriver(opts), probeMs, "initialization", (late) => {
4274
4734
  late.dispose();
4275
4735
  });
4276
4736
  try {
4277
4737
  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");
4738
+ const clouds = await import("./webgpu-clouds-DwSBoV8A.mjs");
4739
+ const snow = await import("./webgpu-snow-cover-CiqYhvPq.mjs");
4279
4740
  return new Renderer(opts, {
4280
4741
  three,
4281
4742
  backend: "webgpu",
4282
4743
  clouds: {
4283
4744
  material: clouds.createWebGpuCloudMaterial,
4284
- installShadows: (uniforms) => clouds.installWebGpuCloudShadows(three, uniforms)
4745
+ installShadows: (uniforms) => clouds.installWebGpuCloudShadows(three, uniforms),
4746
+ installSnowCover: (uniforms) => snow.installWebGpuSnowCover(three, uniforms)
4285
4747
  },
4286
4748
  ...optimizer ? { optimizer } : {},
4287
4749
  ...opts.reflections === true ? { reflectionFilter: (await import("./webgpu-sky-reflections-CymGEes-.mjs")).createWebGpuSkyReflectionFilter(three) } : {}
@@ -4334,8 +4796,17 @@ var Renderer = class Renderer {
4334
4796
  logarithmicDepthBuffer: opts.logarithmicDepthBuffer ?? false
4335
4797
  });
4336
4798
  this.three.setPixelRatio(pixelRatio);
4337
- if (this.cloudBackend) this.cloudBackend.installShadows(this.cloudShadows);
4338
- else this.releaseCloudShadows = installWebGlCloudShadows(this.three, this.cloudShadows);
4799
+ if (this.cloudBackend) {
4800
+ this.cloudBackend.installShadows(this.cloudShadows);
4801
+ this.cloudBackend.installSnowCover(this.snowCover);
4802
+ } else {
4803
+ const far = new FarShadow(this.three);
4804
+ this.farShadow = far;
4805
+ this.releaseCloudShadows = installWebGlCloudShadows(this.three, this.cloudShadows, (shader, material) => {
4806
+ injectFarShadow(shader, far.uniforms);
4807
+ injectSnowCover(shader, this.snowCover, material);
4808
+ });
4809
+ }
4339
4810
  if (this.backend === "webgpu") this.three.onDeviceLost = (info) => {
4340
4811
  if (this.disposed) return;
4341
4812
  this.deviceLossReason = info.message;
@@ -4619,11 +5090,11 @@ var Renderer = class Renderer {
4619
5090
  });
4620
5091
  }
4621
5092
  const instanced = mesh;
4622
- const fresh = [
4623
- ...Object.values(mesh.geometry.attributes).map((a) => a instanceof THREE.InterleavedBufferAttribute ? a.data : a),
5093
+ const fresh = [...new Set([
5094
+ ...Object.values(mesh.geometry.attributes),
4624
5095
  ...mesh.geometry.index ? [mesh.geometry.index] : [],
4625
5096
  ...instanced.isInstancedMesh ? [instanced.instanceMatrix, ...instanced.instanceColor ? [instanced.instanceColor] : []] : []
4626
- ].filter((attribute) => {
5097
+ ].map((a) => a instanceof THREE.InterleavedBufferAttribute ? a.data : a))].filter((attribute) => {
4627
5098
  if (lane.glAttributes.has(attribute)) return false;
4628
5099
  const existing = this.preparedResources.get(attribute);
4629
5100
  if (existing?.version === attribute.version) {
@@ -5025,6 +5496,7 @@ var Renderer = class Renderer {
5025
5496
  weather?.update(this.weatherTimeOverride ?? this.environmentSeconds, this.camera, this.worldOrigin, sky?.frame);
5026
5497
  if (weather) weather.writeShadows(this.cloudShadows, cloudShadowed);
5027
5498
  else this.cloudShadows.molenCloudShadow.value.x = 0;
5499
+ writeSnowCover(this.snowCover, weather?.data.snowCover, this.worldOrigin);
5028
5500
  const shadowMap = this.cloudShadows.molenCloudMap.value;
5029
5501
  if (weather && shadowMap.version !== this.cloudShadowMapVersion) {
5030
5502
  this.cloudShadowMapVersion = shadowMap.version;
@@ -5264,6 +5736,7 @@ var Renderer = class Renderer {
5264
5736
  this.activeWeather?.dispose();
5265
5737
  this.activeWeather = void 0;
5266
5738
  this.releaseCloudShadows?.();
5739
+ this.farShadow?.dispose();
5267
5740
  this.cloudTextures.dispose();
5268
5741
  this.reflections?.dispose();
5269
5742
  this.hideReflectedAmbient(void 0);
@@ -5939,4 +6412,4 @@ function decodeStarCatalog(input) {
5939
6412
  }));
5940
6413
  }
5941
6414
  //#endregion
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 };
6415
+ export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InputMap, InstanceBatch, InstanceMatrixAttribute, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applyLivery, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, isInstanceBatch, isInstanceBatchGeometry, lerp3, liveryGraphicTexture, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };