@bendyline/molen-client 0.0.10 → 0.0.12

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,4 +1,5 @@
1
- import { t as InputMap } from "./input-BVZjf4T-.mjs";
1
+ import { t as InputMap } from "./input-BliZYUY1.mjs";
2
+ import { boostSpeedMultiplier } from "@bendyline/molen-schema";
2
3
  import * as THREE from "three";
3
4
  import { Octree } from "three/addons/math/Octree.js";
4
5
  import { Capsule } from "three/addons/math/Capsule.js";
@@ -177,126 +178,6 @@ function selectMedian({ centers, order }, axis, left, right, k) {
177
178
  }
178
179
  }
179
180
  //#endregion
180
- //#region src/navigation/fly.ts
181
- var FlyController = class {
182
- position;
183
- /** Engine yaw: 0 faces +X (east), -PI/2 faces north. */
184
- yaw;
185
- /** Radians above the horizon (negative looks down). */
186
- pitch;
187
- minSpeed;
188
- speedPerMeter;
189
- sprintFactor;
190
- minClearance;
191
- lookSensitivity;
192
- constructor(position, orientation, options = {}) {
193
- this.position = [...position];
194
- this.yaw = orientation.yaw;
195
- this.pitch = orientation.pitch;
196
- this.minSpeed = options.minSpeed ?? 12;
197
- this.speedPerMeter = options.speedPerMeter ?? 1.2;
198
- this.sprintFactor = options.sprintFactor ?? 4;
199
- this.minClearance = options.minClearance ?? 2;
200
- this.lookSensitivity = options.lookSensitivity ?? .003;
201
- }
202
- update(dt, input, environment) {
203
- const step = Math.max(0, Math.min(.1, dt));
204
- const turned = applyCameraLookDelta(this.yaw, this.pitch, input.look[0], input.look[1], this.lookSensitivity);
205
- this.yaw = turned.yaw;
206
- this.pitch = turned.pitch;
207
- const ground = environment.groundHeight(this.position[0], this.position[2]);
208
- const aboveGround = ground === void 0 ? 100 : Math.max(0, this.position[1] - ground);
209
- const speed = Math.max(this.minSpeed, aboveGround * this.speedPerMeter) * (input.sprint ? this.sprintFactor : 1) * step;
210
- const forward = cameraPlanarForward(this.yaw);
211
- const right = cameraRight(this.yaw);
212
- const { move } = input;
213
- for (let axis = 0; axis < 3; axis++) this.position[axis] = this.position[axis] + (forward[axis] * move.forward + right[axis] * move.right) * speed;
214
- this.position[1] += move.up * speed;
215
- const floor = environment.groundHeight(this.position[0], this.position[2]);
216
- if (floor !== void 0 && this.position[1] < floor + this.minClearance) this.position[1] = floor + this.minClearance;
217
- const direction = cameraForward(this.yaw, this.pitch);
218
- return {
219
- position: [...this.position],
220
- lookAt: [
221
- this.position[0] + direction[0],
222
- this.position[1] + direction[1],
223
- this.position[2] + direction[2]
224
- ],
225
- direction
226
- };
227
- }
228
- };
229
- //#endregion
230
- //#region src/navigation/follow.ts
231
- var FollowController = class {
232
- position;
233
- yawOffset = 0;
234
- pitchOffset = 0;
235
- distance;
236
- height;
237
- lookHeight;
238
- smoothing;
239
- recenter;
240
- minClearance;
241
- constructor(options = {}) {
242
- this.distance = options.distance ?? 6;
243
- this.height = options.height ?? 2.2;
244
- this.lookHeight = options.lookHeight ?? 1.2;
245
- this.smoothing = options.smoothing ?? .18;
246
- this.recenter = options.recenter ?? 1.5;
247
- this.minClearance = options.minClearance ?? .6;
248
- }
249
- /** Snap next frame instead of easing (after a teleport or a subject change). */
250
- reset() {
251
- this.position = void 0;
252
- this.yawOffset = 0;
253
- this.pitchOffset = 0;
254
- }
255
- update(dt, subject, input, environment) {
256
- const step = Math.max(0, Math.min(.1, dt));
257
- const looking = input.look[0] !== 0 || input.look[1] !== 0;
258
- this.yawOffset = Math.max(-Math.PI, Math.min(Math.PI, this.yawOffset - input.look[0] * .005));
259
- this.pitchOffset = Math.max(-.35, Math.min(.9, this.pitchOffset + input.look[1] * .004));
260
- if (!looking && this.recenter > 0) {
261
- const decay = Math.exp(-step / this.recenter);
262
- this.yawOffset *= decay;
263
- this.pitchOffset *= decay;
264
- }
265
- const heading = subject.heading + this.yawOffset;
266
- const lookAt = [
267
- subject.position[0],
268
- subject.position[1] + this.lookHeight,
269
- subject.position[2]
270
- ];
271
- const reach = this.distance * Math.cos(this.pitchOffset);
272
- const ideal = [
273
- subject.position[0] - Math.sin(heading) * reach,
274
- subject.position[1] + this.height + this.distance * Math.sin(this.pitchOffset),
275
- subject.position[2] + Math.cos(heading) * reach
276
- ];
277
- if (this.position === void 0) this.position = [...ideal];
278
- else {
279
- const blend = this.smoothing <= 0 ? 1 : 1 - Math.exp(-step / this.smoothing);
280
- for (let axis = 0; axis < 3; axis++) this.position[axis] = this.position[axis] + (ideal[axis] - this.position[axis]) * blend;
281
- }
282
- const ground = environment.groundHeight(this.position[0], this.position[2]);
283
- if (ground !== void 0 && this.position[1] < ground + this.minClearance) this.position[1] = ground + this.minClearance;
284
- const dx = lookAt[0] - this.position[0];
285
- const dy = lookAt[1] - this.position[1];
286
- const dz = lookAt[2] - this.position[2];
287
- const length = Math.hypot(dx, dy, dz) || 1;
288
- return {
289
- position: [...this.position],
290
- lookAt,
291
- direction: [
292
- dx / length,
293
- dy / length,
294
- dz / length
295
- ]
296
- };
297
- }
298
- };
299
- //#endregion
300
181
  //#region src/navigation/pointer.ts
301
182
  function emptyGestures() {
302
183
  return {
@@ -478,8 +359,10 @@ const NAVIGATION_ACTIONS = {
478
359
  jump: "nav-jump",
479
360
  interact: "nav-interact",
480
361
  view: "nav-view",
362
+ boost: "nav-boost",
481
363
  throttleUp: "nav-throttle-up",
482
364
  throttleDown: "nav-throttle-down",
365
+ power: "nav-power",
483
366
  yawLeft: "nav-yaw-left",
484
367
  yawRight: "nav-yaw-right",
485
368
  engine: "nav-engine",
@@ -488,6 +371,20 @@ const NAVIGATION_ACTIONS = {
488
371
  vector: "nav-vector",
489
372
  recover: "nav-recover"
490
373
  };
374
+ const ACTUATOR_KEYS = {
375
+ KeyB: "speedBrake",
376
+ KeyH: "tailHook",
377
+ KeyO: "canopy",
378
+ KeyK: "wipers",
379
+ KeyL: "headlights",
380
+ Digit1: "doorFrontLeft",
381
+ Digit2: "doorFrontRight",
382
+ Digit3: "doorRearLeft",
383
+ Digit4: "doorRearRight",
384
+ Digit5: "hood",
385
+ Digit6: "trunk"
386
+ };
387
+ const ACTUATOR_BINDINGS = Object.fromEntries(Object.entries(ACTUATOR_KEYS).map(([key, name]) => [key, `nav-actuator-${name}`]));
491
388
  const A = NAVIGATION_ACTIONS;
492
389
  const MOVE_KEYS = {
493
390
  KeyW: A.forward,
@@ -547,9 +444,10 @@ const STICKS = [
547
444
  * Default key/gamepad bindings per navigation mode. Orbit and fly use Q/E for down/up; walk and
548
445
  * drive use E to interact (board or leave a vehicle), Space to jump or brake, Shift to sprint
549
446
  * 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 ←/→)
550
- * bank, Q/Z work the rudder or pedals, Shift/Ctrl (or +/−, Page Up/Down) set throttle or
447
+ * bank, Z/C work the rudder or pedals, =/− (or numpad +/−, Page Up/Down) set throttle or
551
448
  * collective, I toggles the engine, G the gear, F the flaps, R recovers after an impact, Space
552
- * brakes, V switches the view and E leaves. Hosts may replace any profile through
449
+ * brakes, V switches the view and E leaves. T toggles travel boost in walk, drive and pilot.
450
+ * Hosts may replace any profile through
553
451
  * `InputMap.defineProfile`.
554
452
  */
555
453
  function navigationInputProfiles() {
@@ -583,7 +481,8 @@ function navigationInputProfiles() {
583
481
  Space: A.jump,
584
482
  KeyE: A.interact,
585
483
  KeyF: A.interact,
586
- KeyV: A.view
484
+ KeyV: A.view,
485
+ KeyT: A.boost
587
486
  },
588
487
  axes: STICKS,
589
488
  buttons: [
@@ -605,78 +504,84 @@ function navigationInputProfiles() {
605
504
  }
606
505
  ]
607
506
  };
507
+ const pilot = {
508
+ bindings: {
509
+ ...ACTUATOR_BINDINGS,
510
+ KeyW: A.forward,
511
+ ArrowUp: A.forward,
512
+ KeyS: A.back,
513
+ ArrowDown: A.back,
514
+ KeyA: A.left,
515
+ ArrowLeft: A.left,
516
+ KeyD: A.right,
517
+ ArrowRight: A.right,
518
+ KeyZ: A.yawLeft,
519
+ KeyC: A.yawRight,
520
+ Equal: A.throttleUp,
521
+ NumpadAdd: A.throttleUp,
522
+ PageUp: A.throttleUp,
523
+ Minus: A.throttleDown,
524
+ NumpadSubtract: A.throttleDown,
525
+ PageDown: A.throttleDown,
526
+ Space: A.jump,
527
+ KeyE: A.interact,
528
+ KeyV: A.view,
529
+ KeyT: A.boost,
530
+ KeyI: A.engine,
531
+ KeyG: A.gear,
532
+ KeyF: A.flaps,
533
+ KeyJ: A.vector,
534
+ KeyR: A.recover
535
+ },
536
+ axes: STICKS,
537
+ buttons: [
538
+ {
539
+ button: 7,
540
+ action: A.throttleUp
541
+ },
542
+ {
543
+ button: 6,
544
+ action: A.throttleDown
545
+ },
546
+ {
547
+ button: 4,
548
+ action: A.yawLeft
549
+ },
550
+ {
551
+ button: 5,
552
+ action: A.yawRight
553
+ },
554
+ {
555
+ button: 0,
556
+ action: A.jump
557
+ },
558
+ {
559
+ button: 2,
560
+ action: A.interact
561
+ },
562
+ {
563
+ button: 3,
564
+ action: A.view
565
+ },
566
+ {
567
+ button: 1,
568
+ action: A.engine
569
+ }
570
+ ]
571
+ };
608
572
  return {
609
573
  orbit: aerial,
610
574
  fly: aerial,
611
575
  walk: ground,
612
- drive: ground,
613
- pilot: {
576
+ drive: {
577
+ ...ground,
614
578
  bindings: {
615
- KeyW: A.forward,
616
- ArrowUp: A.forward,
617
- KeyS: A.back,
618
- ArrowDown: A.back,
619
- KeyA: A.left,
620
- ArrowLeft: A.left,
621
- KeyD: A.right,
622
- ArrowRight: A.right,
623
- KeyQ: A.yawLeft,
624
- KeyZ: A.yawRight,
625
- ShiftLeft: A.throttleUp,
626
- ShiftRight: A.throttleUp,
627
- Equal: A.throttleUp,
628
- NumpadAdd: A.throttleUp,
629
- PageUp: A.throttleUp,
630
- ControlLeft: A.throttleDown,
631
- ControlRight: A.throttleDown,
632
- Minus: A.throttleDown,
633
- NumpadSubtract: A.throttleDown,
634
- PageDown: A.throttleDown,
635
- Space: A.jump,
636
- KeyE: A.interact,
637
- KeyV: A.view,
638
- KeyI: A.engine,
639
- KeyG: A.gear,
640
- KeyF: A.flaps,
641
- KeyJ: A.vector,
579
+ ...ground.bindings,
580
+ ...ACTUATOR_BINDINGS,
642
581
  KeyR: A.recover
643
- },
644
- axes: STICKS,
645
- buttons: [
646
- {
647
- button: 7,
648
- action: A.throttleUp
649
- },
650
- {
651
- button: 6,
652
- action: A.throttleDown
653
- },
654
- {
655
- button: 4,
656
- action: A.yawLeft
657
- },
658
- {
659
- button: 5,
660
- action: A.yawRight
661
- },
662
- {
663
- button: 0,
664
- action: A.jump
665
- },
666
- {
667
- button: 2,
668
- action: A.interact
669
- },
670
- {
671
- button: 3,
672
- action: A.view
673
- },
674
- {
675
- button: 1,
676
- action: A.engine
677
- }
678
- ]
679
- }
582
+ }
583
+ },
584
+ pilot
680
585
  };
681
586
  }
682
587
  /** An input with no intent; controllers treat it as "hold still". */
@@ -707,6 +612,8 @@ var NavigationInputSource = class {
707
612
  pointer;
708
613
  interactPresses = 0;
709
614
  viewPresses = 0;
615
+ boostPresses = 0;
616
+ actuatorPresses = {};
710
617
  profile;
711
618
  pilotPresses = {
712
619
  engine: 0,
@@ -730,6 +637,9 @@ var NavigationInputSource = class {
730
637
  this.lookSpeed = options.gamepadLookSpeed ?? 900;
731
638
  this.profile = options.profile ?? "orbit";
732
639
  this.unsubscribe = [
640
+ ...Object.values(ACTUATOR_KEYS).map((name) => this.map.onPress(`nav-actuator-${name}`, () => {
641
+ this.actuatorPresses[name] = (this.actuatorPresses[name] ?? 0) + 1;
642
+ })),
733
643
  ...[
734
644
  "engine",
735
645
  "gear",
@@ -745,10 +655,15 @@ var NavigationInputSource = class {
745
655
  this.map.onPress(A.view, () => {
746
656
  this.viewPresses++;
747
657
  }),
658
+ this.map.onPress(A.boost, () => {
659
+ this.boostPresses++;
660
+ }),
748
661
  this.map.onReset(() => {
749
662
  this.pointer.reset();
750
663
  this.interactPresses = 0;
751
664
  this.viewPresses = 0;
665
+ this.boostPresses = 0;
666
+ this.actuatorPresses = {};
752
667
  this.pilotPresses.engine = 0;
753
668
  this.pilotPresses.gear = 0;
754
669
  this.pilotPresses.flaps = 0;
@@ -794,8 +709,12 @@ var NavigationInputSource = class {
794
709
  jump: v(A.jump) !== 0,
795
710
  interact: this.interactPresses,
796
711
  view: this.viewPresses,
712
+ ...this.boostPresses > 0 ? { boost: this.boostPresses } : {},
797
713
  taps: gestures.taps,
714
+ ...Object.keys(this.actuatorPresses).length ? { actuators: { ...this.actuatorPresses } } : {},
715
+ ...this.profile === "drive" && this.pilotPresses.recover > 0 ? { recover: this.pilotPresses.recover } : {},
798
716
  ...this.profile === "pilot" ? { pilot: {
717
+ ...this.map.hasAxis(A.power) ? { power: v(A.power) } : {},
799
718
  throttle: v(A.throttleUp) - v(A.throttleDown),
800
719
  yaw: v(A.yawRight) - v(A.yawLeft),
801
720
  ...this.pilotPresses
@@ -803,11 +722,13 @@ var NavigationInputSource = class {
803
722
  };
804
723
  this.interactPresses = 0;
805
724
  this.viewPresses = 0;
725
+ this.boostPresses = 0;
806
726
  this.pilotPresses.engine = 0;
807
727
  this.pilotPresses.gear = 0;
808
728
  this.pilotPresses.flaps = 0;
809
729
  this.pilotPresses.vector = 0;
810
730
  this.pilotPresses.recover = 0;
731
+ this.actuatorPresses = {};
811
732
  return input;
812
733
  }
813
734
  dispose() {
@@ -817,6 +738,433 @@ var NavigationInputSource = class {
817
738
  }
818
739
  };
819
740
  //#endregion
741
+ //#region src/navigation/controls.ts
742
+ /** Controller discovery and raw axis/button mapping for the built-in navigation profiles. */
743
+ function createNavigationControls(source, options) {
744
+ const map = source.map;
745
+ const doc = options.container.ownerDocument;
746
+ const defaults = new Map(map.profileNames().map((name) => [name, map.getProfile(name)]));
747
+ let storageMessage = "";
748
+ if (options.storageKey) try {
749
+ const saved = JSON.parse(doc.defaultView?.localStorage.getItem(options.storageKey) ?? "null");
750
+ if (saved && typeof saved === "object") {
751
+ for (const name of map.profileNames()) if (Object.hasOwn(saved, name)) try {
752
+ map.defineProfile(name, saved[name]);
753
+ } catch {
754
+ storageMessage = "Some saved mappings were invalid; defaults were restored.";
755
+ }
756
+ }
757
+ } catch {
758
+ storageMessage = "Saved controls could not be loaded. You can still remap this session.";
759
+ }
760
+ const button = (text, parent, action) => {
761
+ const element = doc.createElement("button");
762
+ element.type = "button";
763
+ element.textContent = text;
764
+ element.addEventListener("click", action);
765
+ parent.append(element);
766
+ return element;
767
+ };
768
+ const dialog = doc.createElement("dialog");
769
+ dialog.setAttribute("aria-label", "Joystick and controller settings");
770
+ dialog.className = "molen-navigation-controls";
771
+ dialog.style.cssText = "box-sizing:border-box;width:min(600px,calc(100vw - 24px));max-height:85vh;overflow:auto;padding:20px;border:1px solid #607b8a;border-radius:12px;background:#162b38;color:#e1edf4;font:14px/1.5 system-ui;color-scheme:dark";
772
+ const heading = doc.createElement("h2");
773
+ heading.textContent = "Joystick and controller settings";
774
+ dialog.append(heading);
775
+ const status = doc.createElement("p");
776
+ status.setAttribute("role", "status");
777
+ const hint = doc.createElement("p");
778
+ hint.textContent = "Press a controller button to let the browser detect it. Move each axis to identify its number below. Controls are suspended while this editor is open.";
779
+ dialog.append(status, hint);
780
+ const select = (text) => {
781
+ const label = doc.createElement("label");
782
+ label.style.cssText = "display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:10px 0;color:inherit;font:inherit";
783
+ label.append(`${text} `);
784
+ const field = doc.createElement("select");
785
+ field.setAttribute("aria-label", text);
786
+ field.style.cssText = "max-width:100%;min-width:0;font:inherit";
787
+ label.append(field);
788
+ dialog.append(label);
789
+ return field;
790
+ };
791
+ const option = (field, value, text) => {
792
+ const item = doc.createElement("option");
793
+ item.value = value;
794
+ item.textContent = text;
795
+ field.append(item);
796
+ };
797
+ const profile = select("Profile");
798
+ for (const name of map.profileNames()) option(profile, name, name === "pilot" ? "pilot (aircraft)" : name);
799
+ const device = select("Controller");
800
+ const raw = doc.createElement("pre");
801
+ raw.style.cssText = "white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px";
802
+ dialog.append(raw);
803
+ const axis = select("Axis");
804
+ const axisAction = select("Axis action");
805
+ const invertLabel = doc.createElement("label");
806
+ const invert = doc.createElement("input");
807
+ invert.type = "checkbox";
808
+ invertLabel.append(invert, " Reverse axis");
809
+ dialog.append(invertLabel);
810
+ const zoneLabel = doc.createElement("label");
811
+ zoneLabel.style.cssText = "display:block;margin:10px 0";
812
+ zoneLabel.append("Dead zone ");
813
+ const zone = doc.createElement("input");
814
+ zone.type = "number";
815
+ zone.min = "0";
816
+ zone.max = "0.9";
817
+ zone.step = "0.01";
818
+ zone.value = "0.12";
819
+ zone.style.width = "6em";
820
+ zoneLabel.append(zone);
821
+ dialog.append(zoneLabel);
822
+ const bindings = doc.createElement("div");
823
+ const feedback = doc.createElement("p");
824
+ feedback.setAttribute("role", "status");
825
+ feedback.textContent = storageMessage;
826
+ let pairs = [];
827
+ let resume;
828
+ let deviceSignature = "";
829
+ let controlSignature = "";
830
+ const currentDevice = () => map.devices().find((pad) => String(pad.index) === device.value);
831
+ const renderBindings = () => {
832
+ bindings.replaceChildren();
833
+ const current = map.getProfile(profile.value);
834
+ for (const kind of ["axes", "buttons"]) current[kind]?.forEach((binding, index) => {
835
+ const row = doc.createElement("p");
836
+ row.style.cssText = "font-size:12px;overflow-wrap:anywhere";
837
+ row.append(`${"axis" in binding ? `Axis ${binding.axis} (${binding.mode ?? "signed"}${binding.invert ? ", reversed" : ""})` : `Button ${binding.button}`} → ${binding.action.replace("nav-", "")} · ${binding.device?.id ?? "any controller"} `);
838
+ button("Remove", row, () => {
839
+ const next = map.getProfile(profile.value);
840
+ next[kind]?.splice(index, 1);
841
+ map.defineProfile(profile.value, next);
842
+ renderBindings();
843
+ });
844
+ bindings.append(row);
845
+ });
846
+ };
847
+ const sameDevice = (binding) => {
848
+ const pad = currentDevice();
849
+ return !!pad && (binding.device?.id === void 0 || binding.device.id === pad.id) && (binding.device?.index === void 0 || binding.device.index === pad.index);
850
+ };
851
+ const bindAxis = button("Assign axis", dialog, () => {
852
+ const pad = currentDevice();
853
+ const deadZone = Number(zone.value);
854
+ if (!pad || !Number.isFinite(deadZone) || deadZone < 0 || deadZone >= 1) {
855
+ feedback.textContent = "Choose a detected controller and a dead zone from 0 to less than 1.";
856
+ return;
857
+ }
858
+ const next = map.getProfile(profile.value);
859
+ const pair = pairs[Number(axisAction.value)];
860
+ const actions = pair ? [pair[1], pair[2]] : [NAVIGATION_ACTIONS.power];
861
+ const index = Number(axis.value);
862
+ next.axes = (next.axes ?? []).filter((binding) => !sameDevice(binding) || binding.axis !== index && !actions.includes(binding.action));
863
+ const common = {
864
+ axis: index,
865
+ device: { id: pad.id },
866
+ invert: invert.checked,
867
+ deadZone
868
+ };
869
+ if (pair) next.axes.push({
870
+ ...common,
871
+ action: pair[1],
872
+ mode: "negative"
873
+ }, {
874
+ ...common,
875
+ action: pair[2],
876
+ mode: "positive"
877
+ });
878
+ else next.axes.push({
879
+ ...common,
880
+ deadZone: 0,
881
+ action: NAVIGATION_ACTIONS.power,
882
+ mode: "unit"
883
+ });
884
+ map.defineProfile(profile.value, next);
885
+ feedback.textContent = "Axis assigned. Close the editor to try it; Save keeps it for next time.";
886
+ renderBindings();
887
+ });
888
+ const padButton = select("Button");
889
+ const buttonAction = select("Button action");
890
+ const bindButton = button("Assign button", dialog, () => {
891
+ const pad = currentDevice();
892
+ if (!pad) return;
893
+ const next = map.getProfile(profile.value);
894
+ const index = Number(padButton.value);
895
+ next.buttons = (next.buttons ?? []).filter((binding) => !sameDevice(binding) || binding.button !== index);
896
+ next.buttons.push({
897
+ button: index,
898
+ action: buttonAction.value,
899
+ device: { id: pad.id }
900
+ });
901
+ map.defineProfile(profile.value, next);
902
+ feedback.textContent = "Button assigned. Close the editor to try it; Save keeps it for next time.";
903
+ renderBindings();
904
+ });
905
+ const updateProfile = () => {
906
+ const pilot = profile.value === "pilot";
907
+ pairs = [
908
+ [
909
+ pilot ? "Pitch (positive = nose up)" : "Forward / backward",
910
+ NAVIGATION_ACTIONS.forward,
911
+ NAVIGATION_ACTIONS.back
912
+ ],
913
+ [
914
+ pilot ? "Roll (positive = right)" : "Left / right",
915
+ NAVIGATION_ACTIONS.left,
916
+ NAVIGATION_ACTIONS.right
917
+ ],
918
+ [
919
+ "Look left / right",
920
+ NAVIGATION_ACTIONS.lookLeft,
921
+ NAVIGATION_ACTIONS.lookRight
922
+ ],
923
+ [
924
+ "Look up / down",
925
+ NAVIGATION_ACTIONS.lookUp,
926
+ NAVIGATION_ACTIONS.lookDown
927
+ ],
928
+ ...pilot ? [[
929
+ "Rudder (positive = right)",
930
+ NAVIGATION_ACTIONS.yawLeft,
931
+ NAVIGATION_ACTIONS.yawRight
932
+ ]] : [[
933
+ "Down / up",
934
+ NAVIGATION_ACTIONS.down,
935
+ NAVIGATION_ACTIONS.up
936
+ ]]
937
+ ];
938
+ axisAction.replaceChildren();
939
+ pairs.forEach((pair, index) => {
940
+ option(axisAction, String(index), pair[0]);
941
+ });
942
+ if (pilot) option(axisAction, "power", "Throttle / collective (absolute lever)");
943
+ buttonAction.replaceChildren();
944
+ const actions = [
945
+ [NAVIGATION_ACTIONS.jump, pilot || profile.value === "drive" ? "Brake" : "Jump"],
946
+ [NAVIGATION_ACTIONS.interact, "Enter / exit vehicle"],
947
+ [NAVIGATION_ACTIONS.view, "Change view"],
948
+ ...pilot ? [
949
+ [NAVIGATION_ACTIONS.throttleUp, "Increase throttle"],
950
+ [NAVIGATION_ACTIONS.throttleDown, "Decrease throttle"],
951
+ [NAVIGATION_ACTIONS.engine, "Engine"],
952
+ [NAVIGATION_ACTIONS.gear, "Landing gear"],
953
+ [NAVIGATION_ACTIONS.flaps, "Flaps"],
954
+ [NAVIGATION_ACTIONS.vector, "Thrust vector"],
955
+ [NAVIGATION_ACTIONS.recover, "Recover"]
956
+ ] : [
957
+ [NAVIGATION_ACTIONS.sprint, "Sprint / handbrake"],
958
+ [NAVIGATION_ACTIONS.up, "Up"],
959
+ [NAVIGATION_ACTIONS.down, "Down"]
960
+ ]
961
+ ];
962
+ for (const [value, label] of actions) option(buttonAction, value, label);
963
+ renderBindings();
964
+ };
965
+ profile.addEventListener("change", updateProfile);
966
+ const mappingDetails = doc.createElement("details");
967
+ const mappingSummary = doc.createElement("summary");
968
+ mappingSummary.textContent = "Current mappings";
969
+ mappingDetails.append(mappingSummary, bindings);
970
+ dialog.append(feedback, mappingDetails);
971
+ button("Save", dialog, () => {
972
+ if (!options.storageKey) return;
973
+ try {
974
+ doc.defaultView?.localStorage.setItem(options.storageKey, JSON.stringify(Object.fromEntries(map.profileNames().map((name) => [name, map.getProfile(name)]))));
975
+ feedback.textContent = "Controls saved on this browser.";
976
+ } catch {
977
+ feedback.textContent = "Browser storage is unavailable. Mappings still work for this session.";
978
+ }
979
+ }).hidden = !options.storageKey;
980
+ button("Reset profile", dialog, () => {
981
+ const original = defaults.get(profile.value);
982
+ if (original) map.defineProfile(profile.value, original);
983
+ feedback.textContent = "Default gamepad mappings restored. Save to keep this reset.";
984
+ renderBindings();
985
+ });
986
+ button("Done", dialog, () => dialog.close());
987
+ const close = () => {
988
+ resume?.();
989
+ resume = void 0;
990
+ options.focusTarget.focus();
991
+ };
992
+ dialog.addEventListener("close", close);
993
+ const open = button("Controllers", options.container, () => {
994
+ profile.value = map.activeProfile ?? map.profileNames()[0] ?? "";
995
+ updateProfile();
996
+ resume = map.suspend();
997
+ doc.exitPointerLock?.();
998
+ dialog.showModal();
999
+ poll();
1000
+ });
1001
+ doc.body.append(dialog);
1002
+ const poll = () => {
1003
+ if (dialog.open) map.update();
1004
+ const pads = map.devices();
1005
+ open.textContent = `Controllers (${pads.length})`;
1006
+ if (!dialog.open) return;
1007
+ const message = map.gamepadStatus === "blocked" ? "Controller access is blocked by the browser or embedding page." : map.gamepadStatus === "unavailable" ? "This browser does not expose controller input. Use HTTPS or localhost in a browser with Gamepad API support." : pads.length ? `${pads.length} controller(s) detected.` : "No controller detected yet. Focus this page and press a controller button.";
1008
+ if (status.textContent !== message) status.textContent = message;
1009
+ const signature = JSON.stringify(pads.map((pad) => [pad.id, pad.index]));
1010
+ if (signature !== deviceSignature) {
1011
+ deviceSignature = signature;
1012
+ const previous = device.value;
1013
+ device.replaceChildren();
1014
+ for (const pad of pads) option(device, String(pad.index), `${pad.id} (#${pad.index})`);
1015
+ if (pads.some((pad) => String(pad.index) === previous)) device.value = previous;
1016
+ }
1017
+ const pad = currentDevice();
1018
+ const controls = JSON.stringify([
1019
+ pad?.id,
1020
+ pad?.index,
1021
+ pad?.axes.length,
1022
+ pad?.buttons.length
1023
+ ]);
1024
+ if (controls !== controlSignature) {
1025
+ controlSignature = controls;
1026
+ axis.replaceChildren();
1027
+ padButton.replaceChildren();
1028
+ pad?.axes.forEach((_, index) => {
1029
+ option(axis, String(index), String(index));
1030
+ });
1031
+ pad?.buttons.forEach((_, index) => {
1032
+ option(padButton, String(index), String(index));
1033
+ });
1034
+ }
1035
+ bindAxis.disabled = !pad?.axes.length;
1036
+ bindButton.disabled = !pad?.buttons.length;
1037
+ raw.textContent = pad ? `Axes: ${pad.axes.map((value, index) => `${index}: ${value.toFixed(2)}`).join(" ")}\nPressed buttons: ${pad.buttons.flatMap((value, index) => value.pressed || value.value > .5 ? [index] : []).join(", ") || "none"}` : "";
1038
+ };
1039
+ const timer = setInterval(poll, 100);
1040
+ return { dispose() {
1041
+ clearInterval(timer);
1042
+ resume?.();
1043
+ dialog.remove();
1044
+ open.remove();
1045
+ } };
1046
+ }
1047
+ //#endregion
1048
+ //#region src/navigation/fly.ts
1049
+ var FlyController = class {
1050
+ position;
1051
+ /** Engine yaw: 0 faces +X (east), -PI/2 faces north. */
1052
+ yaw;
1053
+ /** Radians above the horizon (negative looks down). */
1054
+ pitch;
1055
+ minSpeed;
1056
+ speedPerMeter;
1057
+ sprintFactor;
1058
+ minClearance;
1059
+ lookSensitivity;
1060
+ constructor(position, orientation, options = {}) {
1061
+ this.position = [...position];
1062
+ this.yaw = orientation.yaw;
1063
+ this.pitch = orientation.pitch;
1064
+ this.minSpeed = options.minSpeed ?? 12;
1065
+ this.speedPerMeter = options.speedPerMeter ?? 1.2;
1066
+ this.sprintFactor = options.sprintFactor ?? 4;
1067
+ this.minClearance = options.minClearance ?? 2;
1068
+ this.lookSensitivity = options.lookSensitivity ?? .003;
1069
+ }
1070
+ update(dt, input, environment) {
1071
+ const step = Math.max(0, Math.min(.1, dt));
1072
+ const turned = applyCameraLookDelta(this.yaw, this.pitch, input.look[0], input.look[1], this.lookSensitivity);
1073
+ this.yaw = turned.yaw;
1074
+ this.pitch = turned.pitch;
1075
+ const ground = environment.groundHeight(this.position[0], this.position[2]);
1076
+ const aboveGround = ground === void 0 ? 100 : Math.max(0, this.position[1] - ground);
1077
+ const speed = Math.max(this.minSpeed, aboveGround * this.speedPerMeter) * (input.sprint ? this.sprintFactor : 1) * step;
1078
+ const forward = cameraPlanarForward(this.yaw);
1079
+ const right = cameraRight(this.yaw);
1080
+ const { move } = input;
1081
+ for (let axis = 0; axis < 3; axis++) this.position[axis] = this.position[axis] + (forward[axis] * move.forward + right[axis] * move.right) * speed;
1082
+ this.position[1] += move.up * speed;
1083
+ const floor = environment.groundHeight(this.position[0], this.position[2]);
1084
+ if (floor !== void 0 && this.position[1] < floor + this.minClearance) this.position[1] = floor + this.minClearance;
1085
+ const direction = cameraForward(this.yaw, this.pitch);
1086
+ return {
1087
+ position: [...this.position],
1088
+ lookAt: [
1089
+ this.position[0] + direction[0],
1090
+ this.position[1] + direction[1],
1091
+ this.position[2] + direction[2]
1092
+ ],
1093
+ direction
1094
+ };
1095
+ }
1096
+ };
1097
+ //#endregion
1098
+ //#region src/navigation/follow.ts
1099
+ var FollowController = class {
1100
+ position;
1101
+ yawOffset = 0;
1102
+ pitchOffset = 0;
1103
+ distance;
1104
+ height;
1105
+ lookHeight;
1106
+ smoothing;
1107
+ recenter;
1108
+ minClearance;
1109
+ constructor(options = {}) {
1110
+ this.distance = options.distance ?? 6;
1111
+ this.height = options.height ?? 2.2;
1112
+ this.lookHeight = options.lookHeight ?? 1.2;
1113
+ this.smoothing = options.smoothing ?? .18;
1114
+ this.recenter = options.recenter ?? 1.5;
1115
+ this.minClearance = options.minClearance ?? .6;
1116
+ }
1117
+ /** Snap next frame instead of easing (after a teleport or a subject change). */
1118
+ reset() {
1119
+ this.position = void 0;
1120
+ this.yawOffset = 0;
1121
+ this.pitchOffset = 0;
1122
+ }
1123
+ update(dt, subject, input, environment) {
1124
+ const step = Math.max(0, Math.min(.1, dt));
1125
+ const looking = input.look[0] !== 0 || input.look[1] !== 0;
1126
+ this.yawOffset = Math.max(-Math.PI, Math.min(Math.PI, this.yawOffset - input.look[0] * .005));
1127
+ this.pitchOffset = Math.max(-.35, Math.min(.9, this.pitchOffset + input.look[1] * .004));
1128
+ if (!looking && this.recenter > 0) {
1129
+ const decay = Math.exp(-step / this.recenter);
1130
+ this.yawOffset *= decay;
1131
+ this.pitchOffset *= decay;
1132
+ }
1133
+ const heading = subject.heading + this.yawOffset;
1134
+ const lookAt = [
1135
+ subject.position[0],
1136
+ subject.position[1] + this.lookHeight,
1137
+ subject.position[2]
1138
+ ];
1139
+ const reach = this.distance * Math.cos(this.pitchOffset);
1140
+ const ideal = [
1141
+ subject.position[0] - Math.sin(heading) * reach,
1142
+ subject.position[1] + this.height + this.distance * Math.sin(this.pitchOffset),
1143
+ subject.position[2] + Math.cos(heading) * reach
1144
+ ];
1145
+ if (this.position === void 0) this.position = [...ideal];
1146
+ else {
1147
+ const blend = this.smoothing <= 0 ? 1 : 1 - Math.exp(-step / this.smoothing);
1148
+ for (let axis = 0; axis < 3; axis++) this.position[axis] = this.position[axis] + (ideal[axis] - this.position[axis]) * blend;
1149
+ }
1150
+ const ground = environment.groundHeight(this.position[0], this.position[2]);
1151
+ if (ground !== void 0 && this.position[1] < ground + this.minClearance) this.position[1] = ground + this.minClearance;
1152
+ const dx = lookAt[0] - this.position[0];
1153
+ const dy = lookAt[1] - this.position[1];
1154
+ const dz = lookAt[2] - this.position[2];
1155
+ const length = Math.hypot(dx, dy, dz) || 1;
1156
+ return {
1157
+ position: [...this.position],
1158
+ lookAt,
1159
+ direction: [
1160
+ dx / length,
1161
+ dy / length,
1162
+ dz / length
1163
+ ]
1164
+ };
1165
+ }
1166
+ };
1167
+ //#endregion
820
1168
  //#region src/navigation/orbit.ts
821
1169
  const TAU = Math.PI * 2;
822
1170
  function smoothstep(t) {
@@ -1332,11 +1680,17 @@ function requireFinite(value, name, allowZero) {
1332
1680
  /**
1333
1681
  * A small collision neighborhood in metric coordinates, independent of floating-origin shifts.
1334
1682
  * Only visible, resident geometry under `root` participates; evicted tiles and hidden layers
1335
- * disappear on the next scan, and instance transforms are expanded only inside the
1336
- * neighborhood. Large geometries (terrain tiles, building cells) are walked through a per-geometry
1683
+ * disappear on the next scan, including meshes with all render layers disabled unless marked
1684
+ * `userData.walkCollisionOnly` (for example, a smooth staircase proxy). Instance
1685
+ * transforms are expanded only inside the neighborhood. Large geometries (terrain tiles,
1686
+ * building cells) are walked through a per-geometry
1337
1687
  * spatial index, so a rebuild costs the triangles near the subject rather than the whole tile.
1338
1688
  * Meshes opt out with `userData.walkIgnore`, and water materials (`userData.terrainWaterMaterial`)
1339
- * and `semantic:landcover` overlays are never solid.
1689
+ * are never solid. Land cover is a solid walking surface: its visible elevation can differ from
1690
+ * bare terrain, and full-tile land cover can replace the bare surface altogether.
1691
+ * A group whose contents lie within an X/Z rectangle of its own frame declares it as
1692
+ * `userData.walkFootprint` (`[minX, minZ, maxX, maxZ]`, like a terrain tile): a scan skips the
1693
+ * whole group when that rectangle is out of reach.
1340
1694
  */
1341
1695
  var WalkCollision = class {
1342
1696
  origin = new THREE.Vector3();
@@ -1375,8 +1729,9 @@ var WalkCollision = class {
1375
1729
  const moved = !this.initialized || band === void 0 !== (this.centerY === void 0) || Math.hypot(x - this.origin.x, z - this.origin.z) >= this.rebuildDistance || band !== void 0 && this.centerY !== void 0 && Math.abs(band - this.centerY) >= this.rebuildDistance;
1376
1730
  const now = this.now();
1377
1731
  if (!moved && !this.stale && now - this.scannedAt < this.rescanIntervalMs) return;
1378
- root.updateWorldMatrix(true, true);
1732
+ root.updateWorldMatrix(true, false);
1379
1733
  const inverse = root.matrixWorld.clone().invert();
1734
+ const candidate = new THREE.Matrix4();
1380
1735
  const meshes = [];
1381
1736
  const centerX = moved ? x : this.origin.x;
1382
1737
  const centerZ = moved ? z : this.origin.z;
@@ -1384,25 +1739,44 @@ var WalkCollision = class {
1384
1739
  const reach = this.radius + this.rebuildDistance;
1385
1740
  const verticalReach = (this.verticalRadius ?? 0) + this.rebuildDistance;
1386
1741
  const bounds = new THREE.Box3();
1387
- root.traverseVisible((object) => {
1388
- if (!(object instanceof THREE.Mesh) || object.userData.walkIgnore === true) return;
1742
+ const sphere = new THREE.Sphere();
1743
+ const footprint = new THREE.Box3();
1744
+ const outOfReach = (min, max) => min.x > centerX + reach || max.x < centerX - reach || min.z > centerZ + reach || max.z < centerZ - reach || centerY !== void 0 && (min.y > centerY + verticalReach || max.y < centerY - verticalReach);
1745
+ const visit = (object, inspect) => {
1746
+ if (!object.visible) return;
1747
+ if (object !== root) object.updateWorldMatrix(false, false);
1748
+ const area = object.userData.walkFootprint;
1749
+ if (area !== void 0) {
1750
+ footprint.min.set(area[0], 0, area[1]);
1751
+ footprint.max.set(area[2], 0, area[3]);
1752
+ footprint.applyMatrix4(candidate.multiplyMatrices(inverse, object.matrixWorld));
1753
+ if (footprint.min.x > centerX + reach || footprint.max.x < centerX - reach || footprint.min.z > centerZ + reach || footprint.max.z < centerZ - reach) return;
1754
+ }
1755
+ inspect(object);
1756
+ for (const child of object.children) visit(child, inspect);
1757
+ };
1758
+ visit(root, (object) => {
1759
+ if (!(object instanceof THREE.Mesh) || object.userData.walkIgnore === true || object.layers.mask === 0 && object.userData.walkCollisionOnly !== true) return;
1389
1760
  if (this.ignoreVehicles && (object.userData.vehicleIds || object.userData.vehicleGeometry)) return;
1390
- if (object.name === "semantic:landcover") return;
1391
1761
  if ((Array.isArray(object.material) ? object.material : [object.material]).every((material) => material.userData.terrainWaterMaterial === true)) return;
1392
- const matrix = new THREE.Matrix4().multiplyMatrices(inverse, object.matrixWorld);
1762
+ const matrix = candidate.multiplyMatrices(inverse, object.matrixWorld);
1763
+ const known = object instanceof THREE.InstancedMesh ? object.boundingSphere : object.geometry.boundingSphere;
1764
+ if (known !== null) {
1765
+ sphere.copy(known).applyMatrix4(matrix);
1766
+ bounds.min.setScalar(-sphere.radius).add(sphere.center);
1767
+ bounds.max.setScalar(sphere.radius).add(sphere.center);
1768
+ if (outOfReach(bounds.min, bounds.max)) return;
1769
+ }
1393
1770
  if (object instanceof THREE.InstancedMesh) {
1771
+ geometryBounds(object.geometry);
1394
1772
  if (object.boundingBox === null) object.computeBoundingBox();
1395
1773
  bounds.copy(object.boundingBox);
1396
- } else {
1397
- if (object.geometry.boundingBox === null) object.geometry.computeBoundingBox();
1398
- bounds.copy(object.geometry.boundingBox);
1399
- }
1774
+ } else bounds.copy(geometryBounds(object.geometry));
1400
1775
  bounds.applyMatrix4(matrix);
1401
- if (bounds.min.x > centerX + reach || bounds.max.x < centerX - reach || bounds.min.z > centerZ + reach || bounds.max.z < centerZ - reach) return;
1402
- if (centerY !== void 0 && (bounds.min.y > centerY + verticalReach || bounds.max.y < centerY - verticalReach)) return;
1776
+ if (outOfReach(bounds.min, bounds.max)) return;
1403
1777
  meshes.push({
1404
1778
  mesh: object,
1405
- matrix,
1779
+ matrix: matrix.clone(),
1406
1780
  count: object instanceof THREE.InstancedMesh ? object.count : 1,
1407
1781
  geometry: object.geometry,
1408
1782
  version: object instanceof THREE.InstancedMesh ? object.instanceMatrix.version : (object.geometry.index?.version ?? 0) + (object.geometry.getAttribute("position")?.version ?? 0)
@@ -1456,7 +1830,7 @@ var WalkCollision = class {
1456
1830
  const geometry = mesh.geometry;
1457
1831
  const position = geometry.getAttribute("position");
1458
1832
  if (position === void 0) continue;
1459
- if (geometry.boundingBox === null) geometry.computeBoundingBox();
1833
+ geometryBounds(geometry);
1460
1834
  local.multiplyMatrices(offset, matrix);
1461
1835
  if (mesh instanceof THREE.InstancedMesh && mesh.boundingBox === null) mesh.computeBoundingBox();
1462
1836
  bounds.copy(mesh instanceof THREE.InstancedMesh ? mesh.boundingBox : geometry.boundingBox).applyMatrix4(local);
@@ -1501,6 +1875,32 @@ var WalkCollision = class {
1501
1875
  this.octree.build();
1502
1876
  }
1503
1877
  };
1878
+ /**
1879
+ * The geometry's bounding box, computed once straight from a plain float position array: three's
1880
+ * per-vertex accessors made a freshly streamed building cell's box most of an aircraft's scan.
1881
+ */
1882
+ function geometryBounds(geometry) {
1883
+ const known = geometry.boundingBox;
1884
+ if (known !== null) return known;
1885
+ const position = geometry.getAttribute("position");
1886
+ if (!(position instanceof THREE.BufferAttribute) || !(position.array instanceof Float32Array) || position.normalized || position.itemSize !== 3 || geometry.morphAttributes.position !== void 0) {
1887
+ geometry.computeBoundingBox();
1888
+ return geometry.boundingBox;
1889
+ }
1890
+ const array = position.array;
1891
+ let minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, minZ = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY, maxZ = Number.NEGATIVE_INFINITY;
1892
+ for (let i = 0, end = position.count * 3; i < end; i += 3) {
1893
+ const x = array[i], y = array[i + 1], z = array[i + 2];
1894
+ if (x < minX) minX = x;
1895
+ if (x > maxX) maxX = x;
1896
+ if (y < minY) minY = y;
1897
+ if (y > maxY) maxY = y;
1898
+ if (z < minZ) minZ = z;
1899
+ if (z > maxZ) maxZ = z;
1900
+ }
1901
+ geometry.boundingBox = new THREE.Box3(new THREE.Vector3(minX, minY, minZ), new THREE.Vector3(maxX, maxY, maxZ));
1902
+ return geometry.boundingBox;
1903
+ }
1504
1904
  const BOX_FACES = [
1505
1905
  [
1506
1906
  0,
@@ -1580,6 +1980,8 @@ function addBox(tree, box, transform) {
1580
1980
  const WALK_EYE_HEIGHT = 1.7;
1581
1981
  const WALK_SPEED = 1.5;
1582
1982
  const RUN_SPEED = 4;
1983
+ const SWIM_SPEED = 1.2;
1984
+ const SWIM_DEPTH = WALK_EYE_HEIGHT - .45;
1583
1985
  const BODY_HEIGHT = 1.8;
1584
1986
  const BODY_RADIUS = .3;
1585
1987
  /** `place` tries rings of landing spots this far apart, out to this many rings. */
@@ -1597,12 +1999,18 @@ const FLOOR_NORMAL = Math.cos(Math.PI / 3.6);
1597
1999
  * First-person walking over streamed geometry: a 1.8 m capsule with gravity, jumping, wall
1598
2000
  * sliding and a 50° walkable-slope limit, integrated at a fixed 120 Hz so results agree across
1599
2001
  * frame rates. `feet` is the world position; put the camera `WALK_EYE_HEIGHT` above it. Missing
1600
- * terrain pauses movement (it is never a bottomless pit) until coverage arrives.
2002
+ * terrain pauses movement (it is never a bottomless pit) until coverage arrives. Set
2003
+ * `sampleWaterHeight` to float in deep water and automatically walk again in the shallows.
1601
2004
  */
1602
2005
  var WalkController = class {
2006
+ /** Four times walking/running/swimming speed; jump height and look response stay normal. */
2007
+ boostMode = false;
1603
2008
  feet = new THREE.Vector3();
1604
2009
  velocity = new THREE.Vector3();
1605
2010
  grounded = false;
2011
+ swimming = false;
2012
+ /** Water surface in world meters; null means dry, undefined means coverage is loading. */
2013
+ sampleWaterHeight;
1606
2014
  ready = false;
1607
2015
  waitingForTerrain = false;
1608
2016
  accumulator = 0;
@@ -1612,13 +2020,18 @@ var WalkController = class {
1612
2020
  this.feet.set(x, 0, z);
1613
2021
  this.velocity.set(0, 0, 0);
1614
2022
  this.grounded = false;
2023
+ this.swimming = false;
1615
2024
  this.ready = false;
1616
2025
  this.waitingForTerrain = true;
1617
2026
  this.accumulator = 0;
1618
2027
  this.jumpHeld = false;
1619
2028
  }
1620
- /** Find open ground near the fly camera, rather than dropping through a building's roof. */
1621
- place(collision, sampleHeight) {
2029
+ /**
2030
+ * Find supported open ground. A separate `groundCollision` can exclude vehicles from the
2031
+ * landing ray while `collision` still rejects body overlaps, placing people beside cars.
2032
+ * Deep water supports placement even when no solid lake bed is rendered.
2033
+ */
2034
+ place(collision, sampleHeight, groundCollision = collision) {
1622
2035
  const centerX = this.feet.x;
1623
2036
  const centerZ = this.feet.z;
1624
2037
  for (let ring = 0; ring <= PLACEMENT_RINGS; ring++) {
@@ -1627,17 +2040,21 @@ var WalkController = class {
1627
2040
  const x = centerX + Math.cos(i / count * Math.PI * 2) * ring * PLACEMENT_RING_SPACING;
1628
2041
  const z = centerZ + Math.sin(i / count * Math.PI * 2) * ring * PLACEMENT_RING_SPACING;
1629
2042
  const ground = sampleHeight(x, z);
1630
- if (ground === void 0) continue;
1631
- const ray = new THREE.Ray(new THREE.Vector3(x - collision.origin.x, ground + 1e4, z - collision.origin.z), new THREE.Vector3(0, -1, 0));
1632
- const hit = collision.octree.rayIntersect(ray);
1633
- if (!hit || hit.position.y > ground + 3) continue;
1634
- this.feet.set(x, hit.position.y + .02, z);
2043
+ const water = this.sampleWaterHeight?.(x, z);
2044
+ if (ground === void 0 && water == null) continue;
2045
+ const ray = new THREE.Ray(new THREE.Vector3(x - groundCollision.origin.x, Math.max(ground ?? -Infinity, water ?? -Infinity) + 1e4, z - groundCollision.origin.z), new THREE.Vector3(0, -1, 0));
2046
+ const hit = groundCollision.octree.rayIntersect(ray);
2047
+ const afloat = water != null && (!hit || hit.position.y < water - SWIM_DEPTH);
2048
+ if (!afloat && (!hit || hit.position.y > (ground ?? water ?? 0) + 3)) continue;
2049
+ this.feet.set(x, afloat ? water - SWIM_DEPTH : hit ? hit.position.y + .02 : 0, z);
1635
2050
  this.setCapsule(collision);
1636
2051
  const overlap = collision.octree.capsuleIntersect(this.capsule);
1637
2052
  if (overlap && (overlap.normal.y < FLOOR_NORMAL || overlap.depth > .15)) continue;
1638
2053
  this.ready = true;
1639
2054
  this.waitingForTerrain = false;
1640
- this.grounded = true;
2055
+ this.grounded = !afloat;
2056
+ this.swimming = afloat;
2057
+ this.velocity.set(0, 0, 0);
1641
2058
  return true;
1642
2059
  }
1643
2060
  }
@@ -1661,15 +2078,18 @@ var WalkController = class {
1661
2078
  this.grounded = false;
1662
2079
  }
1663
2080
  const length = Math.max(1, Math.hypot(input.forward, input.right));
1664
- const speed = input.sprint ? 4 : WALK_SPEED;
1665
- const vx = (Math.cos(input.yaw) * input.forward - Math.sin(input.yaw) * input.right) / length * speed;
1666
- const vz = (Math.sin(input.yaw) * input.forward + Math.cos(input.yaw) * input.right) / length * speed;
2081
+ const forwardX = (Math.cos(input.yaw) * input.forward - Math.sin(input.yaw) * input.right) / length;
2082
+ const forwardZ = (Math.sin(input.yaw) * input.forward + Math.cos(input.yaw) * input.right) / length;
1667
2083
  this.accumulator += Math.min(.1, Math.max(0, dt));
1668
2084
  while (this.accumulator >= STEP) {
1669
2085
  this.accumulator -= STEP;
2086
+ const speed = (this.swimming ? SWIM_SPEED * (input.sprint ? 1.5 : 1) : input.sprint ? 4 : WALK_SPEED) * boostSpeedMultiplier(this.boostMode);
2087
+ const vx = forwardX * speed;
2088
+ const vz = forwardZ * speed;
1670
2089
  const nextX = this.feet.x + vx * STEP;
1671
2090
  const nextZ = this.feet.z + vz * STEP;
1672
- this.waitingForTerrain = sampleHeight(nextX, nextZ) === void 0;
2091
+ const water = this.sampleWaterHeight?.(nextX, nextZ);
2092
+ this.waitingForTerrain = sampleHeight(nextX, nextZ) === void 0 && water == null || this.swimming && this.sampleWaterHeight !== void 0 && water === void 0;
1673
2093
  if (this.waitingForTerrain) {
1674
2094
  this.velocity.set(0, 0, 0);
1675
2095
  this.accumulator = 0;
@@ -1679,6 +2099,11 @@ var WalkController = class {
1679
2099
  this.velocity.z = vz;
1680
2100
  this.velocity.y = Math.max(-35, this.velocity.y - GRAVITY * STEP);
1681
2101
  this.feet.addScaledVector(this.velocity, STEP);
2102
+ const floatingFeet = water == null ? -Infinity : water - SWIM_DEPTH;
2103
+ if (this.feet.y <= floatingFeet) {
2104
+ this.feet.y = floatingFeet;
2105
+ this.velocity.y = 0;
2106
+ }
1682
2107
  this.setCapsule(collision);
1683
2108
  this.grounded = false;
1684
2109
  for (let pass = 0; pass < 4; pass++) {
@@ -1700,6 +2125,7 @@ var WalkController = class {
1700
2125
  }
1701
2126
  this.feet.copy(this.capsule.start).add(collision.origin);
1702
2127
  this.feet.y -= BODY_RADIUS;
2128
+ this.swimming = !this.grounded && this.feet.y <= floatingFeet + .05;
1703
2129
  }
1704
2130
  }
1705
2131
  setCapsule(collision) {
@@ -1711,4 +2137,4 @@ var WalkController = class {
1711
2137
  }
1712
2138
  };
1713
2139
  //#endregion
1714
- export { CollisionTree, FlyController, FollowController, MAX_LOOK_PITCH, NAVIGATION_ACTIONS, NavigationInputSource, NavigationPointer, OrbitController, RUN_SPEED, TouchStick, WALK_EYE_HEIGHT, WALK_PLACEMENT_RADIUS, WALK_SPEED, WalkCollision, WalkController, applyCameraLookDelta, cameraForward, cameraPlanarForward, cameraRight, createTouchJoystick, idleNavigationInput, navigationInputProfiles, orientationFromDirection, viewNeedsImmediateUpdate };
2140
+ export { CollisionTree, FlyController, FollowController, MAX_LOOK_PITCH, NAVIGATION_ACTIONS, NavigationInputSource, NavigationPointer, OrbitController, RUN_SPEED, SWIM_SPEED, TouchStick, WALK_EYE_HEIGHT, WALK_PLACEMENT_RADIUS, WALK_SPEED, WalkCollision, WalkController, applyCameraLookDelta, cameraForward, cameraPlanarForward, cameraRight, createNavigationControls, createTouchJoystick, idleNavigationInput, navigationInputProfiles, orientationFromDirection, viewNeedsImmediateUpdate };