@bendyline/molen-client 0.0.7 → 0.0.9

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.
@@ -1,5 +1,5 @@
1
- import { n as ModelSignals } from "./model-signals-DVlLyP-w.mjs";
2
- import { a as VehicleCameraPose, i as VehicleCameraOptions, n as VehicleInteriorVisual } from "./vehicle-interior-0o-8QV_-.mjs";
1
+ import { n as ModelSignals, t as ModelSignalVisual } from "./model-signals-DVlLyP-w.mjs";
2
+ import { a as VehicleCameraPose, i as VehicleCameraOptions, n as VehicleInteriorVisual } from "./vehicle-interior-GWcXnvXS.mjs";
3
3
  import { AircraftInputData, AircraftSpec, AircraftStateData } from "@bendyline/molen-schema";
4
4
  import * as THREE from "three";
5
5
 
@@ -7,10 +7,17 @@ import * as THREE from "three";
7
7
  interface AircraftVisual {
8
8
  object: THREE.Object3D;
9
9
  interior?: VehicleInteriorVisual;
10
+ /** The spec's exterior `animation` bindings (gear legs and doors, control surfaces). */
11
+ animation?: ModelSignalVisual;
10
12
  update(state: AircraftStateData, input: AircraftInputData, altitude: number, signals?: ModelSignals): void;
11
13
  dispose(): void;
12
14
  }
13
- /** Takes ownership of a loaded library GLB. The named nodes remain editable in a DCC. */
15
+ /**
16
+ * Takes ownership of a loaded library GLB. The named nodes remain editable in a DCC.
17
+ *
18
+ * The gear and flaps follow `state.gearPosition` and `state.flapPosition` as they travel, or the
19
+ * selection in `input` when the state has no positions (helicopters, hosts that animate only).
20
+ */
14
21
  declare function createAircraftVisual(model: THREE.Object3D, spec: AircraftSpec): AircraftVisual;
15
22
  interface AircraftCameraPose extends VehicleCameraPose {
16
23
  rotation: [number, number, number, number];
package/dist/aircraft.mjs CHANGED
@@ -1,9 +1,16 @@
1
- import { t as createVehicleInteriorVisual } from "./vehicle-interior-DZT0HmWC.mjs";
1
+ import { t as createModelSignalVisual } from "./model-signals-Dp5OV-Y0.mjs";
2
+ import { t as createVehicleInteriorVisual } from "./vehicle-interior-vJQsRLQy.mjs";
2
3
  import * as THREE from "three";
3
4
  //#region src/aircraft.ts
4
- /** Takes ownership of a loaded library GLB. The named nodes remain editable in a DCC. */
5
+ /**
6
+ * Takes ownership of a loaded library GLB. The named nodes remain editable in a DCC.
7
+ *
8
+ * The gear and flaps follow `state.gearPosition` and `state.flapPosition` as they travel, or the
9
+ * selection in `input` when the state has no positions (helicopters, hosts that animate only).
10
+ */
5
11
  function createAircraftVisual(model, spec) {
6
12
  const interior = spec.visual.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, spec.visual.interior);
13
+ const animation = spec.visual.animation === void 0 ? void 0 : createModelSignalVisual(model, spec.visual.animation);
7
14
  const moving = /* @__PURE__ */ new Map();
8
15
  model.traverse((o) => {
9
16
  o.userData.vehicleGeometry = true;
@@ -21,20 +28,23 @@ function createAircraftVisual(model, spec) {
21
28
  return {
22
29
  object: model,
23
30
  interior,
31
+ animation,
24
32
  update(state, input, altitude, signals) {
33
+ const gear = state.gearPosition ?? Number(input.gear);
34
+ const flaps = state.flapPosition ?? Number(input.flaps);
25
35
  for (const binding of spec.visual.rotors) {
26
36
  const engine = binding.engine === void 0 ? void 0 : state.engines?.[binding.engine];
27
37
  turn(binding.node, binding.axis, (engine?.rotorAngle ?? state.rotorAngle) * binding.multiplier);
28
38
  }
29
- for (const name of spec.visual.gearNodes) for (const node of moving.get(name) ?? []) node.visible = input.gear;
30
- for (const binding of spec.visual.flaps) turn(binding.node, binding.axis, input.flaps ? binding.multiplier : 0);
39
+ for (const name of spec.visual.gearNodes) for (const node of moving.get(name) ?? []) node.visible = gear > 0;
40
+ for (const binding of spec.visual.flaps) turn(binding.node, binding.axis, flaps * binding.multiplier);
31
41
  for (const binding of spec.visual.ailerons) turn(binding.node, binding.axis, input.roll * binding.multiplier);
32
42
  if (interior === void 0 && spec.visual.controlStick !== void 0) {
33
43
  turn(spec.visual.controlStick.node, spec.visual.controlStick.pitchAxis, input.pitch * .22);
34
44
  turn(spec.visual.controlStick.node, spec.visual.controlStick.rollAxis, input.roll * .22);
35
45
  }
36
46
  if (interior === void 0 && spec.visual.collective !== void 0) turn(spec.visual.collective.node, spec.visual.collective.axis, input.power * spec.visual.collective.multiplier);
37
- interior?.update({
47
+ const telemetry = {
38
48
  airspeed: state.airspeed,
39
49
  altitude,
40
50
  altitudeAGL: state.altitudeAGL,
@@ -47,11 +57,16 @@ function createAircraftVisual(model, spec) {
47
57
  pitchInput: input.pitch,
48
58
  rollInput: input.roll,
49
59
  yawInput: input.yaw,
50
- gear: Number(input.gear),
51
- flaps: Number(input.flaps),
60
+ elevator: state.elevator ?? input.pitch,
61
+ gear,
62
+ flaps,
52
63
  engine: Number(input.engine),
64
+ brake: Number(input.brake),
65
+ grounded: Number(state.grounded),
53
66
  ...signals
54
- });
67
+ };
68
+ interior?.update(telemetry);
69
+ animation?.update(telemetry);
55
70
  },
56
71
  dispose() {
57
72
  const geometries = /* @__PURE__ */ new Set(), materials = /* @__PURE__ */ new Set();
@@ -83,7 +98,8 @@ function aircraftCameraPose(transform, spec, options) {
83
98
  const offset = position.clone().sub(target).normalize();
84
99
  position.copy(target).addScaledVector(offset, Math.max(.3, hit - .3));
85
100
  }
86
- up = new THREE.Vector3(0, 1, 0);
101
+ const vertical = THREE.MathUtils.smoothstep(Math.abs(direction.y), .7, .95);
102
+ up = new THREE.Vector3(0, 1, 0).lerp(up, vertical).normalize();
87
103
  }
88
104
  const forward = target.clone().sub(position).normalize();
89
105
  const rotation = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().lookAt(position, target, up));
package/dist/audio.mjs CHANGED
@@ -301,11 +301,21 @@ function audibility(gain, spatial, d) {
301
301
  const ref = spatial.refDistance;
302
302
  return gain * ref / (ref + spatial.rolloff * Math.max(0, d - ref));
303
303
  }
304
- /** Vehicles someone is riding: every `mounted` component names one. */
304
+ /**
305
+ * Vehicles someone is riding: every `mounted` component names one, unless its seat is a
306
+ * `passenger` seat of the vehicle's `mountable` (a companion waiting in a parked car does not
307
+ * start its engine).
308
+ */
305
309
  function occupiedBy(source) {
306
310
  const out = /* @__PURE__ */ new Set();
307
311
  if (!source) return out;
308
- for (const [, mounted] of source.each("mounted")) if (typeof mounted.vehicle === "string") out.add(mounted.vehicle);
312
+ for (const [, mounted] of source.each("mounted")) {
313
+ const vehicle = mounted.vehicle;
314
+ if (typeof vehicle !== "string") continue;
315
+ const seats = source.get(vehicle, "mountable")?.seats;
316
+ if ((Array.isArray(seats) ? seats.find((s) => s?.id === mounted.seat) : void 0)?.role === "passenger") continue;
317
+ out.add(vehicle);
318
+ }
309
319
  return out;
310
320
  }
311
321
  var AudioDirector = class {
@@ -1,4 +1,4 @@
1
- import { n as CameraPose } from "./renderer-DNXUCuIZ.mjs";
1
+ import { n as CameraPose } from "./renderer-BRtQK4jX.mjs";
2
2
 
3
3
  //#region src/camera-track.d.ts
4
4
  interface CameraTrackKeyframe {
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as readModelSignals, n as ModelSignals, r as createModelSignalVisual, t as ModelSignalVisual } from "./model-signals-DVlLyP-w.mjs";
2
2
  import { a as createUrlAssetProvider, i as UrlAssetProviderOptions, n as AssetProvider, r as LoadedGltf, t as AssetCache } from "./assets-IbO4GJpF.mjs";
3
- import { A as createWebGlSkyReflectionFilter, C as EarthSkyState, D as SkyReflectionFilter, E as starDirection, F as FrameAdmissionQueue, I as SceneAdmission, M as AdmissionOptions, N as AdmissionSample, O as SkyReflectionState, P as FrameAdmissionOptions, S as CelestialPosition, T as skyTimeMs, _ as SkyFrame, a as RendererBackendPreference, b as SkyVisualOptions, c as TopDownOrtho, d as ShadowFocus, f as ShadowQuality, g as WeatherVisual, h as createGpuFrameTimer, i as RendererBackend, j as reflectionStateFromLights, k as SkyReflections, l as nextWorldOrigin, m as GpuFrameTimerOptions, n as CameraPose, o as RendererOptions, p as GpuFrameTimer, r as Renderer, s as ThreeRenderer, t as AutoWorldOriginOptions, u as orthoFrustum, v as SkyStar, w as evaluateEarthSky, x as defaultSkyPalette, y as SkyVisual } from "./renderer-DNXUCuIZ.mjs";
3
+ import { A as createWebGlSkyReflectionFilter, C as EarthSkyState, D as SkyReflectionFilter, E as starDirection, F as FrameAdmissionQueue, I as SceneAdmission, M as AdmissionOptions, N as AdmissionSample, O as SkyReflectionState, P as FrameAdmissionOptions, S as CelestialPosition, T as skyTimeMs, _ as SkyFrame, a as RendererBackendPreference, b as SkyVisualOptions, c as TopDownOrtho, d as ShadowFocus, f as ShadowQuality, g as WeatherVisual, h as createGpuFrameTimer, i as RendererBackend, j as reflectionStateFromLights, k as SkyReflections, l as nextWorldOrigin, m as GpuFrameTimerOptions, n as CameraPose, o as RendererOptions, p as GpuFrameTimer, r as Renderer, s as ThreeRenderer, t as AutoWorldOriginOptions, u as orthoFrustum, v as SkyStar, w as evaluateEarthSky, x as defaultSkyPalette, y as SkyVisual } from "./renderer-BRtQK4jX.mjs";
4
4
  import { a as normalizeInputAxis, i as InputMapOptions, n as InputGamepad, o as resolveAction, r as InputMap, t as InputBindings } from "./input-CD-dHuv0.mjs";
5
5
  import { Command, ControlAction, CustomSkyData, Delta, DiagMessage, EarthObserver, EarthSkyData, EngineEvent, EntityId, JsonObject, JsonValue, Keyframe, MessageLink, ModelSignalSpec, Quat, ResolvedWeather, SceneCamera, SceneInput, SceneManifest, SkyAppearance, SkyBodyData, SkyData, SkyData as SkyData$1, SkyPalette, SkyTime, Vec3, WeatherData, WeatherProfile, resolveWeather, weatherProfile } from "@bendyline/molen-schema";
6
6
  import * as THREE from "three";
@@ -159,6 +159,8 @@ declare class InterpolationBuffer {
159
159
  get latestTick(): number | undefined;
160
160
  /** Number of snapshots currently held (≤ capacity). */
161
161
  get size(): number;
162
+ /** Resume wall-clock playback after an intentional pause, retaining poses and the render floor. */
163
+ resumeClock(nowMs: number): void;
162
164
  /**
163
165
  * Fold one arrival into the smoothed clock offset. Anchoring on the newest arrival instead (the
164
166
  * old `latest.tick + (now - latest.recvMs)`) makes every stall a visible rewind: a delta that
@@ -506,6 +508,7 @@ declare class ThreeSceneBackend implements SceneBackend {
506
508
  private readonly modelSignals;
507
509
  private readonly identities;
508
510
  private readonly lights;
511
+ private readonly pointLightSlots;
509
512
  /** Refcounted primitive geometry, keyed by `geometryKey`; disposed when the count hits 0. */
510
513
  private readonly geometries;
511
514
  private readonly entityGeometry;
@@ -573,6 +576,7 @@ declare class ThreeSceneBackend implements SceneBackend {
573
576
  /** Exact tick-derived poses on return to view; invisible shadow casters are never skipped. */
574
577
  updateLiveAnimations(tick: number, tickRate: number, camera: THREE.Camera): void;
575
578
  private updateLocalLights;
579
+ private isSlottedPoint;
576
580
  entityForIntersection(hit: THREE.Intersection): EntityId | undefined;
577
581
  count(): number;
578
582
  dispose(): void;
@@ -836,7 +840,7 @@ interface EnvironmentData {
836
840
  near?: number;
837
841
  far?: number;
838
842
  };
839
- toneMapping?: "none" | "aces" | "agx";
843
+ toneMapping?: "none" | "aces" | "agx" | "neutral";
840
844
  exposure?: number;
841
845
  shadows?: "off" | "low" | "medium" | "high";
842
846
  }
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 { n as readModelSignals, t as createModelSignalVisual } from "./model-signals-Dp5OV-Y0.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);
@@ -1143,7 +1155,7 @@ function applyEnvironment(renderer, env) {
1143
1155
  renderer.three.shadowMap.type = shadows === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
1144
1156
  renderer.three.setClearColor(env.background !== void 0 ? new THREE.Color(env.background) : renderer.defaultClearColor, 1);
1145
1157
  scene.fog = env.fog !== void 0 ? new THREE.Fog(new THREE.Color(env.fog.color), env.fog.near ?? 1, env.fog.far ?? 1e3) : null;
1146
- renderer.three.toneMapping = env.toneMapping === "aces" ? THREE.ACESFilmicToneMapping : env.toneMapping === "agx" ? THREE.AgXToneMapping : THREE.NoToneMapping;
1158
+ renderer.three.toneMapping = env.toneMapping === "aces" ? THREE.ACESFilmicToneMapping : env.toneMapping === "agx" ? THREE.AgXToneMapping : env.toneMapping === "neutral" ? THREE.NeutralToneMapping : THREE.NoToneMapping;
1147
1159
  renderer.three.toneMappingExposure = env.exposure ?? 1;
1148
1160
  }
1149
1161
  //#endregion
@@ -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();
@@ -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);
@@ -2011,6 +2037,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2011
2037
  this.applyModelSignals(id);
2012
2038
  }
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() {
@@ -2088,6 +2115,8 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2088
2115
  this.updateLocalLights(camera);
2089
2116
  }
2090
2117
  updateLocalLights(camera) {
2118
+ camera.updateMatrixWorld();
2119
+ this.frustum.setFromProjectionMatrix(this.viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse), camera.coordinateSystem, camera.reversedDepth);
2091
2120
  const local = [];
2092
2121
  const cameraPosition = camera.getWorldPosition(new THREE.Vector3());
2093
2122
  for (const light of this.lights.values()) {
@@ -2106,6 +2135,26 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2106
2135
  local.sort((a, b) => b.score - a.score || a.light.id - b.light.id);
2107
2136
  for (let i = Math.max(0, Math.floor(cap)); i < local.length; i++) local[i].light.visible = false;
2108
2137
  }
2138
+ if (this.pointLightSlots.length > 0) {
2139
+ let index = 0;
2140
+ for (const { light } of local) {
2141
+ if (!light.visible || !this.isSlottedPoint(light)) continue;
2142
+ const slot = this.pointLightSlots[index++];
2143
+ if (!slot) continue;
2144
+ slot.color.copy(light.color);
2145
+ slot.intensity = light.intensity;
2146
+ slot.distance = light.distance;
2147
+ slot.decay = light.decay;
2148
+ slot.layers.mask = light.layers.mask;
2149
+ slot.position.copy(light.position);
2150
+ slot.updateMatrix();
2151
+ }
2152
+ for (; index < this.pointLightSlots.length; index++) this.pointLightSlots[index].intensity = 0;
2153
+ for (const light of this.lights.values()) if (this.isSlottedPoint(light)) light.visible = false;
2154
+ }
2155
+ }
2156
+ isSlottedPoint(light) {
2157
+ return light instanceof THREE.PointLight && !light.castShadow;
2109
2158
  }
2110
2159
  entityForIntersection(hit) {
2111
2160
  const ids = hit.object.userData.molenEntityIds;
@@ -2119,6 +2168,11 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2119
2168
  this.batches?.dispose();
2120
2169
  for (const id of [...this.objects.keys()]) this.destroy(id);
2121
2170
  for (const id of [...this.lights.keys()]) this.destroyLight(id);
2171
+ for (const slot of this.pointLightSlots) {
2172
+ this.scene.remove(slot);
2173
+ slot.dispose();
2174
+ }
2175
+ this.pointLightSlots.length = 0;
2122
2176
  for (const kind of this.kinds.values()) kind.dispose?.();
2123
2177
  this.kinds.clear();
2124
2178
  for (const entry of this.geometries.values()) entry.geometry.dispose();
@@ -2711,14 +2765,15 @@ var SkyVisual = class {
2711
2765
  this.moonLight.intensity *= 1 - this.cloudAttenuation * .9;
2712
2766
  this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
2713
2767
  this.ambientLight.color.lerp(new THREE.Color("#b9c2cb"), this.cloudAttenuation * daylight * .6);
2768
+ const radiance = this.ambientLight.intensity / Math.PI;
2714
2769
  this.currentReflections = {
2715
- zenith: rgb$1(this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight)),
2716
- horizon: rgb$1(this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight)),
2717
- ground: rgb$1(this.palette.ground.clone().multiplyScalar(.08 + daylight * .92)),
2718
- twilight: rgb$1(this.palette.twilight),
2770
+ zenith: rgb$1(this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight).multiplyScalar(radiance)),
2771
+ horizon: rgb$1(this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight).multiplyScalar(radiance)),
2772
+ ground: rgb$1(this.palette.ground.clone().multiplyScalar((.08 + daylight * .92) * radiance)),
2773
+ twilight: rgb$1(this.palette.twilight.clone().multiplyScalar(radiance)),
2719
2774
  twilightStrength: smooth$2(-18, -4, altitude) * (1 - smooth$2(0, 16, altitude)),
2720
2775
  sunDirection,
2721
- sunColor: rgb$1(this.palette.sun),
2776
+ sunColor: rgb$1(this.palette.sun.clone().multiplyScalar(radiance)),
2722
2777
  sunGlow: smooth$2(-2, 5, altitude) * .22,
2723
2778
  clouds: this.cloudAttenuation
2724
2779
  };
@@ -3292,7 +3347,7 @@ const scratchForward = new THREE.Vector3();
3292
3347
  * vector toward the sun), covering ±`radius`. The light and its target move; the direction of
3293
3348
  * the light is unchanged.
3294
3349
  */
3295
- function focusDirectionalShadow(light, direction, center, radius) {
3350
+ function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false) {
3296
3351
  const toSun = scratchForward.copy(direction).normalize();
3297
3352
  const size = light.shadow.mapSize.x || 2048;
3298
3353
  const texel = 2 * radius / size;
@@ -3319,7 +3374,7 @@ function focusDirectionalShadow(light, direction, center, radius) {
3319
3374
  camera.far = distance + radius * 2 + 1e3;
3320
3375
  camera.updateProjectionMatrix();
3321
3376
  }
3322
- light.shadow.bias = -4e-4;
3377
+ light.shadow.bias = biasAddsTowardLight ? 4e-4 : -4e-4;
3323
3378
  light.shadow.normalBias = texel * 1.2;
3324
3379
  }
3325
3380
  //#endregion
@@ -3572,11 +3627,15 @@ var Renderer = class Renderer {
3572
3627
  optimizer;
3573
3628
  activeSky;
3574
3629
  reflections;
3630
+ /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
3631
+ webgpuShadowLights = /* @__PURE__ */ new WeakSet();
3575
3632
  reflectionClearColor = Object.assign(new THREE.Color(), { a: 1 });
3576
3633
  starCatalog;
3577
3634
  activeWeather;
3578
3635
  weatherTimeOverride;
3579
3636
  weatherLightIntensities = /* @__PURE__ */ new WeakMap();
3637
+ /** The hemisphere the sky reflection map stands in for, and its authored visibility. */
3638
+ hiddenAmbient;
3580
3639
  environmentSeconds = 0;
3581
3640
  environmentTimeOverride;
3582
3641
  lastRenderStats = {
@@ -3606,18 +3665,32 @@ var Renderer = class Renderer {
3606
3665
  setShadowQuality(quality) {
3607
3666
  const enabled = quality !== "off";
3608
3667
  for (const light of this.sunLights()) {
3668
+ if (this.backend === "webgpu" && this.webgpuShadowLights.has(light)) {
3669
+ light.shadow.autoUpdate = enabled;
3670
+ light.shadow.intensity = enabled ? 1 : 0;
3671
+ continue;
3672
+ }
3609
3673
  light.castShadow = enabled;
3610
3674
  if (!enabled) continue;
3611
3675
  const size = SHADOW_MAP_SIZE[quality];
3612
3676
  if (light.shadow.mapSize.x !== size) {
3613
3677
  light.shadow.mapSize.set(size, size);
3614
- light.shadow.map?.dispose();
3615
- light.shadow.map = null;
3678
+ if (this.backend === "webgl") {
3679
+ light.shadow.map?.dispose();
3680
+ light.shadow.map = null;
3681
+ }
3616
3682
  }
3683
+ if (this.backend === "webgpu") this.webgpuShadowLights.add(light);
3617
3684
  }
3685
+ if (this.backend === "webgpu" && this.three.shadowMap.enabled) return;
3618
3686
  this.three.shadowMap.enabled = enabled;
3619
3687
  this.three.shadowMap.type = quality === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
3620
3688
  }
3689
+ /** WebGL PCF shadow lookups against a reversed depth buffer; see focusDirectionalShadow. */
3690
+ webglReversedPcfShadows() {
3691
+ const three = this.three;
3692
+ return three.state?.buffers.depth.getReversed() === true && three.shadowMap.type !== THREE.BasicShadowMap && three.shadowMap.type !== THREE.VSMShadowMap;
3693
+ }
3621
3694
  /** The directional lights standing for the sun: the environment rig's, and the sky's. */
3622
3695
  sunLights() {
3623
3696
  const lights = [];
@@ -3633,7 +3706,7 @@ var Renderer = class Renderer {
3633
3706
  const center = this.shadowCenter.set(focus.center[0] - this.worldOrigin[0], focus.center[1] - this.worldOrigin[1], focus.center[2] - this.worldOrigin[2]);
3634
3707
  for (const light of this.sunLights()) {
3635
3708
  if (!light.castShadow) continue;
3636
- focusDirectionalShadow(light, light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection), center, focus.radius);
3709
+ focusDirectionalShadow(light, light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection), center, focus.radius, this.backend === "webgl" && this.webglReversedPcfShadows());
3637
3710
  }
3638
3711
  }
3639
3712
  /** Active weather effects; physical weather data is also available in the simulation component. */
@@ -3704,7 +3777,7 @@ var Renderer = class Renderer {
3704
3777
  late.dispose();
3705
3778
  });
3706
3779
  try {
3707
- const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-D6e9ZJQM.mjs"))).WebGpuSceneOptimizer(three);
3780
+ const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-DKRyHBRC.mjs"))).WebGpuSceneOptimizer(three);
3708
3781
  return new Renderer(opts, {
3709
3782
  three,
3710
3783
  backend: "webgpu",
@@ -4241,11 +4314,10 @@ var Renderer = class Renderer {
4241
4314
  this.reflections.update(sky?.reflectionState ?? reflectionStateFromLights(ambient, sun, this.three.getClearColor(this.reflectionClearColor), weather?.cloudAttenuation ?? 0));
4242
4315
  if (this.reflections.active) reflectedAmbient = sky?.ambientLight ?? ambient;
4243
4316
  }
4244
- const ambientIntensity = reflectedAmbient?.intensity;
4317
+ this.hideReflectedAmbient(reflectedAmbient);
4245
4318
  const baseFog = this.scene.fog;
4246
4319
  if (weather) this.scene.fog = weather.fogFor(baseFog, sky?.frame);
4247
4320
  try {
4248
- if (reflectedAmbient) reflectedAmbient.intensity = 0;
4249
4321
  if (sky) {
4250
4322
  sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
4251
4323
  sky.prepareCamera(this.camera);
@@ -4270,10 +4342,32 @@ var Renderer = class Renderer {
4270
4342
  this.lastRenderStats.drawCalls = "drawCalls" in info ? info.drawCalls : info.calls;
4271
4343
  this.lastRenderStats.triangles = info.triangles;
4272
4344
  } finally {
4273
- if (reflectedAmbient && ambientIntensity !== void 0) reflectedAmbient.intensity = ambientIntensity;
4274
4345
  this.scene.fog = baseFog;
4275
4346
  }
4276
4347
  }
4348
+ /**
4349
+ * The PMREM supplies both diffuse sky irradiance and specular reflection, so while it is the
4350
+ * scene environment the hemisphere it was sampled from must not light surfaces as well. The
4351
+ * light is hidden, between frames too, rather than dimmed for the visible draw alone: three's
4352
+ * WebGPU renderer updates light uniforms once per frame of its own clock, and warm-up compiles
4353
+ * finish between viewer frames, so a light restored after each draw could leave its full
4354
+ * intensity in the next frame's uniforms and the whole scene flashed bright for that frame.
4355
+ * Its intensity stays the authored value for weather and hosts; it shows again when a host
4356
+ * environment takes over or the renderer is disposed.
4357
+ */
4358
+ hideReflectedAmbient(light) {
4359
+ const hidden = this.hiddenAmbient;
4360
+ if (hidden !== void 0 && hidden.light !== light) {
4361
+ hidden.light.visible = hidden.visible;
4362
+ this.hiddenAmbient = void 0;
4363
+ }
4364
+ if (light === void 0) return;
4365
+ this.hiddenAmbient ??= {
4366
+ light,
4367
+ visible: light.visible
4368
+ };
4369
+ light.visible = false;
4370
+ }
4277
4371
  renderScene() {
4278
4372
  if (this.optimizer === void 0) {
4279
4373
  this.three.render(this.scene, this.camera);
@@ -4319,6 +4413,7 @@ var Renderer = class Renderer {
4319
4413
  this.activeWeather?.dispose();
4320
4414
  this.activeWeather = void 0;
4321
4415
  this.reflections?.dispose();
4416
+ this.hideReflectedAmbient(void 0);
4322
4417
  findEnvironmentRig(this.scene)?.traverse((object) => {
4323
4418
  if (object instanceof THREE.Light) object.dispose();
4324
4419
  });
@@ -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) => {
@@ -16,6 +16,26 @@ function readModelSignals(sources, readComponent) {
16
16
  }
17
17
  return signals;
18
18
  }
19
+ /**
20
+ * A binding's displacement for a signal, before its limits: linear in the signal, or along its
21
+ * keyframed curve, which holds its end values outside the keys. Exported for tests.
22
+ */
23
+ function modelSignalDisplacement(binding, signal) {
24
+ const keys = binding.keys;
25
+ if (keys === void 0) return signal * (binding.scale ?? 1) + (binding.offset ?? 0);
26
+ const first = keys[0];
27
+ const last = keys[keys.length - 1];
28
+ if (first === void 0 || last === void 0) return 0;
29
+ if (signal <= first[0]) return first[1];
30
+ if (signal >= last[0]) return last[1];
31
+ let index = 1;
32
+ while (index < keys.length - 1 && signal > (keys[index]?.[0] ?? Infinity)) index++;
33
+ const [x0, y0] = keys[index - 1] ?? first;
34
+ const [x1, y1] = keys[index] ?? last;
35
+ let f = (signal - x0) / (x1 - x0);
36
+ if (binding.ease === "smooth") f = f * f * (3 - 2 * f);
37
+ return y0 + (y1 - y0) * f;
38
+ }
19
39
  /** Model-agnostic; moves existing geometry without creating a cockpit or changing physics. */
20
40
  function createModelSignalVisual(model, spec) {
21
41
  const nodes = /* @__PURE__ */ new Map();
@@ -39,7 +59,7 @@ function createModelSignalVisual(model, spec) {
39
59
  for (const { binding, node, rest } of bindings) {
40
60
  const signal = signals[binding.source];
41
61
  if (signal === void 0 || !Number.isFinite(signal)) continue;
42
- const value = signal * binding.scale + (binding.offset ?? 0);
62
+ const value = modelSignalDisplacement(binding, signal);
43
63
  if (!Number.isFinite(value)) continue;
44
64
  node[binding.property][binding.axis] = rest + Math.max(binding.min ?? -Infinity, Math.min(binding.max ?? Infinity, value));
45
65
  }
@@ -56,6 +56,12 @@ interface NavigationPointerSurface {
56
56
  ownerDocument?: {
57
57
  pointerLockElement?: unknown;
58
58
  exitPointerLock?(): void;
59
+ addEventListener?(type: string, listener: () => void): void;
60
+ removeEventListener?(type: string, listener: () => void): void;
61
+ defaultView?: {
62
+ addEventListener(type: string, listener: () => void): void;
63
+ removeEventListener(type: string, listener: () => void): void;
64
+ } | null;
59
65
  } | null;
60
66
  }
61
67
  /** The pointer-event fields the tracker reads. */
@@ -168,8 +174,8 @@ declare const NAVIGATION_ACTIONS: {
168
174
  type NavigationProfileName = "orbit" | "fly" | "walk" | "drive" | "pilot";
169
175
  /**
170
176
  * Default key/gamepad bindings per navigation mode. Orbit and fly use Q/E for down/up; walk and
171
- * drive use E to interact (board or leave a vehicle), Space to jump or brake, and V to switch
172
- * the vehicle view. Pilot flies an aircraft: W/S (or ↑/↓) pitch the nose down/up, A/D (or ←/→)
177
+ * drive use E to interact (board or leave a vehicle), Space to jump or brake, Shift to sprint
178
+ * or pull the handbrake, and V to switch the vehicle view. Pilot flies an aircraft: W/S (or ↑/↓) pitch the nose down/up, A/D (or ←/→)
173
179
  * bank, Q/Z work the rudder or pedals, Shift/Ctrl (or +/−, Page Up/Down) set throttle or
174
180
  * collective, I toggles the engine, G the gear, F the flaps, R recovers after an impact, Space
175
181
  * brakes, V switches the view and E leaves. Hosts may replace any profile through
@@ -445,6 +451,8 @@ declare class TouchStick {
445
451
  };
446
452
  }
447
453
  interface TouchJoystickOptions extends TouchStickOptions {
454
+ /** Refocus the keyboard surface before moving (e.g. after using a HUD button). */
455
+ focusTarget?: Pick<HTMLElement, "focus">;
448
456
  /** Software-device name in the InputMap (default `'touch-joystick'`). */
449
457
  source?: string;
450
458
  /** Extra class names for styling the root element. */
@@ -1,4 +1,4 @@
1
- import { t as InputMap } from "./input-CfbIm1MS.mjs";
1
+ import { t as InputMap } from "./input-BVZjf4T-.mjs";
2
2
  import * as THREE from "three";
3
3
  import { Octree } from "three/addons/math/Octree.js";
4
4
  import { Capsule } from "three/addons/math/Capsule.js";
@@ -262,6 +262,7 @@ var NavigationPointer = class {
262
262
  this.listen("pointermove", (event) => this.move(event));
263
263
  this.listen("pointerup", (event) => this.up(event, true));
264
264
  this.listen("pointercancel", (event) => this.up(event, false));
265
+ this.listen("lostpointercapture", (event) => this.up(event, false));
265
266
  this.listen("wheel", (event) => this.wheel(event), { passive: false });
266
267
  this.listen("contextmenu", (event) => event.preventDefault?.());
267
268
  }
@@ -279,7 +280,9 @@ var NavigationPointer = class {
279
280
  }
280
281
  /** Forget held pointers and pending gestures (e.g. on blur or a mode change). */
281
282
  reset() {
283
+ const captured = [...this.pointers.keys()];
282
284
  this.pointers.clear();
285
+ for (const id of captured) if (this.surface.hasPointerCapture?.(id) === true) this.surface.releasePointerCapture?.(id);
283
286
  this.pending = emptyGestures();
284
287
  }
285
288
  dispose() {
@@ -309,13 +312,16 @@ var NavigationPointer = class {
309
312
  startX: event.clientX,
310
313
  startY: event.clientY,
311
314
  startTime: this.now(),
312
- moved: false,
315
+ moved: button !== 0 || event.shiftKey === true || this.pointers.size > 0,
313
316
  pan: button === 1 || button === 2 || event.shiftKey === true
314
317
  });
318
+ if (this.pointers.size > 1) for (const pointer of this.pointers.values()) pointer.moved = true;
315
319
  this.surface.setPointerCapture?.(event.pointerId);
316
320
  }
317
321
  move(event) {
318
322
  if (this.locked() && this.pointers.size <= 1) {
323
+ const pointer = this.pointers.get(event.pointerId);
324
+ if (pointer !== void 0 && (event.movementX || event.movementY)) pointer.moved = true;
319
325
  this.pending.look[0] += event.movementX ?? 0;
320
326
  this.pending.look[1] += event.movementY ?? 0;
321
327
  return;
@@ -468,8 +474,8 @@ const STICKS = [
468
474
  ];
469
475
  /**
470
476
  * Default key/gamepad bindings per navigation mode. Orbit and fly use Q/E for down/up; walk and
471
- * drive use E to interact (board or leave a vehicle), Space to jump or brake, and V to switch
472
- * the vehicle view. Pilot flies an aircraft: W/S (or ↑/↓) pitch the nose down/up, A/D (or ←/→)
477
+ * drive use E to interact (board or leave a vehicle), Space to jump or brake, Shift to sprint
478
+ * or pull the handbrake, and V to switch the vehicle view. Pilot flies an aircraft: W/S (or ↑/↓) pitch the nose down/up, A/D (or ←/→)
473
479
  * bank, Q/Z work the rudder or pedals, Shift/Ctrl (or +/−, Page Up/Down) set throttle or
474
480
  * collective, I toggles the engine, G the gear, F the flaps, R recovers after an impact, Space
475
481
  * brakes, V switches the view and E leaves. Hosts may replace any profile through
@@ -665,8 +671,27 @@ var NavigationInputSource = class {
665
671
  this.map.onPress(A.view, () => {
666
672
  this.viewPresses++;
667
673
  }),
668
- this.map.onReset(() => this.pointer.reset())
674
+ this.map.onReset(() => {
675
+ this.pointer.reset();
676
+ this.interactPresses = 0;
677
+ this.viewPresses = 0;
678
+ this.pilotPresses.engine = 0;
679
+ this.pilotPresses.gear = 0;
680
+ this.pilotPresses.flaps = 0;
681
+ this.pilotPresses.recover = 0;
682
+ })
669
683
  ];
684
+ this.pointer.setPointerLock(this.profile === "walk");
685
+ const document = options.element.ownerDocument;
686
+ const reset = () => this.map.reset();
687
+ document?.defaultView?.addEventListener("blur", reset);
688
+ document?.addEventListener?.("visibilitychange", reset);
689
+ document?.addEventListener?.("pointerlockchange", reset);
690
+ this.unsubscribe.push(() => {
691
+ document?.defaultView?.removeEventListener("blur", reset);
692
+ document?.removeEventListener?.("visibilitychange", reset);
693
+ document?.removeEventListener?.("pointerlockchange", reset);
694
+ });
670
695
  }
671
696
  setProfile(profile) {
672
697
  this.profile = profile;
@@ -1024,6 +1049,14 @@ function createTouchJoystick(container, input, options = {}) {
1024
1049
  root.append(knob);
1025
1050
  container.append(root);
1026
1051
  let pointer;
1052
+ const reset = () => {
1053
+ const captured = pointer;
1054
+ pointer = void 0;
1055
+ if (captured !== void 0 && root.hasPointerCapture(captured)) root.releasePointerCapture(captured);
1056
+ stick.release();
1057
+ input.clearVirtual(source);
1058
+ knob.style.transform = "";
1059
+ };
1027
1060
  const publish = () => {
1028
1061
  const { forward, right } = stick.axes();
1029
1062
  input.setVirtual(source, ACTIONS.forward, Math.max(0, forward));
@@ -1044,6 +1077,7 @@ function createTouchJoystick(container, input, options = {}) {
1044
1077
  if (pointer !== void 0) return;
1045
1078
  event.preventDefault();
1046
1079
  event.stopPropagation();
1080
+ options.focusTarget?.focus({ preventScroll: true });
1047
1081
  pointer = event.pointerId;
1048
1082
  root.setPointerCapture(event.pointerId);
1049
1083
  const { x, y } = center();
@@ -1060,32 +1094,29 @@ function createTouchJoystick(container, input, options = {}) {
1060
1094
  const onUp = (event) => {
1061
1095
  if (event.pointerId !== pointer) return;
1062
1096
  event.stopPropagation();
1063
- pointer = void 0;
1064
- stick.release();
1065
- input.clearVirtual(source);
1066
- knob.style.transform = "";
1097
+ reset();
1067
1098
  };
1068
1099
  root.addEventListener("pointerdown", onDown);
1069
1100
  root.addEventListener("pointermove", onMove);
1070
1101
  root.addEventListener("pointerup", onUp);
1071
1102
  root.addEventListener("pointercancel", onUp);
1103
+ root.addEventListener("lostpointercapture", onUp);
1104
+ document.defaultView?.addEventListener("blur", reset);
1072
1105
  return {
1073
1106
  element: root,
1074
1107
  stick,
1075
1108
  setVisible(visible) {
1076
1109
  root.style.display = visible ? "" : "none";
1077
- if (!visible) {
1078
- pointer = void 0;
1079
- stick.release();
1080
- input.clearVirtual(source);
1081
- }
1110
+ if (!visible) reset();
1082
1111
  },
1083
1112
  dispose() {
1084
1113
  root.removeEventListener("pointerdown", onDown);
1085
1114
  root.removeEventListener("pointermove", onMove);
1086
1115
  root.removeEventListener("pointerup", onUp);
1087
1116
  root.removeEventListener("pointercancel", onUp);
1088
- input.clearVirtual(source);
1117
+ root.removeEventListener("lostpointercapture", onUp);
1118
+ document.defaultView?.removeEventListener("blur", reset);
1119
+ reset();
1089
1120
  root.remove();
1090
1121
  }
1091
1122
  };
@@ -297,6 +297,8 @@ declare class WebGpuSceneOptimizer {
297
297
  private readonly renderHook;
298
298
  private readonly groups;
299
299
  private active;
300
+ /** Bundled groups set aside between frames; see `finish`. */
301
+ private suspended;
300
302
  private frame;
301
303
  private stableCameraFrames;
302
304
  private cameraState;
@@ -459,11 +461,15 @@ declare class Renderer {
459
461
  private readonly optimizer;
460
462
  private activeSky;
461
463
  private readonly reflections;
464
+ /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
465
+ private readonly webgpuShadowLights;
462
466
  private readonly reflectionClearColor;
463
467
  private starCatalog;
464
468
  private activeWeather;
465
469
  private weatherTimeOverride;
466
470
  private readonly weatherLightIntensities;
471
+ /** The hemisphere the sky reflection map stands in for, and its authored visibility. */
472
+ private hiddenAmbient;
467
473
  private environmentSeconds;
468
474
  private environmentTimeOverride;
469
475
  private readonly lastRenderStats;
@@ -480,6 +486,8 @@ declare class Renderer {
480
486
  setShadowFocus(focus: ShadowFocus | undefined): void;
481
487
  /** Turn sun shadows on at a map resolution, or off, without rebuilding the environment. */
482
488
  setShadowQuality(quality: ShadowQuality): void;
489
+ /** WebGL PCF shadow lookups against a reversed depth buffer; see focusDirectionalShadow. */
490
+ private webglReversedPcfShadows;
483
491
  /** The directional lights standing for the sun: the environment rig's, and the sky's. */
484
492
  private sunLights;
485
493
  private applyShadowFocus;
@@ -559,6 +567,17 @@ declare class Renderer {
559
567
  private compileMesh;
560
568
  private prepareWebGlGeometries;
561
569
  render(): void;
570
+ /**
571
+ * The PMREM supplies both diffuse sky irradiance and specular reflection, so while it is the
572
+ * scene environment the hemisphere it was sampled from must not light surfaces as well. The
573
+ * light is hidden, between frames too, rather than dimmed for the visible draw alone: three's
574
+ * WebGPU renderer updates light uniforms once per frame of its own clock, and warm-up compiles
575
+ * finish between viewer frames, so a light restored after each draw could leave its full
576
+ * intensity in the next frame's uniforms and the whole scene flashed bright for that frame.
577
+ * Its intensity stays the authored value for weather and hosts; it shows again when a host
578
+ * environment takes over or the renderer is disposed.
579
+ */
580
+ private hideReflectedAmbient;
562
581
  private renderScene;
563
582
  /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
564
583
  createRenderGroup(): THREE.Group;
@@ -20,7 +20,7 @@ interface VehicleCameraPose {
20
20
  declare function vehicleCameraPose(transform: {
21
21
  pos: [number, number, number];
22
22
  rot: [number, number, number, number];
23
- }, spec: VehicleSpec, options: VehicleCameraOptions): VehicleCameraPose;
23
+ }, spec: Pick<VehicleSpec, "driverEye" | "length">, options: VehicleCameraOptions): VehicleCameraPose;
24
24
  //#endregion
25
25
  //#region src/vehicle-interior.d.ts
26
26
  type VehicleInteriorSignals = ModelSignals;
@@ -1,4 +1,4 @@
1
- import { t as createModelSignalVisual } from "./model-signals-Gw1COJfo.mjs";
1
+ import { t as createModelSignalVisual } from "./model-signals-Dp5OV-Y0.mjs";
2
2
  //#region src/vehicle-interior.ts
3
3
  /** Vehicle convenience wrapper around the platform's model-signal binding system. */
4
4
  function createVehicleInteriorVisual(model, spec) {
@@ -1,4 +1,5 @@
1
- import { a as VehicleCameraPose, i as VehicleCameraOptions, n as VehicleInteriorVisual, o as vehicleCameraPose, r as createVehicleInteriorVisual, t as VehicleInteriorSignals } from "./vehicle-interior-0o-8QV_-.mjs";
1
+ import { t as ModelSignalVisual } from "./model-signals-DVlLyP-w.mjs";
2
+ import { a as VehicleCameraPose, i as VehicleCameraOptions, n as VehicleInteriorVisual, o as vehicleCameraPose, r as createVehicleInteriorVisual, t as VehicleInteriorSignals } from "./vehicle-interior-GWcXnvXS.mjs";
2
3
  import { VehicleData, VehiclePlacement } from "@bendyline/molen-schema";
3
4
  import * as THREE from "three";
4
5
 
@@ -6,11 +7,26 @@ import * as THREE from "three";
6
7
  interface VehicleVisual {
7
8
  object: THREE.Object3D;
8
9
  interior?: VehicleInteriorVisual;
10
+ /** The visual's exterior `animation` bindings, posed from the same signals as the interior. */
11
+ animation?: ModelSignalVisual;
9
12
  update(steer: number, wheelAngle: number, signals?: VehicleInteriorSignals): void;
10
13
  dispose(): void;
11
14
  }
12
- /** Bind a loaded entity GLB to generic wheel/steering animation using external node names. */
13
- declare function createVehicleVisual(model: THREE.Object3D, vehicle: VehicleData): VehicleVisual;
15
+ /**
16
+ * Bind a loaded entity GLB to generic wheel/steering animation using external node names.
17
+ *
18
+ * The simulation leans the whole model with its sprung body (`vehicleState.bodyRoll` and
19
+ * `bodyPitch`). Given those as signals, the wheels take up the lean as suspension travel instead:
20
+ * each moves along the body's up axis to keep its centre at its resting height, so the outside
21
+ * wheels stay on the road in a turn rather than sinking into it.
22
+ */
23
+ declare function createVehicleVisual(model: THREE.Object3D, vehicle: Pick<VehicleData, "visual"> & {
24
+ color?: string;
25
+ spec?: {
26
+ length: number;
27
+ cycle?: unknown;
28
+ };
29
+ }): VehicleVisual;
14
30
  /** The dimensions a vehicle proxy is built from (a `VehicleSpec` satisfies it). */
15
31
  interface VehicleProxyDimensions {
16
32
  width: number;
package/dist/vehicles.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { t as createVehicleInteriorVisual } from "./vehicle-interior-DZT0HmWC.mjs";
1
+ import { t as createModelSignalVisual } from "./model-signals-Dp5OV-Y0.mjs";
2
+ import { t as createVehicleInteriorVisual } from "./vehicle-interior-vJQsRLQy.mjs";
2
3
  import * as THREE from "three";
3
4
  import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
4
5
  //#region src/vehicle-camera.ts
@@ -29,9 +30,21 @@ function vehicleCameraPose(transform, spec, options) {
29
30
  }
30
31
  //#endregion
31
32
  //#region src/vehicles.ts
32
- /** Bind a loaded entity GLB to generic wheel/steering animation using external node names. */
33
+ const bodyLean = new THREE.Quaternion();
34
+ const leanEuler = new THREE.Euler(0, 0, 0, "YXZ");
35
+ const leaned = new THREE.Vector3();
36
+ const travel = new THREE.Vector3();
37
+ /**
38
+ * Bind a loaded entity GLB to generic wheel/steering animation using external node names.
39
+ *
40
+ * The simulation leans the whole model with its sprung body (`vehicleState.bodyRoll` and
41
+ * `bodyPitch`). Given those as signals, the wheels take up the lean as suspension travel instead:
42
+ * each moves along the body's up axis to keep its centre at its resting height, so the outside
43
+ * wheels stay on the road in a turn rather than sinking into it.
44
+ */
33
45
  function createVehicleVisual(model, vehicle) {
34
46
  const interior = vehicle.visual.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, vehicle.visual.interior);
47
+ const animation = vehicle.visual.animation === void 0 ? void 0 : createModelSignalVisual(model, vehicle.visual.animation);
35
48
  const nodes = /* @__PURE__ */ new Map();
36
49
  const frontWheels = new Set(vehicle.visual.frontWheelNodes);
37
50
  const wheels = [];
@@ -53,27 +66,47 @@ function createVehicleVisual(model, vehicle) {
53
66
  object.material = Array.isArray(object.material) ? cloned : cloned[0];
54
67
  }
55
68
  });
56
- for (const name of vehicle.visual.wheelNodes) for (const node of nodes.get(name) ?? []) wheels.push({
57
- node,
58
- front: frontWheels.has(name),
59
- baseY: node.rotation.y
60
- });
69
+ model.updateMatrixWorld(true);
70
+ const toModel = new THREE.Matrix4().copy(model.matrixWorld).invert();
71
+ for (const name of vehicle.visual.wheelNodes) for (const node of nodes.get(name) ?? []) {
72
+ const parent = new THREE.Matrix4().multiplyMatrices(toModel, node.parent?.matrixWorld ?? model.matrixWorld);
73
+ wheels.push({
74
+ node,
75
+ front: frontWheels.has(name),
76
+ baseY: node.rotation.y,
77
+ rest: node.position.clone(),
78
+ center: node.getWorldPosition(new THREE.Vector3()).applyMatrix4(toModel),
79
+ toParent: new THREE.Quaternion().setFromRotationMatrix(parent).invert()
80
+ });
81
+ }
61
82
  if (vehicle.visual.steeringWheelNode !== void 0) steeringWheel = nodes.get(vehicle.visual.steeringWheelNode)?.[0];
62
83
  return {
63
84
  object: model,
64
85
  interior,
86
+ animation,
65
87
  update(steer, angle, signals) {
88
+ const roll = signals?.bodyRoll ?? 0;
89
+ const pitch = signals?.bodyPitch ?? 0;
90
+ const lean = Number.isFinite(roll) && Number.isFinite(pitch) && (roll !== 0 || pitch !== 0);
91
+ if (lean) bodyLean.setFromEuler(leanEuler.set(pitch, 0, roll));
66
92
  for (const wheel of wheels) {
67
93
  wheel.node.rotation.y = wheel.baseY + (wheel.front ? -steer : 0);
68
94
  const spinner = wheel.node.children[0] ?? wheel.node;
69
95
  spinner.rotation.x = angle;
96
+ wheel.node.position.copy(wheel.rest);
97
+ if (!lean || vehicle.spec?.cycle !== void 0) continue;
98
+ const up = travel.set(0, 1, 0).applyQuaternion(bodyLean).y;
99
+ const lift = (wheel.center.y - leaned.copy(wheel.center).applyQuaternion(bodyLean).y) / up;
100
+ wheel.node.position.add(travel.set(0, lift, 0).applyQuaternion(wheel.toParent));
70
101
  }
71
102
  if (interior === void 0 && steeringWheel !== void 0) steeringWheel.rotation.z = steer * 2.5;
72
- interior?.update({
103
+ const telemetry = {
73
104
  steering: steer,
74
105
  wheelAngle: angle,
75
106
  ...signals
76
- });
107
+ };
108
+ interior?.update(telemetry);
109
+ animation?.update(telemetry);
77
110
  },
78
111
  dispose() {
79
112
  const geometries = /* @__PURE__ */ new Set();
@@ -76,6 +76,8 @@ var WebGpuSceneOptimizer = class {
76
76
  renderHook;
77
77
  groups = /* @__PURE__ */ new WeakSet();
78
78
  active = [];
79
+ /** Bundled groups set aside between frames; see `finish`. */
80
+ suspended = [];
79
81
  frame = 0;
80
82
  stableCameraFrames = 0;
81
83
  cameraState = [];
@@ -92,7 +94,7 @@ var WebGpuSceneOptimizer = class {
92
94
  const refresh = nodes.needsRefresh;
93
95
  nodes.needsRefresh = (object) => {
94
96
  const group = object.bundle;
95
- if (group !== null && this.groups.has(group) && group.eligible && group.version === group.recordedVersion && !renderer.getMRT()?.has("velocity")) {
97
+ if (group !== null && this.groups.has(group) && group.eligible && group.version === group.recordedVersion && !renderer.shadowMap.enabled && !renderer.getMRT()?.has("velocity")) {
96
98
  const monitor = object.getMonitor();
97
99
  if (!monitor.hasNode && !monitor.hasAnimation && monitor.renderObjects.has(object)) return false;
98
100
  }
@@ -131,6 +133,8 @@ var WebGpuSceneOptimizer = class {
131
133
  /** Update matrices once; Renderer suppresses Three's duplicate scene traversal for this frame. */
132
134
  prepare(scene, camera) {
133
135
  this.frame++;
136
+ for (const group of this.suspended) Object.assign(group, { isBundleGroup: true });
137
+ this.suspended = [];
134
138
  this.active = [];
135
139
  this.materialSamples.clear();
136
140
  if (scene.matrixWorldAutoUpdate) scene.updateMatrixWorld();
@@ -155,6 +159,8 @@ var WebGpuSceneOptimizer = class {
155
159
  scene.environmentIntensity,
156
160
  this.renderer.toneMapping,
157
161
  this.renderer.toneMappingExposure,
162
+ this.renderer.shadowMap.enabled,
163
+ this.renderer.shadowMap.type,
158
164
  this.renderer.outputColorSpace,
159
165
  this.frameSize.x,
160
166
  this.frameSize.y,
@@ -175,6 +181,8 @@ var WebGpuSceneOptimizer = class {
175
181
  if (object instanceof THREE.Light) {
176
182
  lights.push(object, ...object.matrixWorld.elements);
177
183
  for (const value of Object.values(object)) this.sampleValue(lights, value);
184
+ const shadow = object.shadow;
185
+ if (shadow !== void 0) lights.push(object.castShadow, shadow.mapSize.x, shadow.mapSize.y, shadow.map);
178
186
  }
179
187
  if (object instanceof THREE.DirectionalLight || object instanceof THREE.SpotLight) {
180
188
  lights.push(...object.target.matrixWorld.elements);
@@ -189,7 +197,7 @@ var WebGpuSceneOptimizer = class {
189
197
  own.cursor = 0;
190
198
  own.changed = false;
191
199
  own.writeArray(view);
192
- own.eligible = cacheView && !this.renderer.shadowMap.enabled && scene.overrideMaterial === null && scene.onBeforeRender === THREE.Object3D.prototype.onBeforeRender && this.renderer.getRenderObjectFunction() === this.renderHook && this.renderer.xr?.isPresenting !== true;
200
+ own.eligible = cacheView && scene.overrideMaterial === null && scene.onBeforeRender === THREE.Object3D.prototype.onBeforeRender && this.renderer.getRenderObjectFunction() === this.renderHook && this.renderer.xr?.isPresenting !== true;
193
201
  this.active.push(own);
194
202
  }
195
203
  if (group !== void 0 && cacheView) {
@@ -257,6 +265,11 @@ var WebGpuSceneOptimizer = class {
257
265
  };
258
266
  group.recordedVersion = group.version;
259
267
  }
268
+ for (const group of this.active) {
269
+ if (!group.isBundleGroup) continue;
270
+ Object.assign(group, { isBundleGroup: false });
271
+ this.suspended.push(group);
272
+ }
260
273
  }
261
274
  sampleMatrix(matrix) {
262
275
  let sample = this.matrixSamples.get(matrix);
@@ -312,6 +325,7 @@ var WebGpuSceneOptimizer = class {
312
325
  this.restoreRefresh();
313
326
  this.instances.dispose();
314
327
  this.active = [];
328
+ this.suspended = [];
315
329
  this.materialSamples.clear();
316
330
  }
317
331
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/molen-client",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -68,8 +68,8 @@
68
68
  ],
69
69
  "dependencies": {
70
70
  "zod": "^4.6.5",
71
- "@bendyline/molen-materials": "0.0.6",
72
- "@bendyline/molen-schema": "0.0.5"
71
+ "@bendyline/molen-materials": "0.0.8",
72
+ "@bendyline/molen-schema": "0.0.7"
73
73
  },
74
74
  "peerDependencies": {
75
75
  "@types/three": ">=0.184.0 <0.187.0",