gpue commited on
Commit
ce91fab
·
verified ·
1 Parent(s): cd1aa63

Deploy d6ee77530b30041432b838a2b910123b940f3e6e

Browse files
src/AltitudeSlider.tsx ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ChangeEvent } from "react";
2
+ import { ALTITUDE_LEVELS_MM } from "./altitudeLevels";
3
+
4
+ const SIZES = {
5
+ normal: { trackLength: 90 },
6
+ large: { trackLength: 130 },
7
+ };
8
+
9
+ interface AltitudeSliderProps {
10
+ levelIndex: number;
11
+ disabled: boolean;
12
+ onChange: (index: number) => void;
13
+ size?: "normal" | "large";
14
+ }
15
+
16
+ // Horizontal, discrete-step counterpart to WingSlider.tsx's rotated
17
+ // continuous slider -- steps between altitudeLevels.ts's fixed height levels
18
+ // rather than a free-drag 0-1 range.
19
+ export default function AltitudeSlider({ levelIndex, disabled, onChange, size = "normal" }: AltitudeSliderProps) {
20
+ const { trackLength: TRACK_LENGTH } = SIZES[size];
21
+
22
+ const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
23
+ onChange(Number(e.target.value));
24
+ };
25
+
26
+ return (
27
+ <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
28
+ <input
29
+ type="range"
30
+ min={0}
31
+ max={ALTITUDE_LEVELS_MM.length - 1}
32
+ step={1}
33
+ value={levelIndex}
34
+ disabled={disabled}
35
+ onChange={handleChange}
36
+ style={{
37
+ width: TRACK_LENGTH,
38
+ accentColor: "#8e56fc",
39
+ cursor: disabled ? "default" : "pointer",
40
+ }}
41
+ />
42
+ <span style={{ fontSize: 11, color: "#8b8d99" }}>altitude</span>
43
+ </div>
44
+ );
45
+ }
src/App.tsx CHANGED
@@ -1,11 +1,13 @@
1
  import { useEffect, useRef, useState } from "react";
 
2
  import { apiPath } from "./env";
3
  import FlyScene from "./FlyScene";
4
  import { resumeAudioContext } from "./flyBuzz";
5
  import MobileControlSheet, { MOBILE_SHEET_HANDLE_HEIGHT } from "./MobileControlSheet";
6
  import SidePanel from "./SidePanel";
7
- import { useFlyLayout } from "./useFlyLayout";
8
  import { useIsMobile } from "./useIsMobile";
 
9
  import { useLiveFlyState } from "./useLiveFlyState";
10
  import { useVda5050Nats } from "./vda5050/useVda5050Nats";
11
 
@@ -29,6 +31,8 @@ export default function App() {
29
  const [selectedFlyId, setSelectedFlyId] = useState<string | null>(null);
30
  const [panelCollapsed, setPanelCollapsed] = useState(false);
31
  const [sheetExpanded, setSheetExpanded] = useState(false);
 
 
32
  const isMobile = useIsMobile();
33
 
34
  useEffect(() => {
@@ -47,6 +51,45 @@ export default function App() {
47
  if (selectedFlyId) setSheetExpanded(true);
48
  }, [selectedFlyId]);
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  return (
51
  // Buzzing audio needs a user gesture to start (browser autoplay policy);
52
  // this covers every click/tap anywhere in the app rather than needing a
@@ -100,6 +143,10 @@ export default function App() {
100
  livePositionsRef={livePositionsRef}
101
  expanded={sheetExpanded}
102
  onToggleExpanded={() => setSheetExpanded((e) => !e)}
 
 
 
 
103
  />
104
  </div>
105
  ) : (
@@ -112,6 +159,10 @@ export default function App() {
112
  joystickRef={joystickRef}
113
  wingSlidersRef={wingSlidersRef}
114
  livePositionsRef={livePositionsRef}
 
 
 
 
115
  />
116
  )}
117
  </div>
 
1
  import { useEffect, useRef, useState } from "react";
2
+ import { ALTITUDE_LEVELS_MM } from "./altitudeLevels";
3
  import { apiPath } from "./env";
4
  import FlyScene from "./FlyScene";
5
  import { resumeAudioContext } from "./flyBuzz";
6
  import MobileControlSheet, { MOBILE_SHEET_HANDLE_HEIGHT } from "./MobileControlSheet";
7
  import SidePanel from "./SidePanel";
8
+ import { FLY_GROUND_OFFSET_MM, useFlyLayout } from "./useFlyLayout";
9
  import { useIsMobile } from "./useIsMobile";
10
+ import { useKeyboardControls } from "./useKeyboardControls";
11
  import { useLiveFlyState } from "./useLiveFlyState";
12
  import { useVda5050Nats } from "./vda5050/useVda5050Nats";
13
 
 
31
  const [selectedFlyId, setSelectedFlyId] = useState<string | null>(null);
32
  const [panelCollapsed, setPanelCollapsed] = useState(false);
33
  const [sheetExpanded, setSheetExpanded] = useState(false);
34
+ const [flying, setFlying] = useState(false);
35
+ const [altitudeLevelIndex, setAltitudeLevelIndex] = useState(0);
36
  const isMobile = useIsMobile();
37
 
38
  useEffect(() => {
 
51
  if (selectedFlyId) setSheetExpanded(true);
52
  }, [selectedFlyId]);
53
 
54
+ // Syncs the flight switch/altitude slider's UI state onto whichever fly is
55
+ // selected, same shape as setManualMode above (body applies, cleanup
56
+ // reverts) -- the cleanup is what auto-lands a flying fly the moment you
57
+ // deselect it or select a different one, rather than leaving it hovering
58
+ // unattended with no visible control surface.
59
+ useEffect(() => {
60
+ if (!selectedFlyId) return;
61
+ const live = livePositionsRef.current.get(selectedFlyId);
62
+ if (live) {
63
+ live.flying = flying;
64
+ live.targetAltitudeMm = flying ? ALTITUDE_LEVELS_MM[altitudeLevelIndex] : FLY_GROUND_OFFSET_MM;
65
+ }
66
+ return () => {
67
+ const prevLive = livePositionsRef.current.get(selectedFlyId);
68
+ if (prevLive) {
69
+ prevLive.flying = false;
70
+ prevLive.targetAltitudeMm = FLY_GROUND_OFFSET_MM;
71
+ }
72
+ };
73
+ }, [flying, altitudeLevelIndex, selectedFlyId, livePositionsRef]);
74
+
75
+ // Freshly selecting a different fly always shows it as grounded in the
76
+ // switch/slider, matching the auto-land-on-deselect behavior above.
77
+ useEffect(() => {
78
+ setFlying(false);
79
+ setAltitudeLevelIndex(0);
80
+ }, [selectedFlyId]);
81
+
82
+ const toggleFlying = () => setFlying((f) => !f);
83
+ const onAltitudeChange = (index: number) => {
84
+ setAltitudeLevelIndex(Math.min(ALTITUDE_LEVELS_MM.length - 1, Math.max(0, index)));
85
+ // Changing altitude implies airborne; landing is only ever via the
86
+ // switch/Space, not by stepping back down past level 0.
87
+ setFlying(true);
88
+ };
89
+ const onAltitudeStep = (direction: 1 | -1) => onAltitudeChange(altitudeLevelIndex + direction);
90
+
91
+ useKeyboardControls({ selectedFlyId, joystickRef, onToggleFlying: toggleFlying, onAltitudeStep });
92
+
93
  return (
94
  // Buzzing audio needs a user gesture to start (browser autoplay policy);
95
  // this covers every click/tap anywhere in the app rather than needing a
 
143
  livePositionsRef={livePositionsRef}
144
  expanded={sheetExpanded}
145
  onToggleExpanded={() => setSheetExpanded((e) => !e)}
146
+ flying={flying}
147
+ onToggleFlying={toggleFlying}
148
+ altitudeLevelIndex={altitudeLevelIndex}
149
+ onAltitudeChange={onAltitudeChange}
150
  />
151
  </div>
152
  ) : (
 
159
  joystickRef={joystickRef}
160
  wingSlidersRef={wingSlidersRef}
161
  livePositionsRef={livePositionsRef}
162
+ flying={flying}
163
+ onToggleFlying={toggleFlying}
164
+ altitudeLevelIndex={altitudeLevelIndex}
165
+ onAltitudeChange={onAltitudeChange}
166
  />
167
  )}
168
  </div>
src/FlightSwitch.tsx ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ interface FlightSwitchProps {
2
+ flying: boolean;
3
+ disabled: boolean;
4
+ onToggle: () => void;
5
+ size?: "normal" | "large";
6
+ }
7
+
8
+ export default function FlightSwitch({ flying, disabled, onToggle, size = "normal" }: FlightSwitchProps) {
9
+ return (
10
+ <button
11
+ type="button"
12
+ aria-pressed={flying}
13
+ disabled={disabled}
14
+ onClick={onToggle}
15
+ style={{
16
+ padding: size === "large" ? "10px 20px" : "6px 14px",
17
+ borderRadius: 6,
18
+ border: flying ? "1px solid #8e56fc" : "1px solid #2a2d3a",
19
+ background: flying ? "#8e56fc33" : "transparent",
20
+ color: disabled ? "#5a5d6b" : "inherit",
21
+ cursor: disabled ? "default" : "pointer",
22
+ font: "inherit",
23
+ fontSize: 13,
24
+ }}
25
+ >
26
+ {flying ? "Flying — space to land" : "Walking — space to fly"}
27
+ </button>
28
+ );
29
+ }
src/FlyControls.tsx CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import Joystick from "./Joystick";
2
  import WingSlider from "./WingSlider";
3
 
@@ -5,38 +7,59 @@ interface FlyControlsProps {
5
  disabled: boolean;
6
  joystickRef: React.RefObject<{ x: number; y: number }>;
7
  wingSlidersRef: React.RefObject<{ left: number; right: number }>;
 
 
 
 
8
  size?: "normal" | "large";
9
  }
10
 
11
- export default function FlyControls({ disabled, joystickRef, wingSlidersRef, size = "normal" }: FlyControlsProps) {
 
 
 
 
 
 
 
 
 
12
  return (
13
  <div
14
  style={{
15
  display: "flex",
 
16
  alignItems: "center",
17
- justifyContent: "center",
18
- gap: 16,
19
  padding: "16px 0",
20
  borderBottom: "1px solid #2a2d3a",
21
  }}
22
  >
23
- <WingSlider
24
- label="L wing"
25
- disabled={disabled}
26
- size={size}
27
- onChange={(v) => {
28
- wingSlidersRef.current.left = v;
29
- }}
30
- />
31
- <Joystick vectorRef={joystickRef} disabled={disabled} size={size} />
32
- <WingSlider
33
- label="R wing"
34
- disabled={disabled}
35
- size={size}
36
- onChange={(v) => {
37
- wingSlidersRef.current.right = v;
38
- }}
39
- />
 
 
 
 
 
 
 
 
40
  </div>
41
  );
42
  }
 
1
+ import AltitudeSlider from "./AltitudeSlider";
2
+ import FlightSwitch from "./FlightSwitch";
3
  import Joystick from "./Joystick";
4
  import WingSlider from "./WingSlider";
5
 
 
7
  disabled: boolean;
8
  joystickRef: React.RefObject<{ x: number; y: number }>;
9
  wingSlidersRef: React.RefObject<{ left: number; right: number }>;
10
+ flying: boolean;
11
+ onToggleFlying: () => void;
12
+ altitudeLevelIndex: number;
13
+ onAltitudeChange: (index: number) => void;
14
  size?: "normal" | "large";
15
  }
16
 
17
+ export default function FlyControls({
18
+ disabled,
19
+ joystickRef,
20
+ wingSlidersRef,
21
+ flying,
22
+ onToggleFlying,
23
+ altitudeLevelIndex,
24
+ onAltitudeChange,
25
+ size = "normal",
26
+ }: FlyControlsProps) {
27
  return (
28
  <div
29
  style={{
30
  display: "flex",
31
+ flexDirection: "column",
32
  alignItems: "center",
33
+ gap: 12,
 
34
  padding: "16px 0",
35
  borderBottom: "1px solid #2a2d3a",
36
  }}
37
  >
38
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 16 }}>
39
+ <WingSlider
40
+ label="L wing"
41
+ disabled={disabled}
42
+ size={size}
43
+ onChange={(v) => {
44
+ wingSlidersRef.current.left = v;
45
+ }}
46
+ />
47
+ <Joystick vectorRef={joystickRef} disabled={disabled} size={size} />
48
+ <WingSlider
49
+ label="R wing"
50
+ disabled={disabled}
51
+ size={size}
52
+ onChange={(v) => {
53
+ wingSlidersRef.current.right = v;
54
+ }}
55
+ />
56
+ </div>
57
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 16 }}>
58
+ <FlightSwitch flying={flying} disabled={disabled} onToggle={onToggleFlying} size={size} />
59
+ {flying && (
60
+ <AltitudeSlider levelIndex={altitudeLevelIndex} disabled={disabled} onChange={onAltitudeChange} size={size} />
61
+ )}
62
+ </div>
63
  </div>
64
  );
65
  }
src/FlyInstances.tsx CHANGED
@@ -20,6 +20,27 @@ const MAX_TURN_RATE_RAD_S = 2.5;
20
  // range without distorting the mesh.
21
  const MAX_WING_LIFT_RAD = 1.4;
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  const HALF_WIDTH = FLY_AREA_CONFIG.widthMm / 2;
24
  const HALF_DEPTH = FLY_AREA_CONFIG.depthMm / 2;
25
 
@@ -104,6 +125,10 @@ export default function FlyInstances({
104
  const tmpQuat = useRef(new Quaternion());
105
  const jointQuat = useRef(new Quaternion());
106
  const cameraForward = useRef(new Vector3());
 
 
 
 
107
 
108
  const getRig = (flyId: string, group: Group): Map<string, RigNode> => {
109
  let rig = rigCache.current.get(flyId);
@@ -149,8 +174,9 @@ export default function FlyInstances({
149
  };
150
  }, []);
151
 
152
- useFrame((_, dt) => {
153
  const livePositions = livePositionsRef.current;
 
154
  camera.getWorldDirection(cameraForward.current);
155
 
156
  // Every fly's brain/vision/wings update every frame now (not just the
@@ -202,7 +228,16 @@ export default function FlyInstances({
202
  // position/heading authority away from the local joystick entirely --
203
  // orders are waypoint-based, not a teleop signal, so the two can't
204
  // both drive movement at once.
205
- const isWalking = isSelected && live.operatingMode !== "AUTOMATIC" && (command.forwardSpeed !== 0 || command.turnRate !== 0);
 
 
 
 
 
 
 
 
 
206
  if (isWalking) stepGait(live.gait, command, dt);
207
 
208
  const wings = isSelected ? wingSlidersRef.current : ZERO_WINGS;
@@ -216,10 +251,17 @@ export default function FlyInstances({
216
  // (manual posing, only meaningful for the fly you're driving); the
217
  // brain's motor output plus the looming drive add a flapping
218
  // oscillation on top via wingController.ts.
 
 
 
 
 
 
 
219
  const flap = stepWingController(
220
  live.wingController,
221
- clamp(motorOutput(live.brain, "left") + loom.left, 0, 1),
222
- clamp(motorOutput(live.brain, "right") + loom.right, 0, 1),
223
  dt,
224
  );
225
  live.gait.jointAngles[wingJointName("l", "roll")] = -wings.left * MAX_WING_LIFT_RAD + flap.left;
@@ -268,12 +310,37 @@ export default function FlyInstances({
268
  rigNode.object.quaternion.copy(composed);
269
  }
270
 
271
- if (isWalking) {
272
  live.heading += command.turnRate * dt;
273
  live.x = clamp(live.x + Math.sin(live.heading) * command.forwardSpeed * dt, -HALF_WIDTH, HALF_WIDTH);
274
  live.z = clamp(live.z + Math.cos(live.heading) * command.forwardSpeed * dt, -HALF_DEPTH, HALF_DEPTH);
275
  }
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  // Always sync the rendered transform from live.{x,y,z,heading} --
278
  // that's the single source of truth regardless of who last wrote it
279
  // (local walking just above, or useVda5050Nats.ts for an AUTOMATIC
@@ -282,11 +349,20 @@ export default function FlyInstances({
282
  // backend order can move an unselected/AUTOMATIC fly too, skipping
283
  // this sync would silently leave its mesh frozen at its spawn point
284
  // while its actual position kept changing underneath it.
285
- group.position.set(live.x, live.y, live.z);
286
  // The rig's bind pose faces FACING_OFFSET_RAD in world terms (not +Z),
287
  // so subtract it to make rotation.y actually turn the mesh to face its
288
- // direction of travel instead of appearing to strafe sideways.
289
- group.rotation.y = live.heading - FACING_OFFSET_RAD;
 
 
 
 
 
 
 
 
 
290
  }
291
  });
292
 
 
20
  // range without distorting the mesh.
21
  const MAX_WING_LIFT_RAD = 1.4;
22
 
23
+ // Flight mode: sustained near-max wing drive (not exactly 1.0 so the
24
+ // DRIVE_THRESHOLD-adjacent silence right at touchdown still reads as a
25
+ // distinct transition rather than a hard cliff) -- this alone drives both
26
+ // the visual flap rate and the buzz pitch/gain up via wingController.ts's
27
+ // and flyBuzz.ts's existing drive->frequency mapping, no changes needed
28
+ // there. How fast live.y eases toward live.targetAltitudeMm, and how
29
+ // quickly the little bank/pitch tilt below eases toward its target and
30
+ // back to level -- same exponential-approach idiom wingController.ts
31
+ // already uses for smoothedDrive.
32
+ const FLIGHT_WING_DRIVE = 0.95;
33
+ const ALTITUDE_TAU_S = 0.4;
34
+ const MAX_PITCH_RAD = 0.18; // ~10 deg -- "a little", not aerobatic
35
+ const MAX_ROLL_RAD = 0.22; // ~13 deg
36
+ const TILT_TAU_S = 0.25;
37
+ // A hovering fly's altitude isn't perfectly still -- a gentle sinusoidal
38
+ // bob, render-only (never fed back into live.y/targetAltitudeMm), phase
39
+ // offset per fly (by index) so a group of flying flies doesn't bob in
40
+ // lockstep.
41
+ const BOB_AMPLITUDE_MM = 0.4;
42
+ const BOB_HZ = 1.6;
43
+
44
  const HALF_WIDTH = FLY_AREA_CONFIG.widthMm / 2;
45
  const HALF_DEPTH = FLY_AREA_CONFIG.depthMm / 2;
46
 
 
125
  const tmpQuat = useRef(new Quaternion());
126
  const jointQuat = useRef(new Quaternion());
127
  const cameraForward = useRef(new Vector3());
128
+ // Transient render-only pitch/roll bank while flying -- not part of
129
+ // LiveFlyState since nothing outside this loop ever needs to read it
130
+ // (unlike x/y/z/heading, which CameraRig.tsx and FlyLabels.tsx also consume).
131
+ const tiltRef = useRef(new Map<string, { pitch: number; roll: number }>());
132
 
133
  const getRig = (flyId: string, group: Group): Map<string, RigNode> => {
134
  let rig = rigCache.current.get(flyId);
 
174
  };
175
  }, []);
176
 
177
+ useFrame((state, dt) => {
178
  const livePositions = livePositionsRef.current;
179
+ const elapsedTime = state.clock.elapsedTime;
180
  camera.getWorldDirection(cameraForward.current);
181
 
182
  // Every fly's brain/vision/wings update every frame now (not just the
 
228
  // position/heading authority away from the local joystick entirely --
229
  // orders are waypoint-based, not a teleop signal, so the two can't
230
  // both drive movement at once.
231
+ //
232
+ // isWalking (legs) and isTranslating (x/z/heading) split apart for
233
+ // flight mode: a flying fly still translates from the same joystick
234
+ // command, it just never plays a walking tripod gait while airborne --
235
+ // its legs simply freeze at their last pose, same as any other
236
+ // stopped-walking fly today.
237
+ const hasManualCommand =
238
+ isSelected && live.operatingMode !== "AUTOMATIC" && (command.forwardSpeed !== 0 || command.turnRate !== 0);
239
+ const isWalking = hasManualCommand && !live.flying;
240
+ const isTranslating = hasManualCommand;
241
  if (isWalking) stepGait(live.gait, command, dt);
242
 
243
  const wings = isSelected ? wingSlidersRef.current : ZERO_WINGS;
 
251
  // (manual posing, only meaningful for the fly you're driving); the
252
  // brain's motor output plus the looming drive add a flapping
253
  // oscillation on top via wingController.ts.
254
+ // Flying fully replaces (not blends with) the brain/looming drive: that
255
+ // signal means "resting fly reacting to a nearby threat," which
256
+ // doesn't compose with a sustained flight stroke -- and it would just
257
+ // clip at the clamp(...,0,1) ceiling anyway, since FLIGHT_WING_DRIVE
258
+ // already leaves almost no headroom.
259
+ const baseDriveLeft = clamp(motorOutput(live.brain, "left") + loom.left, 0, 1);
260
+ const baseDriveRight = clamp(motorOutput(live.brain, "right") + loom.right, 0, 1);
261
  const flap = stepWingController(
262
  live.wingController,
263
+ live.flying ? FLIGHT_WING_DRIVE : baseDriveLeft,
264
+ live.flying ? FLIGHT_WING_DRIVE : baseDriveRight,
265
  dt,
266
  );
267
  live.gait.jointAngles[wingJointName("l", "roll")] = -wings.left * MAX_WING_LIFT_RAD + flap.left;
 
310
  rigNode.object.quaternion.copy(composed);
311
  }
312
 
313
+ if (isTranslating) {
314
  live.heading += command.turnRate * dt;
315
  live.x = clamp(live.x + Math.sin(live.heading) * command.forwardSpeed * dt, -HALF_WIDTH, HALF_WIDTH);
316
  live.z = clamp(live.z + Math.cos(live.heading) * command.forwardSpeed * dt, -HALF_DEPTH, HALF_DEPTH);
317
  }
318
 
319
+ // Always ease live.y toward its current target -- climbing while
320
+ // flying, or descending back to ground the instant flying flips false
321
+ // (App.tsx resets targetAltitudeMm to FLY_GROUND_OFFSET_MM then), same
322
+ // exponential-approach idiom as wingController.ts's smoothedDrive.
323
+ live.y += (live.targetAltitudeMm - live.y) * (1 - Math.exp(-dt / ALTITUDE_TAU_S));
324
+
325
+ // A little bank/pitch while actively steering in flight -- purely
326
+ // transient/render-only (tiltRef), eases toward zero on its own the
327
+ // moment the stick centers or flying ends, via the same lerp.
328
+ let tilt = tiltRef.current.get(fly.id);
329
+ if (!tilt) {
330
+ tilt = { pitch: 0, roll: 0 };
331
+ tiltRef.current.set(fly.id, tilt);
332
+ }
333
+ const targetPitch = live.flying ? -joystick.y * MAX_PITCH_RAD : 0;
334
+ const targetRoll = live.flying ? -joystick.x * MAX_ROLL_RAD : 0;
335
+ const tiltAlpha = 1 - Math.exp(-dt / TILT_TAU_S);
336
+ tilt.pitch += (targetPitch - tilt.pitch) * tiltAlpha;
337
+ tilt.roll += (targetRoll - tilt.roll) * tiltAlpha;
338
+
339
+ // A gentle hover bob while flying -- render-only, never written back
340
+ // into live.y/targetAltitudeMm, so it can't drift the fly's actual
341
+ // tracked altitude or fight the climb/descent lerp above.
342
+ const bob = live.flying ? Math.sin(elapsedTime * BOB_HZ * Math.PI * 2 + fly.index) * BOB_AMPLITUDE_MM : 0;
343
+
344
  // Always sync the rendered transform from live.{x,y,z,heading} --
345
  // that's the single source of truth regardless of who last wrote it
346
  // (local walking just above, or useVda5050Nats.ts for an AUTOMATIC
 
349
  // backend order can move an unselected/AUTOMATIC fly too, skipping
350
  // this sync would silently leave its mesh frozen at its spawn point
351
  // while its actual position kept changing underneath it.
352
+ group.position.set(live.x, live.y + bob, live.z);
353
  // The rig's bind pose faces FACING_OFFSET_RAD in world terms (not +Z),
354
  // so subtract it to make rotation.y actually turn the mesh to face its
355
+ // direction of travel instead of appearing to strafe sideways. "YXZ"
356
+ // order composes yaw first (outermost), then two more rotations in
357
+ // the yawed frame -- the standard vehicle-tilt order, keeps
358
+ // rotation.y reading as pure heading and avoids gimbal artifacts at
359
+ // these small tilt angles. tilt.roll/tilt.pitch go into the X/Z slots
360
+ // (not the other way around) because this rig's bind-pose local axes
361
+ // put its forward/back tilt on Z and its left/right bank on X, the
362
+ // opposite of the naive X=pitch/Z=roll guess -- flagged by an earlier
363
+ // build where forward/back steering visibly banked the fly and
364
+ // left/right steering visibly pitched it.
365
+ group.rotation.set(tilt.roll, live.heading - FACING_OFFSET_RAD, tilt.pitch, "YXZ");
366
  }
367
  });
368
 
src/MobileControlSheet.tsx CHANGED
@@ -18,6 +18,10 @@ interface MobileControlSheetProps {
18
  livePositionsRef: React.RefObject<LiveFlyPositions>;
19
  expanded: boolean;
20
  onToggleExpanded: () => void;
 
 
 
 
21
  }
22
 
23
  export default function MobileControlSheet({
@@ -29,6 +33,10 @@ export default function MobileControlSheet({
29
  livePositionsRef,
30
  expanded,
31
  onToggleExpanded,
 
 
 
 
32
  }: MobileControlSheetProps) {
33
  const statusSnapshot = useStatusSnapshot(flies, livePositionsRef);
34
 
@@ -70,7 +78,16 @@ export default function MobileControlSheet({
70
 
71
  {expanded && (
72
  <div style={{ flex: 1, minHeight: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
73
- <FlyControls disabled={!selectedFlyId} joystickRef={joystickRef} wingSlidersRef={wingSlidersRef} size="large" />
 
 
 
 
 
 
 
 
 
74
 
75
  <button
76
  type="button"
 
18
  livePositionsRef: React.RefObject<LiveFlyPositions>;
19
  expanded: boolean;
20
  onToggleExpanded: () => void;
21
+ flying: boolean;
22
+ onToggleFlying: () => void;
23
+ altitudeLevelIndex: number;
24
+ onAltitudeChange: (index: number) => void;
25
  }
26
 
27
  export default function MobileControlSheet({
 
33
  livePositionsRef,
34
  expanded,
35
  onToggleExpanded,
36
+ flying,
37
+ onToggleFlying,
38
+ altitudeLevelIndex,
39
+ onAltitudeChange,
40
  }: MobileControlSheetProps) {
41
  const statusSnapshot = useStatusSnapshot(flies, livePositionsRef);
42
 
 
78
 
79
  {expanded && (
80
  <div style={{ flex: 1, minHeight: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
81
+ <FlyControls
82
+ disabled={!selectedFlyId}
83
+ joystickRef={joystickRef}
84
+ wingSlidersRef={wingSlidersRef}
85
+ flying={flying}
86
+ onToggleFlying={onToggleFlying}
87
+ altitudeLevelIndex={altitudeLevelIndex}
88
+ onAltitudeChange={onAltitudeChange}
89
+ size="large"
90
+ />
91
 
92
  <button
93
  type="button"
src/SidePanel.tsx CHANGED
@@ -17,6 +17,10 @@ interface SidePanelProps {
17
  joystickRef: React.RefObject<{ x: number; y: number }>;
18
  wingSlidersRef: React.RefObject<{ left: number; right: number }>;
19
  livePositionsRef: React.RefObject<LiveFlyPositions>;
 
 
 
 
20
  }
21
 
22
  export default function SidePanel({
@@ -28,6 +32,10 @@ export default function SidePanel({
28
  joystickRef,
29
  wingSlidersRef,
30
  livePositionsRef,
 
 
 
 
31
  }: SidePanelProps) {
32
  const statusSnapshot = useStatusSnapshot(flies, livePositionsRef);
33
 
@@ -65,7 +73,17 @@ export default function SidePanel({
65
  {collapsed ? "‹" : "›"}
66
  </button>
67
 
68
- {!collapsed && <FlyControls disabled={!selectedFlyId} joystickRef={joystickRef} wingSlidersRef={wingSlidersRef} />}
 
 
 
 
 
 
 
 
 
 
69
 
70
  {!collapsed && (
71
  <button
 
17
  joystickRef: React.RefObject<{ x: number; y: number }>;
18
  wingSlidersRef: React.RefObject<{ left: number; right: number }>;
19
  livePositionsRef: React.RefObject<LiveFlyPositions>;
20
+ flying: boolean;
21
+ onToggleFlying: () => void;
22
+ altitudeLevelIndex: number;
23
+ onAltitudeChange: (index: number) => void;
24
  }
25
 
26
  export default function SidePanel({
 
32
  joystickRef,
33
  wingSlidersRef,
34
  livePositionsRef,
35
+ flying,
36
+ onToggleFlying,
37
+ altitudeLevelIndex,
38
+ onAltitudeChange,
39
  }: SidePanelProps) {
40
  const statusSnapshot = useStatusSnapshot(flies, livePositionsRef);
41
 
 
73
  {collapsed ? "‹" : "›"}
74
  </button>
75
 
76
+ {!collapsed && (
77
+ <FlyControls
78
+ disabled={!selectedFlyId}
79
+ joystickRef={joystickRef}
80
+ wingSlidersRef={wingSlidersRef}
81
+ flying={flying}
82
+ onToggleFlying={onToggleFlying}
83
+ altitudeLevelIndex={altitudeLevelIndex}
84
+ onAltitudeChange={onAltitudeChange}
85
+ />
86
+ )}
87
 
88
  {!collapsed && (
89
  <button
src/altitudeLevels.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import { FLY_EXTENT_MM, FLY_GROUND_OFFSET_MM } from "./useFlyLayout";
2
+
3
+ // A clearly readable hop between levels, scaled off the fly's own body size
4
+ // rather than a fixed mm constant so it stays proportionate if that changes.
5
+ const LEVEL_STEP_MM = Math.max(...FLY_EXTENT_MM) * 2.5;
6
+
7
+ export const ALTITUDE_LEVELS_MM = [1, 2, 3].map((n) => FLY_GROUND_OFFSET_MM + n * LEVEL_STEP_MM);
src/useKeyboardControls.ts ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef } from "react";
2
+
3
+ interface KeyboardControlsArgs {
4
+ selectedFlyId: string | null;
5
+ joystickRef: React.RefObject<{ x: number; y: number }>;
6
+ onToggleFlying: () => void;
7
+ onAltitudeStep: (direction: 1 | -1) => void;
8
+ }
9
+
10
+ const ARROW_KEYS = new Set(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]);
11
+
12
+ // Keyboard alternative to Joystick.tsx's pointer drag (arrow keys) and the
13
+ // flight switch/altitude slider (Space, +/-) -- writes straight into the same
14
+ // joystickRef the pointer joystick writes to, so FlyInstances.tsx needs no
15
+ // awareness of where a command came from.
16
+ export function useKeyboardControls({ selectedFlyId, joystickRef, onToggleFlying, onAltitudeStep }: KeyboardControlsArgs) {
17
+ const heldRef = useRef(new Set<string>());
18
+ // Latest-callback refs: onToggleFlying/onAltitudeStep are fresh closures
19
+ // every App render (they're not memoized there), but flying/altitude
20
+ // changes are themselves state updates that would otherwise re-run this
21
+ // effect and clearAll() the joystick mid-press. Keeping only
22
+ // selectedFlyId/joystickRef as real effect deps means listener
23
+ // registration only churns on an actual selection change.
24
+ const onToggleFlyingRef = useRef(onToggleFlying);
25
+ onToggleFlyingRef.current = onToggleFlying;
26
+ const onAltitudeStepRef = useRef(onAltitudeStep);
27
+ onAltitudeStepRef.current = onAltitudeStep;
28
+
29
+ useEffect(() => {
30
+ const applyFromHeld = () => {
31
+ const held = heldRef.current;
32
+ let x = 0;
33
+ let y = 0;
34
+ if (held.has("ArrowUp")) y += 1;
35
+ if (held.has("ArrowDown")) y -= 1;
36
+ if (held.has("ArrowLeft")) x -= 1;
37
+ if (held.has("ArrowRight")) x += 1;
38
+ const mag = Math.hypot(x, y);
39
+ if (mag > 1) {
40
+ x /= mag;
41
+ y /= mag;
42
+ }
43
+ joystickRef.current.x = x;
44
+ joystickRef.current.y = y;
45
+ };
46
+
47
+ const clearAll = () => {
48
+ heldRef.current.clear();
49
+ joystickRef.current.x = 0;
50
+ joystickRef.current.y = 0;
51
+ };
52
+
53
+ // Selection changed -- don't let a key held before switching flies stick.
54
+ clearAll();
55
+ if (!selectedFlyId) return;
56
+
57
+ const onKeyDown = (e: KeyboardEvent) => {
58
+ if (ARROW_KEYS.has(e.key)) {
59
+ e.preventDefault();
60
+ heldRef.current.add(e.key);
61
+ applyFromHeld();
62
+ } else if (e.code === "Space") {
63
+ e.preventDefault();
64
+ onToggleFlyingRef.current();
65
+ } else if (e.key === "+" || e.key === "=") {
66
+ e.preventDefault();
67
+ onAltitudeStepRef.current(1);
68
+ } else if (e.key === "-" || e.key === "_") {
69
+ e.preventDefault();
70
+ onAltitudeStepRef.current(-1);
71
+ }
72
+ };
73
+
74
+ const onKeyUp = (e: KeyboardEvent) => {
75
+ if (ARROW_KEYS.has(e.key)) {
76
+ e.preventDefault();
77
+ heldRef.current.delete(e.key);
78
+ applyFromHeld();
79
+ }
80
+ };
81
+
82
+ window.addEventListener("keydown", onKeyDown);
83
+ window.addEventListener("keyup", onKeyUp);
84
+ window.addEventListener("blur", clearAll);
85
+ return () => {
86
+ window.removeEventListener("keydown", onKeyDown);
87
+ window.removeEventListener("keyup", onKeyUp);
88
+ window.removeEventListener("blur", clearAll);
89
+ clearAll();
90
+ };
91
+ }, [selectedFlyId, joystickRef]);
92
+ }
src/useLiveFlyState.ts CHANGED
@@ -1,7 +1,7 @@
1
  import { useRef } from "react";
2
  import { createBrain, type BrainState } from "./flyBrain";
3
  import { createGaitState, type GaitState } from "./tripodGait";
4
- import type { FlyInstanceData } from "./useFlyLayout";
5
  import { createWingControllerState, type WingControllerState } from "./wingController";
6
 
7
  export interface VisionState {
@@ -33,6 +33,12 @@ export interface LiveFlyState {
33
  batteryPercent: number;
34
  orderId: string;
35
  driving: boolean;
 
 
 
 
 
 
36
  }
37
 
38
  export type LiveFlyPositions = Map<string, LiveFlyState>;
@@ -56,6 +62,8 @@ export function useLiveFlyState(flies: FlyInstanceData[]) {
56
  batteryPercent: 100,
57
  orderId: "",
58
  driving: false,
 
 
59
  },
60
  ]),
61
  ),
 
1
  import { useRef } from "react";
2
  import { createBrain, type BrainState } from "./flyBrain";
3
  import { createGaitState, type GaitState } from "./tripodGait";
4
+ import { FLY_GROUND_OFFSET_MM, type FlyInstanceData } from "./useFlyLayout";
5
  import { createWingControllerState, type WingControllerState } from "./wingController";
6
 
7
  export interface VisionState {
 
33
  batteryPercent: number;
34
  orderId: string;
35
  driving: boolean;
36
+ /** Flight mode -- true while this fly is commanded airborne (App.tsx's
37
+ * flying/altitude UI state syncs onto whichever fly is selected). */
38
+ flying: boolean;
39
+ /** What live.y eases toward each frame (FlyInstances.tsx) -- ground
40
+ * offset while grounded/landing, one of altitudeLevels.ts's levels while flying. */
41
+ targetAltitudeMm: number;
42
  }
43
 
44
  export type LiveFlyPositions = Map<string, LiveFlyState>;
 
62
  batteryPercent: 100,
63
  orderId: "",
64
  driving: false,
65
+ flying: false,
66
+ targetAltitudeMm: FLY_GROUND_OFFSET_MM,
67
  },
68
  ]),
69
  ),