@bendyline/molen-client 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as nlerp4, t as lerp3 } from "./math-ev_jEkRe.mjs";
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";
2
+ import { r as readModelSignals, t as createModelSignalVisual } from "./model-signals-DLgvjBeZ.mjs";
3
+ import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-BVZjf4T-.mjs";
4
4
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
5
5
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
6
6
  import * as THREE from "three";
@@ -446,6 +446,11 @@ var InterpolationBuffer = class {
446
446
  get size() {
447
447
  return this.snaps.length;
448
448
  }
449
+ /** Resume wall-clock playback after an intentional pause, retaining poses and the render floor. */
450
+ resumeClock(nowMs) {
451
+ const tick = this.latestTick;
452
+ if (tick !== void 0) this.clockOffsetMs = nowMs - tick * this.tickMs;
453
+ }
449
454
  /**
450
455
  * Fold one arrival into the smoothed clock offset. Anchoring on the newest arrival instead (the
451
456
  * old `latest.tick + (now - latest.recvMs)`) makes every stall a visible rewind: a delta that
@@ -794,6 +799,7 @@ function createClientCore(opts) {
794
799
  let buffer;
795
800
  let bufferTickRate;
796
801
  let awaitingKeyframe = false;
802
+ let playbackPaused;
797
803
  const delayTicks = opts.interpolationDelayTicks;
798
804
  const nowMs = opts.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
799
805
  const eventHandlers = /* @__PURE__ */ new Map();
@@ -926,10 +932,16 @@ function createClientCore(opts) {
926
932
  },
927
933
  sendCommand,
928
934
  command: (type, payload = {}) => sendCommand(localCommand(seq++, type, payload)),
929
- control: (action) => link.postMessage({
930
- type: "control",
931
- control: action
932
- }),
935
+ control: (action) => {
936
+ if (action.action === "resume") {
937
+ if (playbackPaused !== false) buffer?.resumeClock(nowMs());
938
+ playbackPaused = false;
939
+ } else if (action.action === "pause") playbackPaused = true;
940
+ link.postMessage({
941
+ type: "control",
942
+ control: action
943
+ });
944
+ },
933
945
  dispose: () => {
934
946
  if (listeningWithEventTarget) {
935
947
  link.removeEventListener?.("message", handler);
@@ -1565,6 +1577,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1565
1577
  modelSignals = /* @__PURE__ */ new Map();
1566
1578
  identities = /* @__PURE__ */ new Map();
1567
1579
  lights = /* @__PURE__ */ new Map();
1580
+ pointLightSlots = [];
1568
1581
  /** Refcounted primitive geometry, keyed by `geometryKey`; disposed when the count hits 0. */
1569
1582
  geometries = /* @__PURE__ */ new Map();
1570
1583
  entityGeometry = /* @__PURE__ */ new Map();
@@ -1900,7 +1913,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1900
1913
  }
1901
1914
  applyModelSignals(id) {
1902
1915
  const state = this.modelSignals.get(id);
1903
- state?.visual?.update(state.signals);
1916
+ state?.visual?.update(state.signals, this.animationTick / this.animationTickRate);
1904
1917
  }
1905
1918
  destroy(id) {
1906
1919
  this.modelSignals.delete(id);
@@ -1970,6 +1983,19 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1970
1983
  light.castShadow = data.castShadow === true;
1971
1984
  this.scene.add(light);
1972
1985
  this.lights.set(id, light);
1986
+ const cap = this.optimization.maxLocalLights;
1987
+ if (this.renderer?.backend === "webgpu" && cap !== void 0 && this.isSlottedPoint(light)) {
1988
+ light.visible = false;
1989
+ const count = [...this.lights.values()].filter((value) => this.isSlottedPoint(value)).length;
1990
+ if (this.pointLightSlots.length < Math.min(cap, count)) {
1991
+ const slot = new THREE.PointLight(16777215, 0);
1992
+ slot.name = `molen-point-slot-${this.pointLightSlots.length}`;
1993
+ slot.matrixAutoUpdate = false;
1994
+ slot.updateMatrix();
1995
+ this.pointLightSlots.push(slot);
1996
+ this.scene.add(slot);
1997
+ }
1998
+ }
1973
1999
  }
1974
2000
  updateLight(id, data) {
1975
2001
  this.destroyLight(id);
@@ -2008,9 +2034,10 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2008
2034
  for (const id of this.animations) {
2009
2035
  const binding = this.gltf.get(id);
2010
2036
  if (binding) this.poseAnimation(binding);
2011
- this.applyModelSignals(id);
2012
2037
  }
2038
+ for (const id of this.modelSignals.keys()) this.applyModelSignals(id);
2013
2039
  for (const handle of this.handles.values()) handle.setTick?.(tick, tickRate, void 0);
2040
+ if (this.pointLightSlots.length > 0 && this.renderer) this.updateLocalLights(this.renderer.camera);
2014
2041
  }
2015
2042
  /** Flush static membership only when bindings change; world-origin shifts move the common root. */
2016
2043
  prepareFrame() {
@@ -2059,6 +2086,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2059
2086
  this.applyModelSignals(id);
2060
2087
  this.lastPoseTick.set(id, tick);
2061
2088
  }
2089
+ for (const id of this.modelSignals.keys()) if (!this.animations.has(id)) this.applyModelSignals(id);
2062
2090
  for (const [id, handle] of this.handles) {
2063
2091
  if (handle.setTick === void 0) continue;
2064
2092
  const object = handle.object;
@@ -2088,6 +2116,8 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2088
2116
  this.updateLocalLights(camera);
2089
2117
  }
2090
2118
  updateLocalLights(camera) {
2119
+ camera.updateMatrixWorld();
2120
+ this.frustum.setFromProjectionMatrix(this.viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse), camera.coordinateSystem, camera.reversedDepth);
2091
2121
  const local = [];
2092
2122
  const cameraPosition = camera.getWorldPosition(new THREE.Vector3());
2093
2123
  for (const light of this.lights.values()) {
@@ -2106,6 +2136,26 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2106
2136
  local.sort((a, b) => b.score - a.score || a.light.id - b.light.id);
2107
2137
  for (let i = Math.max(0, Math.floor(cap)); i < local.length; i++) local[i].light.visible = false;
2108
2138
  }
2139
+ if (this.pointLightSlots.length > 0) {
2140
+ let index = 0;
2141
+ for (const { light } of local) {
2142
+ if (!light.visible || !this.isSlottedPoint(light)) continue;
2143
+ const slot = this.pointLightSlots[index++];
2144
+ if (!slot) continue;
2145
+ slot.color.copy(light.color);
2146
+ slot.intensity = light.intensity;
2147
+ slot.distance = light.distance;
2148
+ slot.decay = light.decay;
2149
+ slot.layers.mask = light.layers.mask;
2150
+ slot.position.copy(light.position);
2151
+ slot.updateMatrix();
2152
+ }
2153
+ for (; index < this.pointLightSlots.length; index++) this.pointLightSlots[index].intensity = 0;
2154
+ for (const light of this.lights.values()) if (this.isSlottedPoint(light)) light.visible = false;
2155
+ }
2156
+ }
2157
+ isSlottedPoint(light) {
2158
+ return light instanceof THREE.PointLight && !light.castShadow;
2109
2159
  }
2110
2160
  entityForIntersection(hit) {
2111
2161
  const ids = hit.object.userData.molenEntityIds;
@@ -2119,6 +2169,11 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2119
2169
  this.batches?.dispose();
2120
2170
  for (const id of [...this.objects.keys()]) this.destroy(id);
2121
2171
  for (const id of [...this.lights.keys()]) this.destroyLight(id);
2172
+ for (const slot of this.pointLightSlots) {
2173
+ this.scene.remove(slot);
2174
+ slot.dispose();
2175
+ }
2176
+ this.pointLightSlots.length = 0;
2122
2177
  for (const kind of this.kinds.values()) kind.dispose?.();
2123
2178
  this.kinds.clear();
2124
2179
  for (const entry of this.geometries.values()) entry.geometry.dispose();
@@ -2239,8 +2294,12 @@ var FrameAdmissionQueue = class {
2239
2294
  this.queuedBackground.delete(job.promise);
2240
2295
  job.promise = void 0;
2241
2296
  }
2242
- /** Move a still-queued background job to the normal lane, behind the jobs already there. */
2243
- promote(promise) {
2297
+ /**
2298
+ * Move a still-queued background job to the normal lane, behind the jobs already there, or with
2299
+ * `front` ahead of them: for work a frame is waiting on, such as a material an object holds off
2300
+ * switching to until it is prepared.
2301
+ */
2302
+ promote(promise, options = {}) {
2244
2303
  const job = this.queuedBackground.get(promise);
2245
2304
  const index = job === void 0 ? -1 : this.background.indexOf(job);
2246
2305
  if (job === void 0 || index < 0) return;
@@ -2250,7 +2309,8 @@ var FrameAdmissionQueue = class {
2250
2309
  ...job.options,
2251
2310
  priority: "normal"
2252
2311
  };
2253
- this.jobs.push(job);
2312
+ if (options.front === true) this.jobs.unshift(job);
2313
+ else this.jobs.push(job);
2254
2314
  this.request();
2255
2315
  }
2256
2316
  get pending() {
@@ -2712,9 +2772,14 @@ var SkyVisual = class {
2712
2772
  this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
2713
2773
  this.ambientLight.color.lerp(new THREE.Color("#b9c2cb"), this.cloudAttenuation * daylight * .6);
2714
2774
  const radiance = this.ambientLight.intensity / Math.PI;
2775
+ const saturation = Math.max(0, Math.min(1, light?.skyLightSaturation ?? 1));
2776
+ const cast = (color) => {
2777
+ const luminance = color.r * .2126 + color.g * .7152 + color.b * .0722;
2778
+ return color.setRGB(luminance + (color.r - luminance) * saturation, luminance + (color.g - luminance) * saturation, luminance + (color.b - luminance) * saturation);
2779
+ };
2715
2780
  this.currentReflections = {
2716
- zenith: rgb$1(this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight).multiplyScalar(radiance)),
2717
- horizon: rgb$1(this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight).multiplyScalar(radiance)),
2781
+ zenith: rgb$1(cast(this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight)).multiplyScalar(radiance)),
2782
+ horizon: rgb$1(cast(this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight)).multiplyScalar(radiance)),
2718
2783
  ground: rgb$1(this.palette.ground.clone().multiplyScalar((.08 + daylight * .92) * radiance)),
2719
2784
  twilight: rgb$1(this.palette.twilight.clone().multiplyScalar(radiance)),
2720
2785
  twilightStrength: smooth$2(-18, -4, altitude) * (1 - smooth$2(0, 16, altitude)),
@@ -2763,6 +2828,7 @@ var SkyVisual = class {
2763
2828
  const horizon = this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight);
2764
2829
  const zenith = this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight);
2765
2830
  const twilight = smooth$2(-18, -4, altitude) * (1 - smooth$2(0, 16, altitude));
2831
+ const brightness = this.data.dome?.brightness ?? 1;
2766
2832
  const color = new THREE.Color();
2767
2833
  const dir = new THREE.Vector3();
2768
2834
  for (let i = 0; i < positions.count; i++) {
@@ -2772,7 +2838,7 @@ var SkyVisual = class {
2772
2838
  color.lerp(this.palette.twilight, twilight * Math.exp(-Math.abs(dir.y) * 7) * (.25 + .7 * nearSun));
2773
2839
  if (dir.y < 0) color.lerp(this.palette.ground.clone().multiplyScalar(.08 + daylight * .92), smooth$2(0, .2, -dir.y));
2774
2840
  const glow = clamp$3(dir.dot(sun)) ** 96 * smooth$2(-2, 5, altitude) * .22;
2775
- color.lerp(this.palette.sun, glow);
2841
+ color.lerp(this.palette.sun, glow).multiplyScalar(brightness);
2776
2842
  colors.setXYZW(i, color.r, color.g, color.b, 1);
2777
2843
  }
2778
2844
  colors.needsUpdate = true;
@@ -2889,7 +2955,8 @@ function noise(x, y, period, seed) {
2889
2955
  const d = hash(wrap(ix + 1, period), wrap(iy + 1, period), seed);
2890
2956
  return (a + (b - a) * fx) * (1 - fy) + (c + (d - c) * fx) * fy;
2891
2957
  }
2892
- const CLOUD_RESOLUTION = 256;
2958
+ /** Cloud texture texels per side: about 47 m each at the explorer's 24 km cloud scale. */
2959
+ const CLOUD_RESOLUTION = 512;
2893
2960
  const PARTICLE_LIMIT = 1400;
2894
2961
  /**
2895
2962
  * Lightweight layered clouds and local precipitation with standard materials on both graphics
@@ -2968,6 +3035,7 @@ var WeatherVisual = class {
2968
3035
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
2969
3036
  texture.magFilter = THREE.LinearFilter;
2970
3037
  texture.minFilter = THREE.LinearMipmapLinearFilter;
3038
+ texture.anisotropy = 16;
2971
3039
  texture.generateMipmaps = true;
2972
3040
  texture.colorSpace = THREE.LinearSRGBColorSpace;
2973
3041
  this.cloudTexture = texture;
@@ -3015,7 +3083,7 @@ var WeatherVisual = class {
3015
3083
  for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
3016
3084
  let value = 0, weight = 0;
3017
3085
  for (let octave = 0; octave < 5; octave++) {
3018
- const frequency = 8 * 2 ** octave, amplitude = .5 ** octave;
3086
+ const frequency = 8 * 2 ** octave, amplitude = .52 ** octave;
3019
3087
  value += noise(x / CLOUD_RESOLUTION * frequency, y / CLOUD_RESOLUTION * frequency, frequency, seed + octave) * amplitude;
3020
3088
  weight += amplitude;
3021
3089
  }
@@ -3533,6 +3601,12 @@ var Renderer = class Renderer {
3533
3601
  warmupMaterial;
3534
3602
  warmedPrograms = /* @__PURE__ */ new WeakMap();
3535
3603
  warmedMeshes = /* @__PURE__ */ new WeakMap();
3604
+ /**
3605
+ * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
3606
+ * `prepareVariants`.
3607
+ */
3608
+ warmedVariants = /* @__PURE__ */ new WeakMap();
3609
+ variantInterests = /* @__PURE__ */ new WeakMap();
3536
3610
  warmups = /* @__PURE__ */ new WeakMap();
3537
3611
  /** Deferred meshes whose preparation has not settled, with the interest that can promote it. */
3538
3612
  deferredMeshes = /* @__PURE__ */ new WeakMap();
@@ -3573,6 +3647,10 @@ var Renderer = class Renderer {
3573
3647
  optimizer;
3574
3648
  activeSky;
3575
3649
  reflections;
3650
+ occlusionOptions;
3651
+ occlusion;
3652
+ occlusionLoad;
3653
+ occlusionSuspended = false;
3576
3654
  /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
3577
3655
  webgpuShadowLights = /* @__PURE__ */ new WeakSet();
3578
3656
  reflectionClearColor = Object.assign(new THREE.Color(), { a: 1 });
@@ -3580,6 +3658,8 @@ var Renderer = class Renderer {
3580
3658
  activeWeather;
3581
3659
  weatherTimeOverride;
3582
3660
  weatherLightIntensities = /* @__PURE__ */ new WeakMap();
3661
+ /** The hemisphere the sky reflection map stands in for, and its authored visibility. */
3662
+ hiddenAmbient;
3583
3663
  environmentSeconds = 0;
3584
3664
  environmentTimeOverride;
3585
3665
  lastRenderStats = {
@@ -3716,12 +3796,12 @@ var Renderer = class Renderer {
3716
3796
  try {
3717
3797
  if (typeof navigator === "undefined" || !("gpu" in navigator) || !navigator.gpu) throw new Error("WebGPU is unavailable in this browser or context");
3718
3798
  if (await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request") === null) throw new Error("WebGPU reported no adapter for this device");
3719
- const { createWebGpuDriver } = await import("./webgpu-driver-Bt2mvZk9.mjs");
3799
+ const { createWebGpuDriver } = await import("./webgpu-driver-BQnmPRqs.mjs");
3720
3800
  const three = await withProbeTimeout(createWebGpuDriver(opts), probeMs, "initialization", (late) => {
3721
3801
  late.dispose();
3722
3802
  });
3723
3803
  try {
3724
- const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-DKRyHBRC.mjs"))).WebGpuSceneOptimizer(three);
3804
+ const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-Cup4Yvzs.mjs"))).WebGpuSceneOptimizer(three);
3725
3805
  return new Renderer(opts, {
3726
3806
  three,
3727
3807
  backend: "webgpu",
@@ -3941,9 +4021,11 @@ var Renderer = class Renderer {
3941
4021
  const background = createLane(true);
3942
4022
  const interest = signal === void 0 ? "pinned" : new WarmupInterest(this.cancel);
3943
4023
  const deferred = [];
4024
+ const switching = [];
3944
4025
  root.traverse((object) => {
3945
4026
  const mesh = object;
3946
4027
  if (!mesh.isMesh) return;
4028
+ if (mesh.userData.materialVariants !== void 0) switching.push(mesh);
3947
4029
  if (deferredLevels !== void 0 && withinAny(mesh, root, deferredLevels)) deferred.push(mesh);
3948
4030
  else this.prepareMesh(mesh, foreground, interest);
3949
4031
  });
@@ -3962,6 +4044,7 @@ var Renderer = class Renderer {
3962
4044
  if (this.deferredMeshes.get(mesh) === meshInterest) this.deferredMeshes.delete(mesh);
3963
4045
  });
3964
4046
  });
4047
+ for (const mesh of switching) this.prepareVariants(mesh);
3965
4048
  for (const [lod, levels] of lods ?? []) if (levels.length > 0) this.guardLod(lod);
3966
4049
  const release = () => {
3967
4050
  if (interest !== "pinned") interest.release();
@@ -4094,6 +4177,55 @@ var Renderer = class Renderer {
4094
4177
  }
4095
4178
  lane.glBatches.length = 0;
4096
4179
  }
4180
+ /**
4181
+ * A mesh that swaps its own material, as an instanced detail switch swaps in an opaque twin for
4182
+ * its coarser levels, lists every material in `userData.materialVariants`. Each needs its own
4183
+ * shader build, which the first frame to draw it would otherwise make mid-frame: in flight a whole
4184
+ * view of trees changed level at once and built their twins in one frame, for most of a second.
4185
+ * `userData.materialReady(material)` tells the mesh's owner whether one is ready. Until it is, the
4186
+ * owner keeps what it shows; asking queues its build ahead of other work. Most batches never
4187
+ * change level, so a variant is built only once its mesh asks for it.
4188
+ */
4189
+ prepareVariants(mesh) {
4190
+ let builds = this.warmedVariants.get(mesh);
4191
+ if (builds === void 0) {
4192
+ builds = /* @__PURE__ */ new Map();
4193
+ this.warmedVariants.set(mesh, builds);
4194
+ }
4195
+ builds.set(mesh.material, null);
4196
+ mesh.userData.materialReady ??= (material) => this.variantReady(mesh, material);
4197
+ }
4198
+ /** Whether `mesh` can draw `material` without building it mid-frame; builds it first if not. */
4199
+ variantReady(mesh, material) {
4200
+ const builds = this.warmedVariants.get(mesh);
4201
+ const known = builds?.get(material);
4202
+ if (builds === void 0 || known === null) return true;
4203
+ let promise = known;
4204
+ if (promise === void 0) {
4205
+ let interest = this.variantInterests.get(mesh);
4206
+ if (interest === void 0) {
4207
+ interest = new WarmupInterest(this.cancel);
4208
+ releaseOnDispose(mesh, interest);
4209
+ this.variantInterests.set(mesh, interest);
4210
+ }
4211
+ const warmup = this.warmup(() => this.compileMesh(mesh, material), createLane(true), {
4212
+ label: "shader-variant",
4213
+ bytes: 0
4214
+ });
4215
+ interest.join(warmup);
4216
+ builds.set(material, warmup.promise);
4217
+ const forget = () => {
4218
+ if (builds.get(material) === warmup.promise) builds.delete(material);
4219
+ };
4220
+ warmup.forget.push(forget);
4221
+ warmup.promise.catch(forget);
4222
+ promise = warmup.promise;
4223
+ }
4224
+ const warmup = this.warmups.get(promise);
4225
+ if (warmup === void 0 || warmup.settled) return true;
4226
+ this.admission.promote(promise, { front: true });
4227
+ return false;
4228
+ }
4097
4229
  /** Queue one cancellable warm-up job in the lane's admission priority. */
4098
4230
  warmup(task, lane, options) {
4099
4231
  const controller = new AbortController();
@@ -4182,15 +4314,24 @@ var Renderer = class Renderer {
4182
4314
  warmup.forget.push(forget);
4183
4315
  promise.catch(forget);
4184
4316
  }
4185
- compileMesh(mesh) {
4186
- const visible = mesh.visible, culled = mesh.frustumCulled;
4317
+ /** Build `mesh` for the frame's draw target, drawn with `material` when given. */
4318
+ compileMesh(mesh, material) {
4319
+ const load = this.occlusionOptions !== void 0 ? this.occlusionLoad : void 0;
4320
+ if (load !== void 0 && this.occlusion === void 0) {
4321
+ const retry = () => this.compileMesh(mesh, material);
4322
+ return load.then(retry, retry);
4323
+ }
4324
+ const occlusion = this.occlusionOptions !== void 0 && this.occlusion?.camera === this.camera ? this.occlusion.pass : void 0;
4325
+ const visible = mesh.visible, culled = mesh.frustumCulled, shown = mesh.material;
4187
4326
  mesh.visible = true;
4188
4327
  mesh.frustumCulled = false;
4328
+ if (material !== void 0) mesh.material = material;
4189
4329
  try {
4190
- return this.three.compileAsync(mesh, this.camera, this.scene);
4330
+ return occlusion !== void 0 ? occlusion.compile(mesh) : this.three.compileAsync(mesh, this.camera, this.scene);
4191
4331
  } finally {
4192
4332
  mesh.visible = visible;
4193
4333
  mesh.frustumCulled = culled;
4334
+ mesh.material = shown;
4194
4335
  }
4195
4336
  }
4196
4337
  prepareWebGlGeometries(meshes) {
@@ -4258,12 +4399,26 @@ var Renderer = class Renderer {
4258
4399
  this.reflections.update(sky?.reflectionState ?? reflectionStateFromLights(ambient, sun, this.three.getClearColor(this.reflectionClearColor), weather?.cloudAttenuation ?? 0));
4259
4400
  if (this.reflections.active) reflectedAmbient = sky?.ambientLight ?? ambient;
4260
4401
  }
4261
- const ambientIntensity = reflectedAmbient?.intensity;
4402
+ this.hideReflectedAmbient(reflectedAmbient);
4262
4403
  const baseFog = this.scene.fog;
4263
4404
  if (weather) this.scene.fog = weather.fogFor(baseFog, sky?.frame);
4405
+ const occlusion = this.currentOcclusion();
4264
4406
  try {
4265
- if (reflectedAmbient) reflectedAmbient.intensity = 0;
4266
- if (sky) {
4407
+ if (occlusion) {
4408
+ if (sky) {
4409
+ sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
4410
+ sky.prepareCamera(this.camera);
4411
+ }
4412
+ this.applyShadowFocus();
4413
+ const autoReset = this.three.info.autoReset;
4414
+ this.three.info.reset();
4415
+ this.three.info.autoReset = false;
4416
+ try {
4417
+ this.optimized(() => occlusion.render(sky, !this.occlusionSuspended));
4418
+ } finally {
4419
+ this.three.info.autoReset = autoReset;
4420
+ }
4421
+ } else if (sky) {
4267
4422
  sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
4268
4423
  sky.prepareCamera(this.camera);
4269
4424
  this.applyShadowFocus();
@@ -4287,25 +4442,97 @@ var Renderer = class Renderer {
4287
4442
  this.lastRenderStats.drawCalls = "drawCalls" in info ? info.drawCalls : info.calls;
4288
4443
  this.lastRenderStats.triangles = info.triangles;
4289
4444
  } finally {
4290
- if (reflectedAmbient && ambientIntensity !== void 0) reflectedAmbient.intensity = ambientIntensity;
4291
4445
  this.scene.fog = baseFog;
4292
4446
  }
4293
4447
  }
4448
+ /**
4449
+ * The PMREM supplies both diffuse sky irradiance and specular reflection, so while it is the
4450
+ * scene environment the hemisphere it was sampled from must not light surfaces as well. The
4451
+ * light is hidden, between frames too, rather than dimmed for the visible draw alone: three's
4452
+ * WebGPU renderer updates light uniforms once per frame of its own clock, and warm-up compiles
4453
+ * finish between viewer frames, so a light restored after each draw could leave its full
4454
+ * intensity in the next frame's uniforms and the whole scene flashed bright for that frame.
4455
+ * Its intensity stays the authored value for weather and hosts; it shows again when a host
4456
+ * environment takes over or the renderer is disposed.
4457
+ */
4458
+ hideReflectedAmbient(light) {
4459
+ const hidden = this.hiddenAmbient;
4460
+ if (hidden !== void 0 && hidden.light !== light) {
4461
+ hidden.light.visible = hidden.visible;
4462
+ this.hiddenAmbient = void 0;
4463
+ }
4464
+ if (light === void 0) return;
4465
+ this.hiddenAmbient ??= {
4466
+ light,
4467
+ visible: light.visible
4468
+ };
4469
+ light.visible = false;
4470
+ }
4294
4471
  renderScene() {
4472
+ this.optimized(() => this.three.render(this.scene, this.camera));
4473
+ }
4474
+ optimized(draw) {
4295
4475
  if (this.optimizer === void 0) {
4296
- this.three.render(this.scene, this.camera);
4476
+ draw();
4297
4477
  return;
4298
4478
  }
4299
4479
  this.optimizer.prepare(this.scene, this.camera);
4300
4480
  const autoUpdate = this.scene.matrixWorldAutoUpdate;
4301
4481
  this.scene.matrixWorldAutoUpdate = false;
4302
4482
  try {
4303
- this.three.render(this.scene, this.camera);
4483
+ draw();
4304
4484
  this.optimizer.finish();
4305
4485
  } finally {
4306
4486
  this.scene.matrixWorldAutoUpdate = autoUpdate;
4307
4487
  }
4308
4488
  }
4489
+ /**
4490
+ * Screen-space ambient occlusion on the WebGPU backend (a no-op on WebGL): creases, corners and
4491
+ * the ground around buildings and trees darken a little, as indirect light cannot reach them.
4492
+ * The frame then renders through a node pipeline; frames draw directly while it compiles.
4493
+ */
4494
+ setAmbientOcclusion(enabled, options = {}) {
4495
+ if (this.disposed) throw new Error("Renderer has been disposed");
4496
+ const next = enabled && this.backend === "webgpu" ? { ...options } : void 0;
4497
+ const current = this.occlusionOptions;
4498
+ if (next !== void 0 && current !== void 0 && next.radius === current.radius && next.strength === current.strength && next.reach === current.reach) return;
4499
+ this.occlusion?.pass.dispose();
4500
+ this.occlusion = void 0;
4501
+ this.occlusionOptions = next;
4502
+ this.currentOcclusion();
4503
+ }
4504
+ /**
4505
+ * Skip the occlusion computation while keeping ambient occlusion set up: the frame still draws
4506
+ * into its target, and the image is copied out unshaded. Each object's shaders are built for
4507
+ * one draw target, so turning occlusion off and on again (`setAmbientOcclusion`) built every
4508
+ * object in view again, mid-frame, when the target changed; suspending changes nothing there.
4509
+ */
4510
+ suspendAmbientOcclusion(suspended) {
4511
+ if (this.disposed) throw new Error("Renderer has been disposed");
4512
+ this.occlusionSuspended = suspended;
4513
+ }
4514
+ /** The occlusion pass for the current camera, building one in the background when needed. */
4515
+ currentOcclusion() {
4516
+ const options = this.occlusionOptions;
4517
+ if (options === void 0) return void 0;
4518
+ if (this.occlusion !== void 0 && this.occlusion.camera !== this.camera) {
4519
+ this.occlusion.pass.dispose();
4520
+ this.occlusion = void 0;
4521
+ }
4522
+ if (this.occlusion === void 0 && this.occlusionLoad === void 0) {
4523
+ const camera = this.camera;
4524
+ this.occlusionLoad = import("./webgpu-ambient-occlusion-9gnp3qOY.mjs").then(({ createWebGpuAmbientOcclusion }) => createWebGpuAmbientOcclusion(this.three, this.scene, camera, options)).then((pass) => {
4525
+ if (this.disposed || this.occlusionOptions !== options) pass.dispose();
4526
+ else this.occlusion = {
4527
+ camera,
4528
+ pass
4529
+ };
4530
+ }).finally(() => {
4531
+ this.occlusionLoad = void 0;
4532
+ });
4533
+ }
4534
+ return this.occlusion?.camera === this.camera ? this.occlusion.pass : void 0;
4535
+ }
4309
4536
  /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
4310
4537
  createRenderGroup() {
4311
4538
  return this.optimizer?.createGroup() ?? new THREE.Group();
@@ -4331,11 +4558,15 @@ var Renderer = class Renderer {
4331
4558
  dispose() {
4332
4559
  if (this.disposed) return;
4333
4560
  this.disposed = true;
4561
+ this.occlusionOptions = void 0;
4562
+ this.occlusion?.pass.dispose();
4563
+ this.occlusion = void 0;
4334
4564
  this.activeSky?.dispose();
4335
4565
  this.activeSky = void 0;
4336
4566
  this.activeWeather?.dispose();
4337
4567
  this.activeWeather = void 0;
4338
4568
  this.reflections?.dispose();
4569
+ this.hideReflectedAmbient(void 0);
4339
4570
  findEnvironmentRig(this.scene)?.traverse((object) => {
4340
4571
  if (object instanceof THREE.Light) object.dispose();
4341
4572
  });
@@ -4406,8 +4637,9 @@ function unselectedLodLevels(root, camera) {
4406
4637
  const unselected = /* @__PURE__ */ new Map();
4407
4638
  root.traverse((object) => {
4408
4639
  const lod = object;
4409
- if (!lod.isLOD || !lod.autoUpdate || lod.levels.length < 2) return;
4640
+ if (!lod.isLOD || !lod.autoUpdate) return;
4410
4641
  lod.update(camera);
4642
+ if (lod.levels.length < 2) return;
4411
4643
  const selected = lod.getCurrentLevel();
4412
4644
  unselected.set(lod, lod.levels.filter((_, index) => index !== selected).map((level) => level.object));
4413
4645
  });
@@ -189,14 +189,18 @@ var InputMap = class {
189
189
  }
190
190
  attach(target) {
191
191
  const editable = (ev) => {
192
- return !!ev.target?.closest?.("input, textarea, select, button, [contenteditable]:not([contenteditable=\"false\"]), [data-molen-input-editor]");
192
+ return !!ev.target?.closest?.("input, textarea, select, button, a, summary, [contenteditable]:not([contenteditable=\"false\"]), [data-molen-input-editor]");
193
193
  };
194
194
  const add = (type, fn) => {
195
195
  target.addEventListener(type, fn);
196
196
  this.listeners.push([type, fn]);
197
197
  };
198
198
  add("keydown", (ev) => {
199
- if (!editable(ev)) this.press(ev.code);
199
+ const event = ev;
200
+ if (editable(ev) || event.defaultPrevented || event.isComposing) return;
201
+ if (event.metaKey || event.ctrlKey && !event.code.startsWith("Control") && resolveAction(this.profile.bindings, "ControlLeft") === void 0 && resolveAction(this.profile.bindings, "ControlRight") === void 0 || event.altKey && !event.code.startsWith("Alt") && resolveAction(this.profile.bindings, "AltLeft") === void 0 && resolveAction(this.profile.bindings, "AltRight") === void 0) return;
202
+ if (this.accepting && resolveAction(this.profile.bindings, event.code) !== void 0) event.preventDefault?.();
203
+ this.press(event.code);
200
204
  });
201
205
  add("keyup", (ev) => this.release(ev.code));
202
206
  add("mousedown", (ev) => {
@@ -0,0 +1,63 @@
1
+ import { a as readModelSignals, i as modelSignalDisplacement, n as ModelSignals, r as createModelSignalVisual, t as ModelSignalVisual } from "./model-signals-BpeXhsim.mjs";
2
+ import { ModelSignalBinding, ModelSignalExpression, ModelSignalSpec } from "@bendyline/molen-schema";
3
+
4
+ //#region src/model-signal-expressions.d.ts
5
+ /** Compile a bounded dependency graph once. Evaluation is read-only and never executes code. */
6
+ declare function compileModelSignalExpressions(definitions: Record<string, ModelSignalExpression> | undefined): (sources: ModelSignals) => ModelSignals;
7
+ //#endregion
8
+ //#region src/instruments.d.ts
9
+ interface DialInstrumentOptions {
10
+ node: string;
11
+ source: string;
12
+ /** Measured [reading, needle radians from authored rest] pairs, including nonlinear scales. */
13
+ calibration: [number, number][];
14
+ axis?: "x" | "y" | "z";
15
+ responseSeconds?: number;
16
+ /** Usually 2π for a continuously rotating heading or altimeter needle. */
17
+ period?: number;
18
+ missing?: "hold" | "rest";
19
+ }
20
+ /** The same binding can calibrate tick placement with modelSignalDisplacement(binding, reading). */
21
+ declare function dialInstrument(options: DialInstrumentOptions): ModelSignalBinding;
22
+ interface AltimeterInstrumentOptions {
23
+ /** Caller supplies barometrically indicated altitude in feet, or explicitly labels an approximation. */
24
+ source: string;
25
+ hundreds: string;
26
+ thousands: string;
27
+ tenThousands?: string;
28
+ axis?: "x" | "y" | "z";
29
+ /** +Z facing the viewer uses -1 for clockwise motion. Reverse for a frame facing -Z. */
30
+ direction?: 1 | -1;
31
+ responseSeconds?: number;
32
+ }
33
+ /** Three independent, continuous needles: one turn per 1,000 / 10,000 / 100,000 feet. */
34
+ declare function altimeterInstrument(options: AltimeterInstrumentOptions): ModelSignalBinding[];
35
+ interface AttitudeInstrumentOptions {
36
+ /** A bank frame containing the pitch card, inside the authored face mask. */
37
+ bankNode: string;
38
+ pitchNode: string;
39
+ rollSource?: string;
40
+ pitchSource?: string;
41
+ bankAxis?: "x" | "y" | "z";
42
+ pitchAxis?: "x" | "y" | "z";
43
+ /** Local meters per radian; sign follows the face's orientation. */
44
+ pitchScale: number;
45
+ pitchLimit: number;
46
+ bankDirection?: 1 | -1;
47
+ responseSeconds?: number;
48
+ }
49
+ /** Moving horizon behind a fixed aircraft symbol. Geometry supplies the circular mask. */
50
+ declare function attitudeInstrument(options: AttitudeInstrumentOptions): ModelSignalBinding[];
51
+ /** Own an authored lamp/flag node; positive means on, missing readings turn it off. */
52
+ declare function annunciatorInstrument(node: string, source: string): ModelSignalBinding;
53
+ interface NumericInstrumentOptions {
54
+ source: string;
55
+ /** Most-significant to least-significant digit; each has seven node names in a,b,c,d,e,f,g order. */
56
+ digits: [string, string, string, string, string, string, string][];
57
+ /** Prefix for private derived variables, unique when combining multiple readouts. */
58
+ prefix: string;
59
+ }
60
+ /** Fixed-width unsigned integer display; no DOM, textures or per-frame glyph allocation. */
61
+ declare function numericInstrument(options: NumericInstrumentOptions): ModelSignalSpec;
62
+ //#endregion
63
+ export { AltimeterInstrumentOptions, AttitudeInstrumentOptions, DialInstrumentOptions, type ModelSignalVisual, type ModelSignals, NumericInstrumentOptions, altimeterInstrument, annunciatorInstrument, attitudeInstrument, compileModelSignalExpressions, createModelSignalVisual, dialInstrument, modelSignalDisplacement, numericInstrument, readModelSignals };