@bendyline/molen-client 0.0.8 → 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-DPT7XAYh.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-DPT7XAYh.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;
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);
@@ -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();
@@ -3580,6 +3634,8 @@ var Renderer = class Renderer {
3580
3634
  activeWeather;
3581
3635
  weatherTimeOverride;
3582
3636
  weatherLightIntensities = /* @__PURE__ */ new WeakMap();
3637
+ /** The hemisphere the sky reflection map stands in for, and its authored visibility. */
3638
+ hiddenAmbient;
3583
3639
  environmentSeconds = 0;
3584
3640
  environmentTimeOverride;
3585
3641
  lastRenderStats = {
@@ -4258,11 +4314,10 @@ var Renderer = class Renderer {
4258
4314
  this.reflections.update(sky?.reflectionState ?? reflectionStateFromLights(ambient, sun, this.three.getClearColor(this.reflectionClearColor), weather?.cloudAttenuation ?? 0));
4259
4315
  if (this.reflections.active) reflectedAmbient = sky?.ambientLight ?? ambient;
4260
4316
  }
4261
- const ambientIntensity = reflectedAmbient?.intensity;
4317
+ this.hideReflectedAmbient(reflectedAmbient);
4262
4318
  const baseFog = this.scene.fog;
4263
4319
  if (weather) this.scene.fog = weather.fogFor(baseFog, sky?.frame);
4264
4320
  try {
4265
- if (reflectedAmbient) reflectedAmbient.intensity = 0;
4266
4321
  if (sky) {
4267
4322
  sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
4268
4323
  sky.prepareCamera(this.camera);
@@ -4287,10 +4342,32 @@ var Renderer = class Renderer {
4287
4342
  this.lastRenderStats.drawCalls = "drawCalls" in info ? info.drawCalls : info.calls;
4288
4343
  this.lastRenderStats.triangles = info.triangles;
4289
4344
  } finally {
4290
- if (reflectedAmbient && ambientIntensity !== void 0) reflectedAmbient.intensity = ambientIntensity;
4291
4345
  this.scene.fog = baseFog;
4292
4346
  }
4293
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
+ }
4294
4371
  renderScene() {
4295
4372
  if (this.optimizer === void 0) {
4296
4373
  this.three.render(this.scene, this.camera);
@@ -4336,6 +4413,7 @@ var Renderer = class Renderer {
4336
4413
  this.activeWeather?.dispose();
4337
4414
  this.activeWeather = void 0;
4338
4415
  this.reflections?.dispose();
4416
+ this.hideReflectedAmbient(void 0);
4339
4417
  findEnvironmentRig(this.scene)?.traverse((object) => {
4340
4418
  if (object instanceof THREE.Light) object.dispose();
4341
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
  };
@@ -468,6 +468,8 @@ declare class Renderer {
468
468
  private activeWeather;
469
469
  private weatherTimeOverride;
470
470
  private readonly weatherLightIntensities;
471
+ /** The hemisphere the sky reflection map stands in for, and its authored visibility. */
472
+ private hiddenAmbient;
471
473
  private environmentSeconds;
472
474
  private environmentTimeOverride;
473
475
  private readonly lastRenderStats;
@@ -565,6 +567,17 @@ declare class Renderer {
565
567
  private compileMesh;
566
568
  private prepareWebGlGeometries;
567
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;
568
581
  private renderScene;
569
582
  /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
570
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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/molen-client",
3
- "version": "0.0.8",
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.7",
72
- "@bendyline/molen-schema": "0.0.6"
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",