@bendyline/molen-client 0.0.2 → 0.0.3

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,8 @@
1
1
  import { n as nlerp4, t as lerp3 } from "./math-ev_jEkRe.mjs";
2
2
  import { n as readModelSignals, t as createModelSignalVisual } from "./model-signals-Gw1COJfo.mjs";
3
+ import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-CfbIm1MS.mjs";
3
4
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
4
- import { inputProfileIssues, inputProfileSchema, resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
5
+ import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
5
6
  import * as THREE from "three";
6
7
  import * as SkeletonUtils from "three/addons/utils/SkeletonUtils.js";
7
8
  import { bakeMatGraph, bakePixelGrid, registerMaterialSchemas } from "@bendyline/molen-materials";
@@ -152,14 +153,17 @@ var AdaptiveQualityController = class {
152
153
  this.samples = ordered.length;
153
154
  const memory = this.memorySamples > 0 ? this.memoryTotal / this.memorySamples : 0;
154
155
  const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0);
156
+ const measured = this.cpuSamples > 0 || this.gpuSamples > 0;
155
157
  const loading = this.loading;
156
158
  this.resetWindow();
157
159
  const overloaded = mean > this.targetFrameMs * 1.18 || this.p90FrameMs > this.targetFrameMs * 1.5 && this.slowFrameRatio >= .25;
158
160
  const headroom = !loading && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
159
- this.overloadMs = overloaded ? this.overloadMs + elapsed : 0;
161
+ const renderBound = !loading || !measured || work > this.targetFrameMs * .75;
162
+ this.overloadMs = overloaded && renderBound ? this.overloadMs + elapsed : 0;
160
163
  this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
161
164
  if (this.warmupElapsedMs < this.warmupMs) return;
162
- if (memory > 1 && this.level > this.minLevel) return this.change(this.level - 1, "memory-pressure");
165
+ const memorySettling = loading && this.reason === "memory-pressure" && this.clockMs - this.lastChangeMs < this.increaseDelayMs;
166
+ if (memory > 1 && this.level > this.minLevel && !memorySettling) return this.change(this.level - 1, "memory-pressure");
163
167
  if (this.clockMs - this.lastChangeMs < this.cooldownMs) return;
164
168
  if (overloaded && this.overloadMs >= this.decreaseDelayMs && this.level > this.minLevel) return this.change(this.level - 1, "frame-time");
165
169
  if (headroom && this.headroomMs >= this.increaseDelayMs * this.recoveryMultiplier && this.level < this.maxLevel) return this.change(this.level + 1, "headroom");
@@ -950,328 +954,6 @@ function describeLinkFailure(kind, ev) {
950
954
  return "kernel link error (no detail; the worker may have failed to load)";
951
955
  }
952
956
  //#endregion
953
- //#region src/input.ts
954
- /** Resolve a key or Mouse<button> code to its bound action. */
955
- function resolveAction(bindings, code) {
956
- return Object.hasOwn(bindings, code) ? bindings[code] : void 0;
957
- }
958
- function copyProfile(profile) {
959
- const result = inputProfileSchema.parse(profile);
960
- const issues = inputProfileIssues(result);
961
- if (issues.length) throw new Error(issues[0]?.message);
962
- return result;
963
- }
964
- function matches(device, pad) {
965
- return (device?.id === void 0 || device.id === pad.id) && (device?.index === void 0 || device.index === pad.index);
966
- }
967
- /** Calibrate and shape a raw axis. Invalid/non-finite hardware readings are neutral. */
968
- function normalizeInputAxis(raw, binding) {
969
- if (!Number.isFinite(raw)) return 0;
970
- const min = binding.min ?? -1;
971
- const max = binding.max ?? 1;
972
- const center = binding.center ?? 0;
973
- let value = binding.mode === "unit" ? (raw - min) / (max - min) : raw >= center ? (raw - center) / (max - center) : (raw - center) / (center - min);
974
- value = Math.max(binding.mode === "unit" ? 0 : -1, Math.min(1, value));
975
- if (binding.invert) value = binding.mode === "unit" ? 1 - value : -value;
976
- if (binding.mode === "positive") value = Math.max(0, value);
977
- if (binding.mode === "negative") value = Math.max(0, -value);
978
- const zone = binding.deadZone ?? (binding.mode === "unit" ? 0 : .12);
979
- const magnitude = Math.max(0, (Math.abs(value) - zone) / (1 - zone));
980
- return Math.sign(value) * magnitude ** (binding.curve ?? 1);
981
- }
982
- /**
983
- * Keyboard/mouse + browser controllers mapped to numeric named actions. Call update() each
984
- * frame (applyInputRules does this on its poller). Profiles are complete replacements.
985
- */
986
- var InputMap = class {
987
- base;
988
- profiles = /* @__PURE__ */ new Map();
989
- current;
990
- keys = /* @__PURE__ */ new Set();
991
- blockedKeys = /* @__PURE__ */ new Set();
992
- blockedButtons = /* @__PURE__ */ new Set();
993
- baselineButtons = false;
994
- values = /* @__PURE__ */ new Map();
995
- padValues = /* @__PURE__ */ new Map();
996
- pads = [];
997
- enabled = true;
998
- disposed = false;
999
- focused = true;
1000
- suspensions = 0;
1001
- revision = 0;
1002
- pressHandlers = /* @__PURE__ */ new Map();
1003
- releaseHandlers = /* @__PURE__ */ new Map();
1004
- changeHandlers = /* @__PURE__ */ new Set();
1005
- resetHandlers = /* @__PURE__ */ new Set();
1006
- profileHandlers = /* @__PURE__ */ new Set();
1007
- target;
1008
- provider;
1009
- listeners = [];
1010
- status = "unavailable";
1011
- constructor(opts) {
1012
- this.base = copyProfile({
1013
- bindings: opts.bindings,
1014
- axes: opts.axes,
1015
- buttons: opts.buttons
1016
- });
1017
- for (const [name, profile] of Object.entries(opts.profiles ?? {})) this.profiles.set(name, copyProfile(profile));
1018
- if (opts.profile !== void 0 && !this.profiles.has(opts.profile)) throw new Error(`Unknown input profile "${opts.profile}".`);
1019
- this.current = opts.profile;
1020
- this.target = opts.target;
1021
- this.provider = opts.getGamepads ?? (() => typeof navigator !== "undefined" && typeof navigator.getGamepads === "function" ? navigator.getGamepads() : []);
1022
- if (opts.getGamepads || typeof navigator !== "undefined" && typeof navigator.getGamepads === "function") this.status = "available";
1023
- if (this.target) this.attach(this.target);
1024
- }
1025
- get accepting() {
1026
- return this.enabled && this.focused && this.suspensions === 0;
1027
- }
1028
- get profile() {
1029
- return this.current === void 0 ? this.base : this.profiles.get(this.current);
1030
- }
1031
- get activeProfile() {
1032
- return this.current;
1033
- }
1034
- get gamepadStatus() {
1035
- return this.status;
1036
- }
1037
- profileNames() {
1038
- return [...this.profiles.keys()];
1039
- }
1040
- /** Detached, serializable copy for custom editors and host-managed persistence. */
1041
- getProfile(...selection) {
1042
- const name = selection.length === 0 ? this.current : selection[0];
1043
- const profile = name === void 0 ? this.base : this.profiles.get(name);
1044
- if (!profile) throw new Error(`Unknown input profile "${name}".`);
1045
- return copyProfile(profile);
1046
- }
1047
- /** Atomically validate and replace bindings; no held button becomes a new action. */
1048
- defineProfile(name, profile) {
1049
- const next = copyProfile(profile);
1050
- if (name === "") throw new Error("Profile names must not be empty.");
1051
- if (name === void 0) this.base = next;
1052
- else this.profiles.set(name, next);
1053
- if (name === this.current) this.reset();
1054
- for (const fn of this.profileHandlers) fn();
1055
- }
1056
- /** Undefined selects the root bindings. Held keys/buttons must be released before reuse. */
1057
- setProfile(name) {
1058
- if (name !== void 0 && !this.profiles.has(name)) throw new Error(`Unknown input profile "${name}".`);
1059
- if (name === this.current) return;
1060
- this.current = name;
1061
- this.reset();
1062
- for (const fn of this.profileHandlers) fn();
1063
- }
1064
- /** Snapshot of all detected devices and raw values, suitable for an axis/button inspector. */
1065
- devices() {
1066
- return this.pads.map((pad) => ({
1067
- ...pad,
1068
- axes: [...pad.axes],
1069
- buttons: pad.buttons.map((button) => ({ ...button }))
1070
- }));
1071
- }
1072
- /** Poll fresh browser objects; unplugging or losing permission releases affected controls. */
1073
- update() {
1074
- if (this.disposed) return;
1075
- try {
1076
- this.pads = this.provider().filter((pad) => pad?.connected === true).map((pad) => ({
1077
- id: pad.id,
1078
- index: pad.index,
1079
- connected: pad.connected,
1080
- mapping: pad.mapping,
1081
- axes: Array.from(pad.axes),
1082
- buttons: Array.from(pad.buttons, (button) => ({
1083
- pressed: button.pressed,
1084
- value: button.value
1085
- }))
1086
- }));
1087
- if (this.status === "blocked") this.status = "available";
1088
- } catch {
1089
- this.pads = [];
1090
- this.status = "blocked";
1091
- }
1092
- const down = /* @__PURE__ */ new Set();
1093
- for (const pad of this.pads) pad.buttons.forEach((button, index) => {
1094
- if (button.pressed || button.value > 0) down.add(JSON.stringify([
1095
- pad.id,
1096
- pad.index,
1097
- index
1098
- ]));
1099
- });
1100
- if (this.baselineButtons || !this.accepting) for (const key of down) this.blockedButtons.add(key);
1101
- for (const key of this.blockedButtons) if (!down.has(key)) this.blockedButtons.delete(key);
1102
- this.baselineButtons = false;
1103
- this.padValues.clear();
1104
- if (this.accepting) for (const pad of this.pads) {
1105
- for (const binding of this.profile.axes ?? []) {
1106
- const raw = pad.axes[binding.axis];
1107
- if (matches(binding.device, pad) && raw !== void 0) this.contribute(this.padValues, binding.action, normalizeInputAxis(raw, binding));
1108
- }
1109
- for (const binding of this.profile.buttons ?? []) {
1110
- const button = pad.buttons[binding.button];
1111
- const key = JSON.stringify([
1112
- pad.id,
1113
- pad.index,
1114
- binding.button
1115
- ]);
1116
- if (matches(binding.device, pad) && button && !this.blockedButtons.has(key) && (button.value >= (binding.threshold ?? .5) || binding.threshold === void 0 && button.pressed)) this.contribute(this.padValues, binding.action, 1);
1117
- }
1118
- }
1119
- this.recompute();
1120
- }
1121
- /** Suspend while editing a form/menu; device discovery continues during update(). */
1122
- setEnabled(enabled) {
1123
- if (this.enabled === enabled) return;
1124
- this.enabled = enabled;
1125
- this.reset();
1126
- }
1127
- /** Temporarily suppress gameplay while a remapping UI is open; returned release is idempotent. */
1128
- suspend() {
1129
- this.suspensions++;
1130
- this.reset();
1131
- let released = false;
1132
- return () => {
1133
- if (released) return;
1134
- released = true;
1135
- this.suspensions--;
1136
- this.reset();
1137
- };
1138
- }
1139
- attach(target) {
1140
- const editable = (ev) => {
1141
- return !!ev.target?.closest?.("input, textarea, select, button, [contenteditable]:not([contenteditable=\"false\"]), [data-molen-input-editor]");
1142
- };
1143
- const add = (type, fn) => {
1144
- target.addEventListener(type, fn);
1145
- this.listeners.push([type, fn]);
1146
- };
1147
- add("keydown", (ev) => {
1148
- if (!editable(ev)) this.press(ev.code);
1149
- });
1150
- add("keyup", (ev) => this.release(ev.code));
1151
- add("mousedown", (ev) => {
1152
- if (!editable(ev)) this.press(`Mouse${ev.button}`);
1153
- });
1154
- add("mouseup", (ev) => this.release(`Mouse${ev.button}`));
1155
- add("blur", () => {
1156
- this.focused = false;
1157
- this.reset();
1158
- });
1159
- add("focus", () => {
1160
- this.focused = true;
1161
- this.blockedKeys.clear();
1162
- });
1163
- }
1164
- press(code) {
1165
- if (this.disposed || !this.accepting || this.blockedKeys.has(code) || this.keys.has(code)) return;
1166
- this.keys.add(code);
1167
- this.recompute();
1168
- }
1169
- release(code) {
1170
- this.blockedKeys.delete(code);
1171
- if (this.keys.delete(code)) this.recompute();
1172
- }
1173
- /** Numeric action value; strongest absolute contribution wins, keyboard wins ties. */
1174
- value(action) {
1175
- return this.values.get(action) ?? 0;
1176
- }
1177
- isActive(action) {
1178
- return this.value(action) !== 0;
1179
- }
1180
- activeActions() {
1181
- return new Set(this.values.keys());
1182
- }
1183
- contribute(values, action, value) {
1184
- if (Number.isFinite(value) && Math.abs(value) > Math.abs(values.get(action) ?? 0)) values.set(action, value);
1185
- }
1186
- recompute() {
1187
- const next = /* @__PURE__ */ new Map();
1188
- if (this.accepting) {
1189
- for (const code of this.keys) {
1190
- const action = resolveAction(this.profile.bindings, code);
1191
- if (action !== void 0) this.contribute(next, action, 1);
1192
- }
1193
- for (const [action, value] of this.padValues) this.contribute(next, action, value);
1194
- }
1195
- this.commit(next);
1196
- }
1197
- commit(next) {
1198
- const prev = this.values;
1199
- this.values = next;
1200
- const revision = ++this.revision;
1201
- for (const action of new Set([...prev.keys(), ...next.keys()])) {
1202
- const before = prev.get(action) ?? 0;
1203
- const after = next.get(action) ?? 0;
1204
- const handlers = before === 0 && after !== 0 ? this.pressHandlers : before !== 0 && after === 0 ? this.releaseHandlers : void 0;
1205
- for (const fn of handlers?.get(action) ?? []) {
1206
- if (this.revision !== revision) return;
1207
- fn(action);
1208
- }
1209
- }
1210
- if (this.revision !== revision) return;
1211
- if ([...new Set([...prev.keys(), ...next.keys()])].some((action) => prev.get(action) !== next.get(action))) for (const fn of this.changeHandlers) fn();
1212
- }
1213
- /** Release actions immediately; suppress held physical buttons until released. */
1214
- reset() {
1215
- for (const key of this.keys) this.blockedKeys.add(key);
1216
- this.keys.clear();
1217
- this.padValues.clear();
1218
- this.baselineButtons = true;
1219
- this.commit(/* @__PURE__ */ new Map());
1220
- for (const fn of this.resetHandlers) fn();
1221
- }
1222
- subscribe(map, action, handler) {
1223
- let set = map.get(action);
1224
- if (!set) {
1225
- set = /* @__PURE__ */ new Set();
1226
- map.set(action, set);
1227
- }
1228
- set.add(handler);
1229
- return () => {
1230
- set.delete(handler);
1231
- };
1232
- }
1233
- onPress(action, handler) {
1234
- return this.subscribe(this.pressHandlers, action, handler);
1235
- }
1236
- onRelease(action, handler) {
1237
- return this.subscribe(this.releaseHandlers, action, handler);
1238
- }
1239
- /** Action values changed (including neutralization on reset/profile switch). */
1240
- onChange(handler) {
1241
- this.changeHandlers.add(handler);
1242
- return () => {
1243
- this.changeHandlers.delete(handler);
1244
- };
1245
- }
1246
- /** Explicit neutralization on reset, focus loss, suspension or profile replacement. */
1247
- onReset(handler) {
1248
- this.resetHandlers.add(handler);
1249
- return () => {
1250
- this.resetHandlers.delete(handler);
1251
- };
1252
- }
1253
- /** Profile selection or definitions changed. */
1254
- onProfilesChanged(handler) {
1255
- this.profileHandlers.add(handler);
1256
- return () => {
1257
- this.profileHandlers.delete(handler);
1258
- };
1259
- }
1260
- dispose() {
1261
- if (this.disposed) return;
1262
- this.disposed = true;
1263
- if (this.target) for (const [type, fn] of this.listeners) this.target.removeEventListener(type, fn);
1264
- this.listeners.length = 0;
1265
- this.reset();
1266
- this.pressHandlers.clear();
1267
- this.releaseHandlers.clear();
1268
- this.changeHandlers.clear();
1269
- this.resetHandlers.clear();
1270
- this.profileHandlers.clear();
1271
- this.pads = [];
1272
- }
1273
- };
1274
- //#endregion
1275
957
  //#region src/scene-bindings.ts
1276
958
  /**
1277
959
  * Apply a scene's `camera` block. `fixed` and `free-fly` pose the perspective camera (free-fly
@@ -1398,6 +1080,13 @@ const defaultEnvironment = {
1398
1080
  }
1399
1081
  };
1400
1082
  const RIG_NAME = "$environment";
1083
+ /**
1084
+ * The environment rig, always a direct child of the scene. `getObjectByName` would search the
1085
+ * world graph first (every resident tile, hidden or not) before reaching it.
1086
+ */
1087
+ function findEnvironmentRig(scene) {
1088
+ return scene.children.find((child) => child.name === RIG_NAME);
1089
+ }
1401
1090
  const SHADOW_MAP_SIZE = {
1402
1091
  low: 1024,
1403
1092
  medium: 2048,
@@ -1411,7 +1100,7 @@ const SHADOW_MAP_SIZE = {
1411
1100
  function applyEnvironment(renderer, env) {
1412
1101
  renderer.setSky(env.sky, env.shadows ?? "off");
1413
1102
  const scene = renderer.scene;
1414
- const existing = scene.getObjectByName(RIG_NAME);
1103
+ const existing = findEnvironmentRig(scene);
1415
1104
  if (existing !== void 0) {
1416
1105
  existing.traverse((object) => {
1417
1106
  if (object.isLight) object.dispose();
@@ -1457,6 +1146,15 @@ function applyEnvironment(renderer, env) {
1457
1146
  //#endregion
1458
1147
  //#region src/three/materials.ts
1459
1148
  registerMaterialSchemas();
1149
+ function validateImage(image) {
1150
+ if (!Number.isSafeInteger(image.width) || image.width < 1 || !Number.isSafeInteger(image.height) || image.height < 1 || !Number.isSafeInteger(image.width * image.height * 4) || image.data.length !== image.width * image.height * 4) throw new Error("Invalid baked material image: expected positive dimensions and matching RGBA8 data");
1151
+ }
1152
+ /** StandardMaterial samples roughness from G and metalness from B, as linear UNORM8. */
1153
+ function uniformChannel(image, channel) {
1154
+ const value = image.data[channel];
1155
+ for (let i = channel + 4; i < image.data.length; i += 4) if (image.data[i] !== value) return void 0;
1156
+ return value / 255;
1157
+ }
1460
1158
  function textureFrom(image, filter, srgb) {
1461
1159
  const tex = new THREE.DataTexture(new Uint8Array(image.data.buffer.slice(0)), image.width, image.height, THREE.RGBAFormat);
1462
1160
  tex.flipY = false;
@@ -1468,6 +1166,7 @@ function textureFrom(image, filter, srgb) {
1468
1166
  }
1469
1167
  /** Upload a BakedMaterial's slots onto a MeshStandardMaterial. */
1470
1168
  function materialFromBaked(baked) {
1169
+ for (const image of Object.values(baked.slots)) if (image !== void 0) validateImage(image);
1471
1170
  const material = new THREE.MeshStandardMaterial({
1472
1171
  roughness: 1,
1473
1172
  metalness: 1
@@ -1478,9 +1177,16 @@ function materialFromBaked(baked) {
1478
1177
  material.roughness = .6;
1479
1178
  material.metalness = 0;
1480
1179
  }
1481
- if (baked.slots.roughness !== void 0) material.roughnessMap = textureFrom(baked.slots.roughness, filter, false);
1482
- if (baked.slots.metalness !== void 0) material.metalnessMap = textureFrom(baked.slots.metalness, filter, false);
1483
- else if (baked.slots.baseColor !== void 0) material.metalness = 0;
1180
+ if (baked.slots.roughness !== void 0) {
1181
+ const value = uniformChannel(baked.slots.roughness, 1);
1182
+ if (value === void 0) material.roughnessMap = textureFrom(baked.slots.roughness, filter, false);
1183
+ else material.roughness *= value;
1184
+ }
1185
+ if (baked.slots.metalness !== void 0) {
1186
+ const value = uniformChannel(baked.slots.metalness, 2);
1187
+ if (value === void 0) material.metalnessMap = textureFrom(baked.slots.metalness, filter, false);
1188
+ else material.metalness *= value;
1189
+ } else if (baked.slots.baseColor !== void 0) material.metalness = 0;
1484
1190
  if (baked.slots.normal !== void 0) material.normalMap = textureFrom(baked.slots.normal, filter, false);
1485
1191
  if (baked.slots.emissive !== void 0) {
1486
1192
  material.emissiveMap = textureFrom(baked.slots.emissive, filter, true);
@@ -2446,6 +2152,8 @@ function createGltfLoader(renderer, config = {}) {
2446
2152
  var FrameAdmissionQueue = class {
2447
2153
  options;
2448
2154
  jobs = [];
2155
+ background = [];
2156
+ queuedBackground = /* @__PURE__ */ new WeakMap();
2449
2157
  scheduled = false;
2450
2158
  disposed = false;
2451
2159
  clock;
@@ -2472,8 +2180,9 @@ var FrameAdmissionQueue = class {
2472
2180
  run(task, options = {}) {
2473
2181
  if (this.disposed || options.signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
2474
2182
  if (!Number.isFinite(options.bytes ?? 0) || (options.bytes ?? 0) < 0) return Promise.reject(/* @__PURE__ */ new RangeError("Admission bytes must be finite and nonnegative"));
2475
- return new Promise((resolve, reject) => {
2476
- const job = {
2183
+ let job;
2184
+ const promise = new Promise((resolve, reject) => {
2185
+ job = {
2477
2186
  run: task,
2478
2187
  resolve: (value) => resolve(value),
2479
2188
  reject,
@@ -2481,22 +2190,52 @@ var FrameAdmissionQueue = class {
2481
2190
  queued: this.clock()
2482
2191
  };
2483
2192
  job.abort = () => {
2484
- const index = this.jobs.indexOf(job);
2193
+ const lane = this.jobs.includes(job) ? this.jobs : this.background;
2194
+ const index = lane.indexOf(job);
2485
2195
  if (index >= 0) {
2486
- this.jobs.splice(index, 1);
2196
+ lane.splice(index, 1);
2197
+ this.forget(job);
2487
2198
  reject(new DOMException("Admission cancelled", "AbortError"));
2488
2199
  }
2489
2200
  };
2490
2201
  options.signal?.addEventListener("abort", job.abort, { once: true });
2491
- this.jobs.push(job);
2202
+ (options.priority === "background" ? this.background : this.jobs).push(job);
2492
2203
  this.request();
2493
2204
  });
2205
+ if (options.priority === "background") {
2206
+ job.promise = promise;
2207
+ this.queuedBackground.set(promise, job);
2208
+ }
2209
+ return promise;
2210
+ }
2211
+ /**
2212
+ * Callers keep the promise (preparation caches do, keyed by long-lived resources); the job holds
2213
+ * the task and everything it captured. Only a queued job may stay reachable from its promise.
2214
+ */
2215
+ forget(job) {
2216
+ if (job.promise === void 0) return;
2217
+ this.queuedBackground.delete(job.promise);
2218
+ job.promise = void 0;
2219
+ }
2220
+ /** Move a still-queued background job to the normal lane, behind the jobs already there. */
2221
+ promote(promise) {
2222
+ const job = this.queuedBackground.get(promise);
2223
+ const index = job === void 0 ? -1 : this.background.indexOf(job);
2224
+ if (job === void 0 || index < 0) return;
2225
+ this.forget(job);
2226
+ this.background.splice(index, 1);
2227
+ job.options = {
2228
+ ...job.options,
2229
+ priority: "normal"
2230
+ };
2231
+ this.jobs.push(job);
2232
+ this.request();
2494
2233
  }
2495
2234
  get pending() {
2496
- return this.jobs.length;
2235
+ return this.jobs.length + this.background.length;
2497
2236
  }
2498
2237
  request() {
2499
- if (this.scheduled || this.disposed || this.jobs.length === 0) return;
2238
+ if (this.scheduled || this.disposed || this.pending === 0) return;
2500
2239
  this.scheduled = true;
2501
2240
  this.schedule(() => {
2502
2241
  this.scheduled = false;
@@ -2508,11 +2247,14 @@ var FrameAdmissionQueue = class {
2508
2247
  if (this.disposed) return;
2509
2248
  const start = this.clock();
2510
2249
  let bytes = 0, count = 0;
2511
- while (this.jobs.length > 0) {
2512
- const next = this.jobs[0];
2250
+ for (;;) {
2251
+ const lane = this.jobs.length > 0 ? this.jobs : this.background;
2252
+ const next = lane[0];
2253
+ if (next === void 0) break;
2513
2254
  const cost = next.options.bytes ?? 0;
2514
2255
  if (count > 0 && (count >= this.maxJobs || this.clock() - start >= this.maxMs || bytes + cost > this.maxBytes)) break;
2515
- this.jobs.shift();
2256
+ lane.shift();
2257
+ this.forget(next);
2516
2258
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
2517
2259
  if (next.options.signal?.aborted) {
2518
2260
  next.reject(new DOMException("Admission cancelled", "AbortError"));
@@ -2532,18 +2274,20 @@ var FrameAdmissionQueue = class {
2532
2274
  queueMs: began - next.queued,
2533
2275
  workMs,
2534
2276
  bytes: cost,
2535
- overBudget: workMs > this.maxMs || cost > this.maxBytes
2277
+ overBudget: workMs > this.maxMs || cost > this.maxBytes,
2278
+ background: next.options.priority === "background"
2536
2279
  });
2537
2280
  }
2538
2281
  this.request();
2539
2282
  }
2540
2283
  dispose() {
2541
2284
  this.disposed = true;
2542
- for (const job of this.jobs) {
2285
+ for (const job of [...this.jobs, ...this.background]) {
2543
2286
  if (job.abort) job.options.signal?.removeEventListener("abort", job.abort);
2544
2287
  job.reject(new DOMException("Admission queue disposed", "AbortError"));
2545
2288
  }
2546
2289
  this.jobs = [];
2290
+ this.background = [];
2547
2291
  }
2548
2292
  };
2549
2293
  //#endregion
@@ -2749,9 +2493,14 @@ function starDirection(rightAscensionDeg, declinationDeg, state) {
2749
2493
  //#endregion
2750
2494
  //#region src/sky/visual.ts
2751
2495
  const RAD$1 = Math.PI / 180;
2752
- const clamp$2 = (x) => Math.max(0, Math.min(1, x));
2753
- function smooth$1(a, b, x) {
2754
- const t = clamp$2((x - a) / (b - a));
2496
+ const clamp$3 = (x) => Math.max(0, Math.min(1, x));
2497
+ const rgb$1 = (color) => [
2498
+ color.r,
2499
+ color.g,
2500
+ color.b
2501
+ ];
2502
+ function smooth$2(a, b, x) {
2503
+ const t = clamp$3((x - a) / (b - a));
2755
2504
  return t * t * (3 - 2 * t);
2756
2505
  }
2757
2506
  const defaultSkyPalette = {
@@ -2789,7 +2538,7 @@ function starGeometry(count) {
2789
2538
  }
2790
2539
  /** Star colour from its B−V colour index. */
2791
2540
  function starColor(bv) {
2792
- return new THREE.Color("#b6d1ff").lerp(new THREE.Color("#fff4e8"), smooth$1(-.3, .5, bv)).lerp(new THREE.Color("#ffb46c"), smooth$1(.5, 1.8, bv));
2541
+ return new THREE.Color("#b6d1ff").lerp(new THREE.Color("#fff4e8"), smooth$2(-.3, .5, bv)).lerp(new THREE.Color("#ffb46c"), smooth$2(.5, 1.8, bv));
2793
2542
  }
2794
2543
  /**
2795
2544
  * Generic clear-sky dome, celestial spheres, batched stars and lighting, using standard
@@ -2813,6 +2562,7 @@ var SkyVisual = class {
2813
2562
  lastTime;
2814
2563
  cloudAttenuation = 0;
2815
2564
  currentFrame;
2565
+ currentReflections;
2816
2566
  disposed = false;
2817
2567
  constructor(data, options = {}) {
2818
2568
  this.data = skySchema.parse(data);
@@ -2859,9 +2609,13 @@ var SkyVisual = class {
2859
2609
  get frame() {
2860
2610
  return this.currentFrame;
2861
2611
  }
2612
+ /** Sky radiance for the viewer's shared PBR environment, sampled with the celestial frame. */
2613
+ get reflectionState() {
2614
+ return this.currentReflections;
2615
+ }
2862
2616
  /** Diffuse cloud lighting; actual celestial occlusion comes from the cloud layer geometry. */
2863
2617
  setCloudAttenuation(value) {
2864
- const next = clamp$2(value);
2618
+ const next = clamp$3(value);
2865
2619
  if (next === this.cloudAttenuation) return;
2866
2620
  this.cloudAttenuation = next;
2867
2621
  this.lastTime = void 0;
@@ -2896,8 +2650,8 @@ var SkyVisual = class {
2896
2650
  const moonVector = moonDirection ? new THREE.Vector3(...moonDirection) : void 0;
2897
2651
  const moonIllumination = earth?.moon.illuminatedFraction ?? (moonVector ? (1 - moonVector.dot(sunVector)) / 2 : 0);
2898
2652
  const altitude = Math.asin(sunDirection[1]) / RAD$1;
2899
- const daylight = smooth$1(-12, 8, altitude);
2900
- const starVisibility = (1 - smooth$1(-18, -4, altitude)) * (1 - .65 * moonIllumination * smooth$1(0, .5, moonDirection?.[1] ?? -1));
2653
+ const daylight = smooth$2(-12, 8, altitude);
2654
+ const starVisibility = (1 - smooth$2(-18, -4, altitude)) * (1 - .65 * moonIllumination * smooth$2(0, .5, moonDirection?.[1] ?? -1));
2901
2655
  const sunDiameterDeg = earth?.sun.angularDiameterDeg ?? (data.mode === "custom" ? data.sunBody.angularDiameterDeg ?? .53 : .53);
2902
2656
  const moonDiameterDeg = earth?.moon.angularDiameterDeg ?? (data.mode === "custom" ? data.moonBody?.angularDiameterDeg ?? .53 : .53);
2903
2657
  this.currentFrame = {
@@ -2924,10 +2678,10 @@ var SkyVisual = class {
2924
2678
  ]).map((v) => v * RAD$1)));
2925
2679
  this.updateStars(rotation, starVisibility, moonVector, moonDiameterDeg * (data.moon?.size ?? 1));
2926
2680
  const light = data.lighting;
2927
- this.sunLight.color.copy(this.palette.sun).lerp(this.palette.twilight, 1 - smooth$1(0, 18, altitude));
2928
- this.sunLight.intensity = (light?.sunIntensity ?? 3) * smooth$1(-.8, 8, altitude);
2681
+ this.sunLight.color.copy(this.palette.sun).lerp(this.palette.twilight, 1 - smooth$2(0, 18, altitude));
2682
+ this.sunLight.intensity = (light?.sunIntensity ?? 3) * smooth$2(-.8, 8, altitude);
2929
2683
  this.moonLight.color.copy(this.palette.moon);
2930
- this.moonLight.intensity = (light?.moonIntensity ?? .12) * moonIllumination * smooth$1(0, .2, moonDirection?.[1] ?? -1) * (1 - daylight);
2684
+ this.moonLight.intensity = (light?.moonIntensity ?? .12) * moonIllumination * smooth$2(0, .2, moonDirection?.[1] ?? -1) * (1 - daylight);
2931
2685
  this.ambientLight.color.copy(this.palette.nightHorizon).lerp(this.palette.dayHorizon, daylight);
2932
2686
  this.ambientLight.groundColor.copy(this.palette.ground);
2933
2687
  this.ambientLight.intensity = (light?.nightAmbient ?? .025) * (1 - daylight) + (light?.dayAmbient ?? .6) * daylight;
@@ -2935,6 +2689,17 @@ var SkyVisual = class {
2935
2689
  this.moonLight.intensity *= 1 - this.cloudAttenuation * .9;
2936
2690
  this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
2937
2691
  this.ambientLight.color.lerp(new THREE.Color("#b9c2cb"), this.cloudAttenuation * daylight * .6);
2692
+ this.currentReflections = {
2693
+ zenith: rgb$1(this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight)),
2694
+ horizon: rgb$1(this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight)),
2695
+ ground: rgb$1(this.palette.ground.clone().multiplyScalar(.08 + daylight * .92)),
2696
+ twilight: rgb$1(this.palette.twilight),
2697
+ twilightStrength: smooth$2(-18, -4, altitude) * (1 - smooth$2(0, 16, altitude)),
2698
+ sunDirection,
2699
+ sunColor: rgb$1(this.palette.sun),
2700
+ sunGlow: smooth$2(-2, 5, altitude) * .22,
2701
+ clouds: this.cloudAttenuation
2702
+ };
2938
2703
  return this.currentFrame;
2939
2704
  }
2940
2705
  /** Copy view orientation/projection only; celestial bodies never translate with the camera. */
@@ -2974,16 +2739,16 @@ var SkyVisual = class {
2974
2739
  const positions = this.dome.geometry.getAttribute("position");
2975
2740
  const horizon = this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight);
2976
2741
  const zenith = this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight);
2977
- const twilight = smooth$1(-18, -4, altitude) * (1 - smooth$1(0, 16, altitude));
2742
+ const twilight = smooth$2(-18, -4, altitude) * (1 - smooth$2(0, 16, altitude));
2978
2743
  const color = new THREE.Color();
2979
2744
  const dir = new THREE.Vector3();
2980
2745
  for (let i = 0; i < positions.count; i++) {
2981
2746
  dir.fromBufferAttribute(positions, i).normalize();
2982
- color.copy(horizon).lerp(zenith, clamp$2(dir.y) ** .45);
2983
- const nearSun = clamp$2((dir.dot(sun) + 1) / 2) ** 8;
2747
+ color.copy(horizon).lerp(zenith, clamp$3(dir.y) ** .45);
2748
+ const nearSun = clamp$3((dir.dot(sun) + 1) / 2) ** 8;
2984
2749
  color.lerp(this.palette.twilight, twilight * Math.exp(-Math.abs(dir.y) * 7) * (.25 + .7 * nearSun));
2985
- if (dir.y < 0) color.lerp(this.palette.ground.clone().multiplyScalar(.08 + daylight * .92), smooth$1(0, .2, -dir.y));
2986
- const glow = clamp$2(dir.dot(sun)) ** 96 * smooth$1(-2, 5, altitude) * .22;
2750
+ if (dir.y < 0) color.lerp(this.palette.ground.clone().multiplyScalar(.08 + daylight * .92), smooth$2(0, .2, -dir.y));
2751
+ const glow = clamp$3(dir.dot(sun)) ** 96 * smooth$2(-2, 5, altitude) * .22;
2987
2752
  color.lerp(this.palette.sun, glow);
2988
2753
  colors.setXYZW(i, color.r, color.g, color.b, 1);
2989
2754
  }
@@ -2996,13 +2761,13 @@ var SkyVisual = class {
2996
2761
  body.visible = direction.y + radius > 0;
2997
2762
  const positions = body.geometry.getAttribute("position");
2998
2763
  const colors = body.geometry.getAttribute("color");
2999
- const base = lunar ? this.palette.moon : this.palette.sun.clone().lerp(this.palette.twilight, 1 - smooth$1(0, .2, direction.y));
2764
+ const base = lunar ? this.palette.moon : this.palette.sun.clone().lerp(this.palette.twilight, 1 - smooth$2(0, .2, direction.y));
3000
2765
  const normal = new THREE.Vector3();
3001
2766
  for (let i = 0; i < positions.count; i++) {
3002
2767
  normal.fromBufferAttribute(positions, i).normalize();
3003
2768
  const illumination = lunar ? (this.data.moon?.earthshine ?? .025) + Math.max(0, normal.dot(sun)) * .975 : 2.5;
3004
2769
  const albedo = lunar ? .85 + .15 * Math.sin(normal.x * 27 + Math.sin(normal.y * 19) * 2) * Math.sin(normal.z * 21) : 1;
3005
- colors.setXYZW(i, base.r * illumination * albedo, base.g * illumination * albedo, base.b * illumination * albedo, smooth$1(-3e-4, 3e-4, direction.y + normal.y * radius));
2770
+ 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));
3006
2771
  }
3007
2772
  colors.needsUpdate = true;
3008
2773
  body.material.side = THREE.FrontSide;
@@ -3045,7 +2810,7 @@ var SkyVisual = class {
3045
2810
  right.crossVectors(Math.abs(d.y) > .99 ? new THREE.Vector3(1, 0, 0) : pole, d).normalize();
3046
2811
  up.crossVectors(d, right);
3047
2812
  const size = (8e-4 + 45e-5 * Math.max(0, 6 - star.magnitude)) * (this.data.stars?.size ?? 1);
3048
- const alpha = moon && this.data.moon?.visible !== false && d.dot(moon) > Math.cos(Math.min(170, moonDiameter) * RAD$1 / 2) ? 0 : visibility * smooth$1(0, .06, d.y) * (this.data.stars?.intensity ?? 1);
2813
+ const alpha = moon && this.data.moon?.visible !== false && d.dot(moon) > Math.cos(Math.min(170, moonDiameter) * RAD$1 / 2) ? 0 : visibility * smooth$2(0, .06, d.y) * (this.data.stars?.intensity ?? 1);
3049
2814
  const brightness = Math.min(3, 10 ** (-.2 * (star.magnitude - 2)));
3050
2815
  for (let j = 0; j < 7; j++) {
3051
2816
  p.copy(d);
@@ -3081,10 +2846,10 @@ var SkyVisual = class {
3081
2846
  };
3082
2847
  //#endregion
3083
2848
  //#region src/weather/visual.ts
3084
- const clamp$1 = (x) => Math.max(0, Math.min(1, x));
2849
+ const clamp$2 = (x) => Math.max(0, Math.min(1, x));
3085
2850
  const wrap = (x, size) => (x % size + size) % size;
3086
- function smooth(a, b, x) {
3087
- const t = clamp$1((x - a) / (b - a));
2851
+ function smooth$1(a, b, x) {
2852
+ const t = clamp$2((x - a) / (b - a));
3088
2853
  return t * t * (3 - 2 * t);
3089
2854
  }
3090
2855
  function hash(x, y, seed) {
@@ -3094,7 +2859,7 @@ function hash(x, y, seed) {
3094
2859
  }
3095
2860
  function noise(x, y, period, seed) {
3096
2861
  const ix = Math.floor(x), iy = Math.floor(y);
3097
- const fx = smooth(0, 1, x - ix), fy = smooth(0, 1, y - iy);
2862
+ const fx = smooth$1(0, 1, x - ix), fy = smooth$1(0, 1, y - iy);
3098
2863
  const a = hash(wrap(ix, period), wrap(iy, period), seed);
3099
2864
  const b = hash(wrap(ix + 1, period), wrap(iy, period), seed);
3100
2865
  const c = hash(wrap(ix, period), wrap(iy + 1, period), seed);
@@ -3194,7 +2959,7 @@ var WeatherVisual = class {
3194
2959
  1,
3195
2960
  1,
3196
2961
  1,
3197
- 1 - smooth(.6, 1, r)
2962
+ 1 - smooth$1(.6, 1, r)
3198
2963
  ], j * 4);
3199
2964
  }
3200
2965
  geometry.setAttribute("color", new THREE.BufferAttribute(colors, 4));
@@ -3244,8 +3009,8 @@ var WeatherVisual = class {
3244
3009
  const i = y * CLOUD_RESOLUTION + x, n = field[i] ?? 0;
3245
3010
  const dx = (field[y * CLOUD_RESOLUTION + (x + 1) % CLOUD_RESOLUTION] ?? n) - n;
3246
3011
  const dz = (field[(y + 1) % CLOUD_RESOLUTION * CLOUD_RESOLUTION + x] ?? n) - n;
3247
- const shade = clamp$1(.56 + (1 - smooth(threshold, threshold + .25, n)) * .3 + (dx * sun[0] + dz * sun[2]) * 4 - clouds.density * .15);
3248
- const alpha = smooth(threshold - .075, threshold + .075, n) * (1 - Math.exp(-clouds.density * 6));
3012
+ const shade = clamp$2(.56 + (1 - smooth$1(threshold, threshold + .25, n)) * .3 + (dx * sun[0] + dz * sun[2]) * 4 - clouds.density * .15);
3013
+ const alpha = smooth$1(threshold - .075, threshold + .075, n) * (1 - Math.exp(-clouds.density * 6));
3249
3014
  pixels.set([
3250
3015
  shade * 255,
3251
3016
  shade * 255,
@@ -3259,7 +3024,7 @@ var WeatherVisual = class {
3259
3024
  const size = Math.max(2e3, Math.min(16e4, far * 1.4));
3260
3025
  const absoluteX = this.cameraPosition.x + origin[0], absoluteZ = this.cameraPosition.z + origin[2];
3261
3026
  this.color.set("#101829").lerp(new THREE.Color("#e4e9ee"), daylight);
3262
- const sunset = (1 - smooth(0, .3, Math.abs(sun[1]))) * smooth(-.15, .05, sun[1]);
3027
+ const sunset = (1 - smooth$1(0, .3, Math.abs(sun[1]))) * smooth$1(-.15, .05, sun[1]);
3263
3028
  this.color.lerp(new THREE.Color("#f6b88d"), sunset * .55);
3264
3029
  this.color.multiplyScalar(1 + daylight * 1.8);
3265
3030
  for (const [i, layer] of this.cloudLayers.entries()) {
@@ -3300,7 +3065,7 @@ var WeatherVisual = class {
3300
3065
  255,
3301
3066
  255,
3302
3067
  255,
3303
- (1 - smooth(.15, 1, r)) * 255
3068
+ (1 - smooth$1(.15, 1, r)) * 255
3304
3069
  ], (y * 32 + x) * 4);
3305
3070
  }
3306
3071
  this.particleTexture = new THREE.DataTexture(pixels, 32, 32);
@@ -3489,6 +3254,155 @@ function createGpuFrameTimer(context, options = {}) {
3489
3254
  };
3490
3255
  }
3491
3256
  //#endregion
3257
+ //#region src/three/sky-reflections.ts
3258
+ const WIDTH = 256;
3259
+ const HEIGHT = 128;
3260
+ const clamp$1 = (v) => Math.max(0, Math.min(1, v));
3261
+ const rgb = (color) => [
3262
+ color.r,
3263
+ color.g,
3264
+ color.b
3265
+ ];
3266
+ const smooth = (v) => {
3267
+ const t = clamp$1(v);
3268
+ return t * t * (3 - 2 * t);
3269
+ };
3270
+ /** Match the clear-sky palette, then replace directional colour with diffuse cloud radiance. */
3271
+ function sampleSkyReflection(state, x, y, z, out) {
3272
+ const dot = x * state.sunDirection[0] + y * state.sunDirection[1] + z * state.sunDirection[2];
3273
+ const sky = clamp$1(y) ** .45;
3274
+ const sunset = state.twilightStrength * Math.exp(-Math.abs(y) * 7) * (.25 + .7 * clamp$1((dot + 1) / 2) ** 8);
3275
+ const ground = y < 0 ? smooth(-y / .2) : 0;
3276
+ const glow = clamp$1(dot) ** 96 * state.sunGlow;
3277
+ const cloud = clamp$1(state.clouds) * (1 - ground);
3278
+ const grey = (state.horizon[0] * .2126 + state.horizon[1] * .7152 + state.horizon[2] * .0722) * (.8 + .2 * sky);
3279
+ const channel = (i) => {
3280
+ let v = state.horizon[i] + (state.zenith[i] - state.horizon[i]) * sky;
3281
+ v += (state.twilight[i] - v) * sunset;
3282
+ v += (state.ground[i] - v) * ground;
3283
+ v += (state.sunColor[i] - v) * glow * (1 - ground);
3284
+ return Math.max(0, v + (grey - v) * cloud);
3285
+ };
3286
+ return out.setRGB(channel(0), channel(1), channel(2));
3287
+ }
3288
+ /**
3289
+ * One small half-float panorama and filtered target per viewer; no model-specific textures or
3290
+ * network fetches. Quantization suppresses imperceptible ephemeris changes and camera motion
3291
+ * never invalidates the map. Explicit host-assigned scene.environment textures take priority.
3292
+ */
3293
+ var SkyReflections = class {
3294
+ scene;
3295
+ filter;
3296
+ texture;
3297
+ pixels = new Uint16Array(WIDTH * HEIGHT * 4);
3298
+ directions = new Float32Array(WIDTH * HEIGHT * 3);
3299
+ key;
3300
+ result;
3301
+ disposed = false;
3302
+ /** False when a host has replaced the scene environment with its own texture. */
3303
+ get active() {
3304
+ return this.result !== void 0 && this.scene.environment === this.result;
3305
+ }
3306
+ constructor(scene, filter) {
3307
+ this.scene = scene;
3308
+ this.filter = filter;
3309
+ this.texture = new THREE.DataTexture(this.pixels, WIDTH, HEIGHT, THREE.RGBAFormat, THREE.HalfFloatType);
3310
+ this.texture.name = "molen:sky-reflection-radiance";
3311
+ this.texture.mapping = THREE.EquirectangularReflectionMapping;
3312
+ this.texture.colorSpace = THREE.LinearSRGBColorSpace;
3313
+ this.texture.minFilter = THREE.LinearFilter;
3314
+ this.texture.magFilter = THREE.LinearFilter;
3315
+ this.texture.generateMipmaps = false;
3316
+ for (let row = 0; row < HEIGHT; row++) {
3317
+ const latitude = ((row + .5) / HEIGHT - .5) * Math.PI;
3318
+ for (let col = 0; col < WIDTH; col++) {
3319
+ const longitude = ((col + .5) / WIDTH - .5) * 2 * Math.PI;
3320
+ const index = (row * WIDTH + col) * 3;
3321
+ this.directions[index] = Math.cos(latitude) * Math.cos(longitude);
3322
+ this.directions[index + 1] = Math.sin(latitude);
3323
+ this.directions[index + 2] = Math.cos(latitude) * Math.sin(longitude);
3324
+ }
3325
+ }
3326
+ }
3327
+ update(state) {
3328
+ if (this.disposed) return false;
3329
+ if (this.scene.environment !== null && this.scene.environment !== this.result) return false;
3330
+ const key = [
3331
+ ...state.zenith,
3332
+ ...state.horizon,
3333
+ ...state.ground,
3334
+ ...state.twilight,
3335
+ state.twilightStrength,
3336
+ ...state.sunDirection,
3337
+ ...state.sunColor,
3338
+ state.sunGlow,
3339
+ state.clouds
3340
+ ].map((v) => Math.round(v * 128)).join(",");
3341
+ if (key === this.key) {
3342
+ if (this.result) this.scene.environment = this.result;
3343
+ return false;
3344
+ }
3345
+ const color = new THREE.Color();
3346
+ for (let i = 0; i < WIDTH * HEIGHT; i++) {
3347
+ sampleSkyReflection(state, this.directions[i * 3], this.directions[i * 3 + 1], this.directions[i * 3 + 2], color);
3348
+ this.pixels[i * 4] = THREE.DataUtils.toHalfFloat(color.r);
3349
+ this.pixels[i * 4 + 1] = THREE.DataUtils.toHalfFloat(color.g);
3350
+ this.pixels[i * 4 + 2] = THREE.DataUtils.toHalfFloat(color.b);
3351
+ this.pixels[i * 4 + 3] = THREE.DataUtils.toHalfFloat(1);
3352
+ }
3353
+ this.texture.needsUpdate = true;
3354
+ this.result = this.filter.update(this.texture);
3355
+ this.result.name = "molen:sky-reflection-pmrem";
3356
+ this.scene.environment = this.result;
3357
+ this.key = key;
3358
+ return true;
3359
+ }
3360
+ dispose() {
3361
+ if (this.disposed) return;
3362
+ this.disposed = true;
3363
+ if (this.scene.environment === this.result) this.scene.environment = null;
3364
+ this.filter.dispose();
3365
+ this.texture.dispose();
3366
+ this.result = void 0;
3367
+ }
3368
+ };
3369
+ function createWebGlSkyReflectionFilter(renderer) {
3370
+ let generator;
3371
+ let target;
3372
+ return {
3373
+ update(texture) {
3374
+ generator ??= new THREE.PMREMGenerator(renderer);
3375
+ target = generator.fromEquirectangular(texture, target);
3376
+ return target.texture;
3377
+ },
3378
+ dispose() {
3379
+ target?.dispose();
3380
+ generator?.dispose();
3381
+ target = void 0;
3382
+ generator = void 0;
3383
+ }
3384
+ };
3385
+ }
3386
+ /** Fallback for authored/static light rigs without a celestial SkyVisual. */
3387
+ function reflectionStateFromLights(ambient, sun, background, clouds) {
3388
+ const brightness = (ambient?.intensity ?? .5) / Math.PI;
3389
+ const horizon = (ambient?.color ?? background).clone().multiplyScalar(brightness);
3390
+ const zenith = background.clone().multiplyScalar(brightness);
3391
+ const ground = (ambient?.groundColor ?? new THREE.Color("#283b32")).clone().multiplyScalar(brightness);
3392
+ const direction = sun ? sun.position.clone().sub(sun.target.position).normalize() : new THREE.Vector3(0, 1, 0);
3393
+ return {
3394
+ zenith: rgb(zenith),
3395
+ horizon: rgb(horizon),
3396
+ ground: rgb(ground),
3397
+ twilight: rgb(horizon),
3398
+ twilightStrength: 0,
3399
+ sunDirection: direction.toArray(),
3400
+ sunColor: rgb(sun?.color ?? horizon),
3401
+ sunGlow: Math.min(.22, (sun?.intensity ?? 0) * .08),
3402
+ clouds
3403
+ };
3404
+ }
3405
+ //#endregion
3492
3406
  //#region src/three/renderer.ts
3493
3407
  /** Orthographic half-extents for a vertical view extent at an aspect ratio (pure; testable). */
3494
3408
  function orthoFrustum(viewHeight, aspect) {
@@ -3549,6 +3463,12 @@ var Renderer = class Renderer {
3549
3463
  warmupMaterial;
3550
3464
  warmedPrograms = /* @__PURE__ */ new WeakMap();
3551
3465
  warmedMeshes = /* @__PURE__ */ new WeakMap();
3466
+ warmups = /* @__PURE__ */ new WeakMap();
3467
+ /** Deferred meshes whose preparation has not settled, with the interest that can promote it. */
3468
+ deferredMeshes = /* @__PURE__ */ new WeakMap();
3469
+ guardedLods = /* @__PURE__ */ new WeakSet();
3470
+ /** Shared by every interest, so none captures the scope (and object tree) that created it. */
3471
+ cancel = (warmup) => this.cancelWarmup(warmup);
3552
3472
  three;
3553
3473
  backend;
3554
3474
  fallback;
@@ -3578,15 +3498,22 @@ var Renderer = class Renderer {
3578
3498
  autoWorldOrigin;
3579
3499
  timers = /* @__PURE__ */ new Set();
3580
3500
  disposed = false;
3501
+ releaseContextOnDispose;
3581
3502
  deviceLossReason;
3582
3503
  optimizer;
3583
3504
  activeSky;
3505
+ reflections;
3506
+ reflectionClearColor = Object.assign(new THREE.Color(), { a: 1 });
3584
3507
  starCatalog;
3585
3508
  activeWeather;
3586
3509
  weatherTimeOverride;
3587
3510
  weatherLightIntensities = /* @__PURE__ */ new WeakMap();
3588
3511
  environmentSeconds = 0;
3589
3512
  environmentTimeOverride;
3513
+ lastRenderStats = {
3514
+ drawCalls: 0,
3515
+ triangles: 0
3516
+ };
3590
3517
  /** Active clear-sky visual and sampled ephemeris, when environment.sky is configured. */
3591
3518
  get sky() {
3592
3519
  return this.activeSky;
@@ -3654,7 +3581,7 @@ var Renderer = class Renderer {
3654
3581
  try {
3655
3582
  if (typeof navigator === "undefined" || !("gpu" in navigator) || !navigator.gpu) throw new Error("WebGPU is unavailable in this browser or context");
3656
3583
  if (await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request") === null) throw new Error("WebGPU reported no adapter for this device");
3657
- const { createWebGpuDriver } = await import("./webgpu-driver-DXsRuz8j.mjs");
3584
+ const { createWebGpuDriver } = await import("./webgpu-driver-Bt2mvZk9.mjs");
3658
3585
  const three = await withProbeTimeout(createWebGpuDriver(opts), probeMs, "initialization", (late) => {
3659
3586
  late.dispose();
3660
3587
  });
@@ -3663,7 +3590,8 @@ var Renderer = class Renderer {
3663
3590
  return new Renderer(opts, {
3664
3591
  three,
3665
3592
  backend: "webgpu",
3666
- ...optimizer ? { optimizer } : {}
3593
+ ...optimizer ? { optimizer } : {},
3594
+ ...opts.reflections === true ? { reflectionFilter: (await import("./webgpu-sky-reflections-CymGEes-.mjs")).createWebGpuSkyReflectionFilter(three) } : {}
3667
3595
  });
3668
3596
  } catch (error) {
3669
3597
  three.dispose();
@@ -3695,6 +3623,7 @@ var Renderer = class Renderer {
3695
3623
  const cameraNear = opts.cameraNear ?? .1;
3696
3624
  const cameraFar = opts.cameraFar ?? 5e3;
3697
3625
  this.autoWorldOrigin = opts.autoWorldOrigin;
3626
+ this.releaseContextOnDispose = opts.releaseContextOnDispose ?? false;
3698
3627
  this.cameraNear = cameraNear;
3699
3628
  this.cameraFar = cameraFar;
3700
3629
  this.viewportWidth = width;
@@ -3702,7 +3631,7 @@ var Renderer = class Renderer {
3702
3631
  this.pixelRatio = pixelRatio;
3703
3632
  this.backend = initialized?.backend ?? "webgl";
3704
3633
  this.optimizer = initialized?.optimizer;
3705
- this.three = initialized?.three ?? new THREE.WebGLRenderer({
3634
+ this.three = initialized?.three ?? createWebGlRenderer({
3706
3635
  canvas: opts.canvas,
3707
3636
  antialias: opts.antialias ?? false,
3708
3637
  preserveDrawingBuffer: opts.preserveDrawingBuffer ?? true,
@@ -3722,6 +3651,7 @@ var Renderer = class Renderer {
3722
3651
  this.defaultClearColor = new THREE.Color(opts.clearColor ?? "#1a1a20");
3723
3652
  this.three.setClearColor(this.defaultClearColor, 1);
3724
3653
  this.scene = new THREE.Scene();
3654
+ this.reflections = opts.reflections === true ? new SkyReflections(this.scene, initialized?.reflectionFilter ?? createWebGlSkyReflectionFilter(this.three)) : void 0;
3725
3655
  this.worldRoot = new THREE.Group();
3726
3656
  this.worldRoot.name = "molen:world-root";
3727
3657
  this.scene.add(this.worldRoot);
@@ -3762,6 +3692,10 @@ var Renderer = class Renderer {
3762
3692
  getWorldOrigin() {
3763
3693
  return [...this.worldOrigin];
3764
3694
  }
3695
+ /** Drawing size in CSS pixels as last passed to `setSize` (before the pixel ratio). */
3696
+ getViewportSize() {
3697
+ return [this.viewportWidth, this.viewportHeight];
3698
+ }
3765
3699
  setCameraClip(near, far) {
3766
3700
  if (!Number.isFinite(near) || near <= 0 || !Number.isFinite(far) || far <= near) throw new Error("camera clip range requires finite 0 < near < far");
3767
3701
  this.camera.near = near;
@@ -3851,125 +3785,264 @@ var Renderer = class Renderer {
3851
3785
  if (this.ortho !== void 0) this.setTopDownOrtho(this.ortho);
3852
3786
  else this.camera.updateProjectionMatrix();
3853
3787
  }
3854
- /** Prepare shared resources once; all dependants await the same admission jobs. */
3855
- async prepareObject(root, signal) {
3856
- const jobs = /* @__PURE__ */ new Set();
3857
- const glAttributes = /* @__PURE__ */ new Set();
3858
- const glBatches = [];
3859
- root.updateWorldMatrix(true, true);
3788
+ /**
3789
+ * Prepare shared resources once; all dependants await the same admission jobs.
3790
+ *
3791
+ * With `parent` (the object this root will be added to), LODs are evaluated for the current
3792
+ * camera as if attached: the levels they select are prepared before this resolves, and the
3793
+ * other levels afterwards in the background, so publication waits only for what can be seen.
3794
+ * Queued work is cancelled once every caller waiting for it has aborted, and background work
3795
+ * once its mesh or geometry is disposed.
3796
+ */
3797
+ async prepareObject(root, signal, parent) {
3798
+ if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
3799
+ updateDetachedWorldMatrix(root, parent);
3800
+ const lods = parent === void 0 ? void 0 : unselectedLodLevels(root, this.camera);
3801
+ const deferredLevels = lods === void 0 ? void 0 : new Set([...lods.values()].flat());
3802
+ const foreground = createLane(false);
3803
+ const background = createLane(true);
3804
+ const interest = signal === void 0 ? "pinned" : new WarmupInterest(this.cancel);
3805
+ const deferred = [];
3860
3806
  root.traverse((object) => {
3861
3807
  const mesh = object;
3862
3808
  if (!mesh.isMesh) return;
3863
- const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
3864
- const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}`;
3865
- const variants = [];
3866
- for (const material of materials) {
3867
- for (const value of Object.values(material)) {
3868
- if (!(value instanceof THREE.Texture)) continue;
3869
- const existing = this.preparedResources.get(value);
3870
- if (existing?.version === value.version) {
3871
- jobs.add(existing.promise);
3872
- continue;
3873
- }
3874
- const promise = this.admission.run(() => this.three.initTexture(value), {
3875
- label: "texture-upload",
3876
- bytes: textureBytes(value)
3877
- });
3878
- this.rememberPreparation([value], promise);
3879
- jobs.add(promise);
3880
- }
3881
- let map = this.warmedPrograms.get(material);
3882
- if (!map) {
3883
- map = /* @__PURE__ */ new Map();
3884
- this.warmedPrograms.set(material, map);
3809
+ if (deferredLevels !== void 0 && withinAny(mesh, root, deferredLevels)) deferred.push(mesh);
3810
+ else this.prepareMesh(mesh, foreground, interest);
3811
+ });
3812
+ this.flushWebGlBatches(foreground);
3813
+ const deferredInterests = deferred.map((mesh) => {
3814
+ const meshInterest = new WarmupInterest(this.cancel);
3815
+ this.prepareMesh(mesh, background, meshInterest);
3816
+ return meshInterest;
3817
+ });
3818
+ this.flushWebGlBatches(background);
3819
+ deferred.forEach((mesh, index) => {
3820
+ const meshInterest = deferredInterests[index];
3821
+ releaseOnDispose(mesh, meshInterest);
3822
+ this.deferredMeshes.set(mesh, meshInterest);
3823
+ meshInterest.settled().then(() => {
3824
+ if (this.deferredMeshes.get(mesh) === meshInterest) this.deferredMeshes.delete(mesh);
3825
+ });
3826
+ });
3827
+ for (const [lod, levels] of lods ?? []) if (levels.length > 0) this.guardLod(lod);
3828
+ const release = () => {
3829
+ if (interest !== "pinned") interest.release();
3830
+ };
3831
+ signal?.addEventListener("abort", release, { once: true });
3832
+ let results;
3833
+ try {
3834
+ results = await Promise.allSettled(foreground.jobs);
3835
+ } finally {
3836
+ signal?.removeEventListener("abort", release);
3837
+ }
3838
+ if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
3839
+ const failure = results.find((result) => result.status === "rejected");
3840
+ if (failure?.status === "rejected") throw failure.reason;
3841
+ }
3842
+ prepareMesh(mesh, lane, interest) {
3843
+ const need = (promise) => {
3844
+ lane.jobs.add(promise);
3845
+ const warmup = this.warmups.get(promise);
3846
+ if (warmup === void 0 || warmup.settled) return;
3847
+ if (interest === "pinned") warmup.pinned = true;
3848
+ else interest.join(warmup);
3849
+ if (!lane.background) this.admission.promote(promise);
3850
+ };
3851
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
3852
+ const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}`;
3853
+ const variants = [];
3854
+ for (const material of materials) {
3855
+ for (const value of Object.values(material)) {
3856
+ if (!(value instanceof THREE.Texture)) continue;
3857
+ const existing = this.preparedResources.get(value);
3858
+ if (existing?.version === value.version) {
3859
+ need(existing.promise);
3860
+ continue;
3885
3861
  }
3886
- const variantKey = `${material.version}/${key}`;
3887
- const existing = map.get(variantKey);
3888
- if (existing) jobs.add(existing);
3889
- else variants.push({
3890
- map,
3891
- key: variantKey
3862
+ const upload = this.warmup(() => this.three.initTexture(value), lane, {
3863
+ label: "texture-upload",
3864
+ bytes: textureBytes(value)
3892
3865
  });
3866
+ this.rememberPreparation([value], upload);
3867
+ need(upload.promise);
3893
3868
  }
3894
- const instanced = mesh;
3895
- const fresh = [
3896
- ...Object.values(mesh.geometry.attributes).map((a) => a instanceof THREE.InterleavedBufferAttribute ? a.data : a),
3897
- ...mesh.geometry.index ? [mesh.geometry.index] : [],
3898
- ...instanced.isInstancedMesh ? [instanced.instanceMatrix, ...instanced.instanceColor ? [instanced.instanceColor] : []] : []
3899
- ].filter((attribute) => {
3900
- if (glAttributes.has(attribute)) return false;
3901
- const existing = this.preparedResources.get(attribute);
3902
- if (existing?.version === attribute.version) {
3903
- jobs.add(existing.promise);
3904
- return false;
3905
- }
3906
- return true;
3907
- });
3908
- let compilation;
3909
- const objectSpecific = instanced.isInstancedMesh || mesh.isSkinnedMesh || mesh.morphTargetInfluences !== void 0;
3910
- const previousMesh = this.warmedMeshes.get(mesh);
3911
- if (previousMesh) jobs.add(previousMesh);
3912
- if (variants.length > 0 || this.backend === "webgpu" && (fresh.length > 0 || objectSpecific && !previousMesh)) {
3913
- compilation = this.admission.run(() => this.compileMesh(mesh), {
3914
- label: this.backend === "webgpu" && fresh.length > 0 ? "geometry-upload-and-shader" : "shader-warmup",
3915
- bytes: this.backend === "webgpu" ? fresh.reduce((sum, a) => sum + a.array.byteLength, 0) : 0
3916
- });
3917
- jobs.add(compilation);
3918
- if (this.backend === "webgpu") {
3919
- this.warmedMeshes.set(mesh, compilation);
3920
- compilation.catch(() => {
3921
- if (this.warmedMeshes.get(mesh) === compilation) this.warmedMeshes.delete(mesh);
3922
- });
3923
- }
3924
- for (const variant of variants) {
3925
- variant.map.set(variant.key, compilation);
3926
- compilation.catch(() => {
3927
- if (variant.map.get(variant.key) === compilation) variant.map.delete(variant.key);
3928
- });
3929
- }
3869
+ let map = this.warmedPrograms.get(material);
3870
+ if (!map) {
3871
+ map = /* @__PURE__ */ new Map();
3872
+ this.warmedPrograms.set(material, map);
3930
3873
  }
3931
- if (fresh.length > 0) if (this.backend === "webgpu") {
3932
- const upload = compilation;
3933
- this.rememberPreparation(fresh, upload);
3934
- jobs.add(upload);
3935
- } else {
3936
- const bytes = fresh.reduce((sum, a) => sum + a.array.byteLength, 0);
3937
- let batch = glBatches.at(-1);
3938
- if (!batch || batch.meshes.length >= 16 || batch.bytes + bytes > this.uploadBatchBytes) {
3939
- batch = {
3940
- meshes: [],
3941
- attributes: [],
3942
- bytes: 0
3943
- };
3944
- glBatches.push(batch);
3945
- }
3946
- batch.meshes.push(mesh);
3947
- batch.attributes.push(...fresh);
3948
- batch.bytes += bytes;
3949
- for (const attribute of fresh) glAttributes.add(attribute);
3874
+ const variantKey = `${material.version}/${key}`;
3875
+ const existing = map.get(variantKey);
3876
+ if (existing) need(existing);
3877
+ else variants.push({
3878
+ map,
3879
+ key: variantKey
3880
+ });
3881
+ }
3882
+ const instanced = mesh;
3883
+ const fresh = [
3884
+ ...Object.values(mesh.geometry.attributes).map((a) => a instanceof THREE.InterleavedBufferAttribute ? a.data : a),
3885
+ ...mesh.geometry.index ? [mesh.geometry.index] : [],
3886
+ ...instanced.isInstancedMesh ? [instanced.instanceMatrix, ...instanced.instanceColor ? [instanced.instanceColor] : []] : []
3887
+ ].filter((attribute) => {
3888
+ if (lane.glAttributes.has(attribute)) return false;
3889
+ const existing = this.preparedResources.get(attribute);
3890
+ if (existing?.version === attribute.version) {
3891
+ need(existing.promise);
3892
+ return false;
3950
3893
  }
3894
+ return true;
3951
3895
  });
3952
- for (const batch of glBatches) {
3953
- const upload = this.admission.run(() => this.prepareWebGlGeometries(batch.meshes), {
3896
+ const objectSpecific = instanced.isInstancedMesh || mesh.isSkinnedMesh || mesh.morphTargetInfluences !== void 0;
3897
+ const previousMesh = this.warmedMeshes.get(mesh);
3898
+ if (previousMesh) need(previousMesh);
3899
+ let compilation;
3900
+ if (variants.length > 0 || this.backend === "webgpu" && (fresh.length > 0 || objectSpecific && !previousMesh)) {
3901
+ const warmup = this.warmup(() => this.compileMesh(mesh), lane, {
3902
+ label: this.backend === "webgpu" && fresh.length > 0 ? "geometry-upload-and-shader" : "shader-warmup",
3903
+ bytes: this.backend === "webgpu" ? fresh.reduce((sum, a) => sum + a.array.byteLength, 0) : 0
3904
+ });
3905
+ compilation = warmup;
3906
+ need(warmup.promise);
3907
+ if (this.backend === "webgpu") {
3908
+ this.warmedMeshes.set(mesh, warmup.promise);
3909
+ const forget = () => {
3910
+ if (this.warmedMeshes.get(mesh) === warmup.promise) this.warmedMeshes.delete(mesh);
3911
+ };
3912
+ warmup.forget.push(forget);
3913
+ warmup.promise.catch(forget);
3914
+ }
3915
+ for (const variant of variants) {
3916
+ variant.map.set(variant.key, warmup.promise);
3917
+ const forget = () => {
3918
+ if (variant.map.get(variant.key) === warmup.promise) variant.map.delete(variant.key);
3919
+ };
3920
+ warmup.forget.push(forget);
3921
+ warmup.promise.catch(forget);
3922
+ }
3923
+ }
3924
+ if (fresh.length === 0) return;
3925
+ if (this.backend === "webgpu") {
3926
+ this.rememberPreparation(fresh, compilation);
3927
+ return;
3928
+ }
3929
+ const bytes = fresh.reduce((sum, a) => sum + a.array.byteLength, 0);
3930
+ let batch = lane.glBatches.at(-1);
3931
+ if (!batch || batch.meshes.length >= 16 || batch.bytes + bytes > this.uploadBatchBytes) {
3932
+ batch = {
3933
+ meshes: [],
3934
+ attributes: [],
3935
+ bytes: 0,
3936
+ interests: /* @__PURE__ */ new Set()
3937
+ };
3938
+ lane.glBatches.push(batch);
3939
+ }
3940
+ batch.meshes.push(mesh);
3941
+ batch.attributes.push(...fresh);
3942
+ batch.bytes += bytes;
3943
+ batch.interests.add(interest);
3944
+ for (const attribute of fresh) lane.glAttributes.add(attribute);
3945
+ }
3946
+ flushWebGlBatches(lane) {
3947
+ for (const batch of lane.glBatches) {
3948
+ const upload = this.warmup(() => this.prepareWebGlGeometries(batch.meshes), lane, {
3954
3949
  label: "geometry-upload",
3955
3950
  bytes: batch.bytes
3956
3951
  });
3957
3952
  this.rememberPreparation(batch.attributes, upload);
3958
- jobs.add(upload);
3953
+ lane.jobs.add(upload.promise);
3954
+ for (const interest of batch.interests) if (interest === "pinned") upload.pinned = true;
3955
+ else interest.join(upload);
3959
3956
  }
3960
- const results = await Promise.allSettled(jobs);
3961
- if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
3962
- const failure = results.find((result) => result.status === "rejected");
3963
- if (failure?.status === "rejected") throw failure.reason;
3957
+ lane.glBatches.length = 0;
3958
+ }
3959
+ /** Queue one cancellable warm-up job in the lane's admission priority. */
3960
+ warmup(task, lane, options) {
3961
+ const controller = new AbortController();
3962
+ const promise = this.admission.run(task, {
3963
+ ...options,
3964
+ signal: controller.signal,
3965
+ priority: lane.background ? "background" : "normal"
3966
+ });
3967
+ const warmup = {
3968
+ promise,
3969
+ controller,
3970
+ waiters: 0,
3971
+ pinned: false,
3972
+ settled: false,
3973
+ forget: []
3974
+ };
3975
+ const settled = () => {
3976
+ warmup.settled = true;
3977
+ warmup.forget.length = 0;
3978
+ };
3979
+ promise.then(settled, settled);
3980
+ this.warmups.set(promise, warmup);
3981
+ return warmup;
3982
+ }
3983
+ /**
3984
+ * Until every level is prepared, an LOD keeps showing a prepared level rather than the one it
3985
+ * selects: drawing an unprepared level would build its shaders synchronously, mid-frame. The
3986
+ * wanted level's background work moves to the normal lane. Three and the scene optimizer call
3987
+ * `update` each frame for visible LODs, so the guard costs nothing elsewhere and removes itself.
3988
+ */
3989
+ guardLod(lod) {
3990
+ if (this.guardedLods.has(lod)) return;
3991
+ this.guardedLods.add(lod);
3992
+ const own = Object.hasOwn(lod, "update");
3993
+ const update = lod.update;
3994
+ lod.update = (camera) => {
3995
+ const shown = lod.levels.findIndex((level) => level.object.visible);
3996
+ update.call(lod, camera);
3997
+ if (this.holdUnpreparedLevel(lod, shown)) return;
3998
+ if (own) lod.update = update;
3999
+ else delete lod.update;
4000
+ this.guardedLods.delete(lod);
4001
+ };
4002
+ }
4003
+ /** Returns whether any level is still being prepared. */
4004
+ holdUnpreparedLevel(lod, shown) {
4005
+ const ready = lod.levels.map((level) => !this.pendingWithin(level.object, false));
4006
+ if (ready.every(Boolean)) return false;
4007
+ const wanted = lod.getCurrentLevel();
4008
+ if (ready[wanted] === true) return true;
4009
+ this.pendingWithin(lod.levels[wanted]?.object, true);
4010
+ let fallback = shown >= 0 && ready[shown] === true ? shown : -1;
4011
+ for (let offset = 1; fallback < 0 && offset < ready.length; offset++) if (ready[wanted - offset] === true) fallback = wanted - offset;
4012
+ else if (ready[wanted + offset] === true) fallback = wanted + offset;
4013
+ if (fallback >= 0) lod.levels.forEach((level, index) => {
4014
+ level.object.visible = index === fallback;
4015
+ });
4016
+ return true;
3964
4017
  }
3965
- rememberPreparation(resources, promise) {
4018
+ /** Whether `object` still has deferred preparation, optionally moving it to the normal lane. */
4019
+ pendingWithin(object, promote) {
4020
+ let pending = false;
4021
+ object?.traverse((child) => {
4022
+ const interest = this.deferredMeshes.get(child);
4023
+ if (interest === void 0) return;
4024
+ pending = true;
4025
+ if (promote) for (const promise of interest.promises()) this.admission.promote(promise);
4026
+ });
4027
+ return pending;
4028
+ }
4029
+ /** Nobody waits any longer: drop the job from every cache first, then from the queue. */
4030
+ cancelWarmup(warmup) {
4031
+ if (warmup.settled || warmup.pinned || warmup.waiters > 0) return;
4032
+ for (const forget of warmup.forget.splice(0)) forget();
4033
+ warmup.controller.abort();
4034
+ }
4035
+ rememberPreparation(resources, warmup) {
4036
+ const promise = warmup.promise;
3966
4037
  for (const resource of resources) this.preparedResources.set(resource, {
3967
4038
  version: resource.version,
3968
4039
  promise
3969
4040
  });
3970
- promise.catch(() => {
4041
+ const forget = () => {
3971
4042
  for (const resource of resources) if (this.preparedResources.get(resource)?.promise === promise) this.preparedResources.delete(resource);
3972
- });
4043
+ };
4044
+ warmup.forget.push(forget);
4045
+ promise.catch(forget);
3973
4046
  }
3974
4047
  compileMesh(mesh) {
3975
4048
  const visible = mesh.visible, culled = mesh.frustumCulled;
@@ -4022,7 +4095,7 @@ var Renderer = class Renderer {
4022
4095
  const weather = this.activeWeather;
4023
4096
  sky?.setCloudAttenuation(weather?.cloudAttenuation ?? 0);
4024
4097
  sky?.update(this.environmentTimeOverride ?? this.environmentSeconds);
4025
- this.scene.getObjectByName("$environment")?.traverse((object) => {
4098
+ findEnvironmentRig(this.scene)?.traverse((object) => {
4026
4099
  if (!(object instanceof THREE.Light)) return;
4027
4100
  let base = this.weatherLightIntensities.get(object);
4028
4101
  if (!weather) {
@@ -4039,9 +4112,19 @@ var Renderer = class Renderer {
4039
4112
  object.intensity = base * (1 - (weather?.cloudAttenuation ?? 0) * (object instanceof THREE.DirectionalLight ? .92 : .2));
4040
4113
  });
4041
4114
  weather?.update(this.weatherTimeOverride ?? this.environmentSeconds, this.camera, this.worldOrigin, sky?.frame);
4115
+ let reflectedAmbient;
4116
+ if (this.reflections) {
4117
+ const rig = findEnvironmentRig(this.scene);
4118
+ const ambient = rig?.children.find((light) => light instanceof THREE.HemisphereLight);
4119
+ const sun = rig?.children.find((light) => light instanceof THREE.DirectionalLight);
4120
+ this.reflections.update(sky?.reflectionState ?? reflectionStateFromLights(ambient, sun, this.three.getClearColor(this.reflectionClearColor), weather?.cloudAttenuation ?? 0));
4121
+ if (this.reflections.active) reflectedAmbient = sky?.ambientLight ?? ambient;
4122
+ }
4123
+ const ambientIntensity = reflectedAmbient?.intensity;
4042
4124
  const baseFog = this.scene.fog;
4043
4125
  if (weather) this.scene.fog = weather.fogFor(baseFog, sky?.frame);
4044
4126
  try {
4127
+ if (reflectedAmbient) reflectedAmbient.intensity = 0;
4045
4128
  if (sky) {
4046
4129
  sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
4047
4130
  sky.prepareCamera(this.camera);
@@ -4057,10 +4140,12 @@ var Renderer = class Renderer {
4057
4140
  this.three.autoClear = autoClear;
4058
4141
  this.three.info.autoReset = autoReset;
4059
4142
  }
4060
- return;
4061
- }
4062
- this.renderScene();
4143
+ } else this.renderScene();
4144
+ const info = this.three.info.render;
4145
+ this.lastRenderStats.drawCalls = "drawCalls" in info ? info.drawCalls : info.calls;
4146
+ this.lastRenderStats.triangles = info.triangles;
4063
4147
  } finally {
4148
+ if (reflectedAmbient && ambientIntensity !== void 0) reflectedAmbient.intensity = ambientIntensity;
4064
4149
  this.scene.fog = baseFog;
4065
4150
  }
4066
4151
  }
@@ -4083,13 +4168,9 @@ var Renderer = class Renderer {
4083
4168
  createRenderGroup() {
4084
4169
  return this.optimizer?.createGroup() ?? new THREE.Group();
4085
4170
  }
4086
- /** Render stats for the screenshot stats block. */
4171
+ /** Last completed visible frame, excluding offscreen resource preparation. */
4087
4172
  stats() {
4088
- const info = this.three.info.render;
4089
- return {
4090
- drawCalls: "drawCalls" in info ? info.drawCalls : info.calls,
4091
- triangles: info.triangles
4092
- };
4173
+ return { ...this.lastRenderStats };
4093
4174
  }
4094
4175
  /** Optional backend-specific GPU timing with the same nonblocking polling interface. */
4095
4176
  createGpuTimer(options = {}) {
@@ -4112,7 +4193,8 @@ var Renderer = class Renderer {
4112
4193
  this.activeSky = void 0;
4113
4194
  this.activeWeather?.dispose();
4114
4195
  this.activeWeather = void 0;
4115
- this.scene.getObjectByName("$environment")?.traverse((object) => {
4196
+ this.reflections?.dispose();
4197
+ findEnvironmentRig(this.scene)?.traverse((object) => {
4116
4198
  if (object instanceof THREE.Light) object.dispose();
4117
4199
  });
4118
4200
  this.admission.dispose();
@@ -4123,8 +4205,107 @@ var Renderer = class Renderer {
4123
4205
  this.optimizer?.dispose();
4124
4206
  this.worldRoot.clear();
4125
4207
  this.three.dispose();
4208
+ if (this.releaseContextOnDispose && this.backend === "webgl") this.three.forceContextLoss();
4126
4209
  }
4127
4210
  };
4211
+ /** One party's interest in queued warm-ups: a caller's signal, or a deferred mesh's lifetime. */
4212
+ var WarmupInterest = class {
4213
+ cancel;
4214
+ joined = /* @__PURE__ */ new Set();
4215
+ released = false;
4216
+ constructor(cancel) {
4217
+ this.cancel = cancel;
4218
+ }
4219
+ join(warmup) {
4220
+ if (this.released || this.joined.has(warmup)) return;
4221
+ this.joined.add(warmup);
4222
+ warmup.waiters++;
4223
+ }
4224
+ release() {
4225
+ if (this.released) return;
4226
+ this.released = true;
4227
+ for (const warmup of this.joined) {
4228
+ warmup.waiters--;
4229
+ this.cancel(warmup);
4230
+ }
4231
+ this.joined.clear();
4232
+ }
4233
+ settled() {
4234
+ return Promise.allSettled(this.promises());
4235
+ }
4236
+ promises() {
4237
+ return [...this.joined].map((warmup) => warmup.promise);
4238
+ }
4239
+ };
4240
+ function createLane(background) {
4241
+ return {
4242
+ background,
4243
+ jobs: /* @__PURE__ */ new Set(),
4244
+ glAttributes: /* @__PURE__ */ new Set(),
4245
+ glBatches: []
4246
+ };
4247
+ }
4248
+ /** World matrices as if `root` were already a child of `parent`, without attaching it. */
4249
+ function updateDetachedWorldMatrix(root, parent) {
4250
+ if (parent === void 0 || root.parent !== null) {
4251
+ root.updateWorldMatrix(true, true);
4252
+ return;
4253
+ }
4254
+ parent.updateWorldMatrix(true, false);
4255
+ root.parent = parent;
4256
+ try {
4257
+ root.updateWorldMatrix(false, true);
4258
+ } finally {
4259
+ root.parent = null;
4260
+ }
4261
+ }
4262
+ /** Per automatic LOD, the levels it would not show to `camera` now; the rest are needed first. */
4263
+ function unselectedLodLevels(root, camera) {
4264
+ const unselected = /* @__PURE__ */ new Map();
4265
+ root.traverse((object) => {
4266
+ const lod = object;
4267
+ if (!lod.isLOD || !lod.autoUpdate || lod.levels.length < 2) return;
4268
+ lod.update(camera);
4269
+ const selected = lod.getCurrentLevel();
4270
+ unselected.set(lod, lod.levels.filter((_, index) => index !== selected).map((level) => level.object));
4271
+ });
4272
+ return unselected;
4273
+ }
4274
+ function withinAny(object, root, set) {
4275
+ for (let node = object; node !== null; node = node.parent) {
4276
+ if (set.has(node)) return true;
4277
+ if (node === root) return false;
4278
+ }
4279
+ return false;
4280
+ }
4281
+ /** Deferred work stays wanted while its mesh lives; tile eviction disposes one or the other. */
4282
+ function releaseOnDispose(mesh, interest) {
4283
+ const targets = [mesh, mesh.geometry];
4284
+ const release = () => {
4285
+ for (const target of targets) target.removeEventListener("dispose", release);
4286
+ interest.release();
4287
+ };
4288
+ for (const target of targets) target.addEventListener("dispose", release);
4289
+ interest.settled().then(() => {
4290
+ for (const target of targets) target.removeEventListener("dispose", release);
4291
+ });
4292
+ }
4293
+ function createWebGlRenderer(options) {
4294
+ const renderer = new THREE.WebGLRenderer(options);
4295
+ if (options.reversedDepthBuffer && renderer.capabilities.reversedDepthBuffer === false) {
4296
+ const canvas = renderer.domElement;
4297
+ const context = renderer.getContext();
4298
+ renderer.dispose();
4299
+ return new THREE.WebGLRenderer({
4300
+ ...options,
4301
+ canvas,
4302
+ context,
4303
+ reversedDepthBuffer: false,
4304
+ logarithmicDepthBuffer: true
4305
+ });
4306
+ }
4307
+ return renderer;
4308
+ }
4128
4309
  function textureBytes(texture) {
4129
4310
  const image = texture.image;
4130
4311
  return image?.data?.byteLength ?? Math.ceil((image?.width ?? 1) * (image?.height ?? 1) * 4 * 4 / 3);
@@ -4509,6 +4690,68 @@ function mountClient(opts, client) {
4509
4690
  }
4510
4691
  }
4511
4692
  //#endregion
4693
+ //#region src/material-store.ts
4694
+ const STORE = "baked";
4695
+ /**
4696
+ * Baked materials kept in IndexedDB across visits; pair with `withBakedMaterialStore` from
4697
+ * `@bendyline/molen-materials`. Undefined where IndexedDB is unavailable. Every failure (quota,
4698
+ * private browsing, a blocked upgrade) resolves as a miss, so baking simply runs as before.
4699
+ */
4700
+ function createIndexedDbMaterialStore(name = "molen-baked-materials") {
4701
+ if (typeof indexedDB === "undefined") return void 0;
4702
+ let database;
4703
+ const open = () => {
4704
+ database ??= new Promise((resolve) => {
4705
+ try {
4706
+ const request = indexedDB.open(name, 1);
4707
+ request.onupgradeneeded = () => request.result.createObjectStore(STORE);
4708
+ request.onsuccess = () => resolve(request.result);
4709
+ request.onerror = () => resolve(void 0);
4710
+ request.onblocked = () => resolve(void 0);
4711
+ } catch {
4712
+ resolve(void 0);
4713
+ }
4714
+ });
4715
+ return database;
4716
+ };
4717
+ const transact = async (mode, work) => {
4718
+ const db = await open();
4719
+ if (db === void 0) return void 0;
4720
+ return new Promise((resolve) => {
4721
+ try {
4722
+ const transaction = db.transaction(STORE, mode);
4723
+ transaction.onabort = () => resolve(void 0);
4724
+ transaction.onerror = () => resolve(void 0);
4725
+ work(transaction.objectStore(STORE), resolve);
4726
+ } catch {
4727
+ resolve(void 0);
4728
+ }
4729
+ });
4730
+ };
4731
+ return {
4732
+ get: (key) => transact("readonly", (store, done) => {
4733
+ const request = store.get(key);
4734
+ request.onsuccess = () => done(request.result);
4735
+ }),
4736
+ set: async (key, material) => {
4737
+ await transact("readwrite", (store, done) => {
4738
+ store.put(material, key).onsuccess = () => done(void 0);
4739
+ });
4740
+ },
4741
+ prune: async (keep) => {
4742
+ await transact("readwrite", (store, done) => {
4743
+ const request = store.openKeyCursor();
4744
+ request.onsuccess = () => {
4745
+ const cursor = request.result;
4746
+ if (cursor === null) return done(void 0);
4747
+ if (!keep(String(cursor.key))) store.delete(cursor.key);
4748
+ cursor.continue();
4749
+ };
4750
+ });
4751
+ }
4752
+ };
4753
+ }
4754
+ //#endregion
4512
4755
  //#region src/sky/star-catalog.ts
4513
4756
  const MAGIC = 1381258061;
4514
4757
  const VERSION = 1;
@@ -4576,4 +4819,4 @@ function decodeStarCatalog(input) {
4576
4819
  }));
4577
4820
  }
4578
4821
  //#endregion
4579
- export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, InputMap, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, lerp3, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, orthoFrustum, readModelSignals, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };
4822
+ export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, InputMap, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, lerp3, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };