@pinkaphant/kolmo 0.5.0 → 0.5.2

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,145 +1,23 @@
1
- import { C as pilotedVehicleQuery, D as writeVehicleTelemetry, E as writeEntityKinematics, S as kolmoWorld, T as vehicleSimQuery, _ as VelocityTrait, a as G_SI, b as flipVehicleBodyUpright, c as evaluateNBodyGravity, d as InteractableTrait, f as PilotLink, g as VehicleTrait, h as VehicleTelemetryTrait, i as useOptionalKootaWorld, l as resolveAttractorMu, m as TransformTrait, n as KolmoPhysics, o as computeCircularOrbitSpeed, p as PilotedTag, r as useIsKolmoCustomGravity, s as createNBodyGravityField, t as KolmoGravityContext, u as ActorTrait, v as WorldSessionTrait, w as useActiveKolmoWorld, x as kolmoActions, y as ensureWorldSession } from "../physics-FhWvTBfH.js";
2
- import React, { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
- import { KeyboardControls, useKeyboardControls } from "@react-three/drei";
4
- import { Joystick, VirtualButton, useButtonStore, useJoystickStore } from "@pinkaphant/ecctrl/input";
1
+ import { A as writeEntityKinematics, C as flipVehicleBodyUpright, D as useActiveKolmoWorld, E as pilotedVehicleQuery, O as useOptionalKootaWorld, S as ensureWorldSession, T as kolmoWorld, _ as VehicleTelemetryTrait, a as computeCircularOrbitSpeed, b as WorldSessionTrait, c as evaluatePreparedNBodyGravity, d as ActorTrait, f as InteractableTrait, g as TransformTrait, h as PilotedTag, i as G_SI, j as writeVehicleTelemetry, k as vehicleSimQuery, l as prepareAttractors, m as PilotLink, n as KolmoPhysics, o as createNBodyGravityField, p as KolmoWorldContext, r as useIsKolmoCustomGravity, s as evaluateNBodyGravity, t as KolmoGravityContext, u as resolveAttractorMu, v as VehicleTrait, w as kolmoActions, x as createEmptyVehicleCmd, y as VelocityTrait } from "../physics-CA1abDCY.js";
2
+ import { _ as useKolmoInput, a as KolmoOverlayPortalContext, c as useKolmoGame, d as KolmoVehicle, f as EMPTY_KOLMO_INPUT, g as KolmoKeyboardContext, h as KolmoKeyboardBridge, i as KolmoInCanvasContext, l as KolmoProp, m as KOLMO_STICK_DEADZONE, n as KolmoGame, o as KolmoWorld, p as KOLMO_KEY_MAP, r as KolmoHud, s as RoomEnvRig, t as KolmoCanvas, u as KolmoSurface } from "../world-BljtS6Fb.js";
3
+ import { useCallback, useContext, useLayoutEffect, useMemo, useRef } from "react";
5
4
  import * as THREE from "three";
6
- import { Canvas, useFrame, useThree } from "@react-three/fiber";
7
- import { CuboidCollider, RigidBody, useRapier } from "@react-three/rapier";
8
- import { WorldProvider, useHas, useQueryFirst } from "koota/react";
5
+ import { clone } from "three/examples/jsm/utils/SkeletonUtils.js";
6
+ import { useFrame, useThree } from "@react-three/fiber";
7
+ import { useRapier } from "@react-three/rapier";
8
+ import { useQueryFirst } from "koota/react";
9
9
  import { Ecctrl } from "@pinkaphant/ecctrl";
10
10
  import { EcctrlCameraControls } from "@pinkaphant/ecctrl/camera";
11
+ import { assignRef, loadKhrGlb } from "@khr3/core";
11
12
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
- import { easing } from "maath";
13
- import { KhrAssembly, cloneKhrBundle, createKhrGltfPlugin, useKhrGlb } from "@khr3/core";
14
- import { KhrVehicle } from "@khr3/core/vehicle";
15
- import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
16
- import "koota";
17
13
  import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
18
14
  import { KTX2Loader } from "three/examples/jsm/loaders/KTX2Loader.js";
19
15
  import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";
20
- // src/engine/input.ts
21
- var KolmoKeyboardContext = createContext(null);
22
- function KolmoKeyboardBridge({ children }) {
23
- const [, getKeys] = useKeyboardControls();
24
- return React.createElement(KolmoKeyboardContext.Provider, { value: getKeys }, children);
25
- }
26
- var KOLMO_STICK_DEADZONE = .08;
27
- var EMPTY_KOLMO_INPUT = Object.freeze({
28
- forward: false,
29
- backward: false,
30
- left: false,
31
- right: false,
32
- brake: false,
33
- boost: false,
34
- interact: false,
35
- turnLeft: false,
36
- turnRight: false,
37
- descend: false,
38
- cameraView: false,
39
- reset: false,
40
- modeToggle: false,
41
- stickX: 0,
42
- stickY: 0
43
- });
44
- var KOLMO_KEY_MAP = [
45
- {
46
- name: "forward",
47
- keys: ["KeyW", "ArrowUp"]
48
- },
49
- {
50
- name: "backward",
51
- keys: ["KeyS", "ArrowDown"]
52
- },
53
- {
54
- name: "left",
55
- keys: ["KeyA", "ArrowLeft"]
56
- },
57
- {
58
- name: "right",
59
- keys: ["KeyD", "ArrowRight"]
60
- },
61
- {
62
- name: "brake",
63
- keys: ["Space"]
64
- },
65
- {
66
- name: "boost",
67
- keys: ["ShiftLeft", "ShiftRight"]
68
- },
69
- {
70
- name: "interact",
71
- keys: ["KeyF", "KeyE"]
72
- },
73
- {
74
- name: "turnLeft",
75
- keys: ["KeyQ"]
76
- },
77
- {
78
- name: "turnRight",
79
- keys: ["KeyC"]
80
- },
81
- {
82
- name: "descend",
83
- keys: ["KeyX", "ControlLeft"]
84
- },
85
- {
86
- name: "cameraView",
87
- keys: ["KeyV"]
88
- },
89
- {
90
- name: "reset",
91
- keys: ["KeyR"]
92
- },
93
- {
94
- name: "modeToggle",
95
- keys: ["KeyG"]
96
- }
97
- ];
98
- /**
99
- * Zero-allocation input reader merging Drei `<KeyboardControls>`, `@pinkaphant/ecctrl/input`
100
- * Zustand stores (`useJoystickStore` + `useButtonStore`), and optional `getInput()` overrides.
101
- */
102
- function useKolmoInput(getInput) {
103
- const getKeyboard = useContext(KolmoKeyboardContext);
104
- const getterRef = useRef(getInput);
105
- getterRef.current = getInput;
106
- const outRef = useRef({ ...EMPTY_KOLMO_INPUT });
107
- return useCallback(() => {
108
- const custom = getterRef.current?.();
109
- const k = getKeyboard ? getKeyboard() : EMPTY_KOLMO_INPUT;
110
- const rawStick = useJoystickStore.getState().joysticks.default;
111
- const btns = useButtonStore.getState().buttons;
112
- const rx = rawStick?.x ?? 0;
113
- const ry = rawStick?.y ?? 0;
114
- const mag = Math.hypot(rx, ry);
115
- const sx = custom?.stickX ?? (mag > .08 ? rx : 0);
116
- const sy = custom?.stickY ?? (mag > .08 ? ry : 0);
117
- const out = outRef.current;
118
- out.stickX = sx;
119
- out.stickY = sy;
120
- out.forward = Boolean(custom?.forward ?? (k.forward || sy > .2));
121
- out.backward = Boolean(custom?.backward ?? (k.backward || sy < -.2));
122
- out.left = Boolean(custom?.left ?? (k.left || sx < -.2));
123
- out.right = Boolean(custom?.right ?? (k.right || sx > .2));
124
- out.brake = Boolean(custom?.brake ?? (k.brake || btns.brake || btns.jump));
125
- out.boost = Boolean(custom?.boost ?? (k.boost || btns.boost || btns.run));
126
- out.interact = Boolean(custom?.interact ?? (k.interact || btns.interact));
127
- out.turnLeft = Boolean(custom?.turnLeft ?? (k.turnLeft || btns.turnLeft));
128
- out.turnRight = Boolean(custom?.turnRight ?? (k.turnRight || btns.turnRight));
129
- out.descend = Boolean(custom?.descend ?? (k.descend || btns.descend));
130
- out.cameraView = Boolean(custom?.cameraView ?? (k.cameraView || btns.cameraView));
131
- out.reset = Boolean(custom?.reset ?? (k.reset || btns.reset));
132
- out.modeToggle = Boolean(custom?.modeToggle ?? (k.modeToggle || btns.modeToggle));
133
- return out;
134
- }, [getKeyboard]);
135
- }
136
16
  // src/engine/actor.tsx
137
- function assignRefValue$2(ref, value) {
138
- if (typeof ref === "function") ref(value);
139
- else if (ref && typeof ref === "object") ref.current = value;
140
- }
141
17
  var _seatVec = new THREE.Vector3();
142
18
  var _camFwd = new THREE.Vector3();
19
+ var _worldUp = new THREE.Vector3(0, 1, 0);
20
+ var _exitQuat = new THREE.Quaternion();
143
21
  function findNearestInteractableVehicleId(world, actorPos) {
144
22
  let nearestId = null;
145
23
  let bestDistSq = 1e400;
@@ -162,13 +40,15 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
162
40
  0
163
41
  ], rotation, userData, children, ...ecctrlRest }) {
164
42
  const ctxCustomGravity = useContext(KolmoGravityContext);
43
+ const effCustomGravity = enableCustomGravity ?? ctxCustomGravity;
165
44
  const activeWorld = useActiveKolmoWorld();
166
45
  useLayoutEffect(() => {
167
46
  ensureWorldSession(activeWorld);
168
47
  }, [activeWorld]);
169
48
  const pilotedVehEnt = useQueryFirst(VehicleTrait, PilotedTag);
170
49
  const readInput = useKolmoInput(getInput);
171
- const hasDom = useThree((s) => typeof s.gl?.domElement?.setAttribute === "function");
50
+ const domElement = useThree((s) => s.gl?.domElement);
51
+ const hasDom = Boolean(domElement && typeof domElement.addEventListener === "function");
172
52
  const { world: rapierWorld } = useRapier();
173
53
  const actorEntRef = useRef(null);
174
54
  const ecctrlRef = useRef(null);
@@ -192,10 +72,48 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
192
72
  run: false,
193
73
  jump: false
194
74
  });
195
- const exitOverrideRef = useRef({
196
- pos: null,
197
- yaw: 0
198
- });
75
+ const applyPendingExit = useCallback((handle) => {
76
+ const ent = actorEntRef.current;
77
+ if (!handle?.body || !ent?.isAlive()) return;
78
+ const d = ent.get(ActorTrait);
79
+ if (!d?.exitSpawnPos) return;
80
+ const [ex, ey, ez] = d.exitSpawnPos;
81
+ _exitQuat.setFromAxisAngle(_worldUp, d.exitSpawnYaw);
82
+ handle.body.setTranslation({
83
+ x: ex,
84
+ y: ey,
85
+ z: ez
86
+ }, true);
87
+ handle.body.setRotation({
88
+ x: _exitQuat.x,
89
+ y: _exitQuat.y,
90
+ z: _exitQuat.z,
91
+ w: _exitQuat.w
92
+ }, true);
93
+ const lv = d.exitLinVel;
94
+ handle.body.setLinvel(lv ? {
95
+ x: lv[0],
96
+ y: lv[1],
97
+ z: lv[2]
98
+ } : {
99
+ x: 0,
100
+ y: 0,
101
+ z: 0
102
+ }, true);
103
+ handle.body.setAngvel({
104
+ x: 0,
105
+ y: 0,
106
+ z: 0
107
+ }, true);
108
+ handle.currPos.set(ex, ey, ez);
109
+ handle.currQuat.copy(_exitQuat);
110
+ ent.set(ActorTrait, {
111
+ ...d,
112
+ handle,
113
+ exitSpawnPos: null,
114
+ exitLinVel: null
115
+ });
116
+ }, []);
199
117
  useLayoutEffect(() => {
200
118
  const ent = activeWorld.spawn(ActorTrait({
201
119
  id: "pilot",
@@ -207,47 +125,51 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
207
125
  actorEntRef.current = ent;
208
126
  const prePiloted = activeWorld.queryFirst(pilotedVehicleQuery);
209
127
  if (prePiloted) ent.add(PilotLink(prePiloted));
210
- const unsub = activeWorld.onChange(ActorTrait, (changed) => {
211
- if (changed !== ent) return;
212
- const d = ent.get(ActorTrait);
213
- if (d) exitOverrideRef.current = {
214
- pos: d.exitSpawnPos,
215
- yaw: d.exitSpawnYaw
216
- };
217
- });
218
128
  return () => {
219
- unsub();
220
129
  actorEntRef.current = null;
221
130
  ent.destroy();
222
131
  };
223
132
  }, [activeWorld]);
133
+ const onFoot = enable && !pilotedVehEnt;
134
+ useLayoutEffect(() => {
135
+ const body = ecctrlRef.current?.body;
136
+ if (!onFoot) {
137
+ camSyncedRef.current = false;
138
+ body?.setEnabled(false);
139
+ return;
140
+ }
141
+ body?.setEnabled(true);
142
+ applyPendingExit(ecctrlRef.current);
143
+ }, [onFoot, applyPendingExit]);
224
144
  useLayoutEffect(() => {
225
145
  const ent = actorEntRef.current;
226
146
  if (ent && pilotedVehEnt && !ent.has(PilotLink(pilotedVehEnt))) ent.add(PilotLink(pilotedVehEnt));
227
147
  }, [pilotedVehEnt]);
228
148
  const assignEcctrlRef = useCallback((handle) => {
229
149
  ecctrlRef.current = handle;
230
- assignRefValue$2(ref, handle);
150
+ assignRef(ref, handle);
231
151
  const ent = actorEntRef.current;
232
152
  if (!ent?.isAlive()) return;
233
153
  const cur = ent.get(ActorTrait);
234
- if (handle?.body && cur?.exitLinVel) handle.body.setLinvel({
235
- x: cur.exitLinVel[0],
236
- y: cur.exitLinVel[1],
237
- z: cur.exitLinVel[2]
238
- }, true);
239
- if (handle?.body) exitOverrideRef.current.pos = null;
154
+ const isFoot = enable && !activeWorld.queryFirst(pilotedVehicleQuery);
155
+ handle?.body?.setEnabled(isFoot);
240
156
  ent.set(ActorTrait, {
241
157
  id: cur?.id ?? "pilot",
242
158
  handle,
243
- exitSpawnPos: handle?.body ? null : cur?.exitSpawnPos ?? null,
159
+ exitSpawnPos: cur?.exitSpawnPos ?? null,
244
160
  exitSpawnYaw: cur?.exitSpawnYaw ?? 0,
245
- exitLinVel: handle?.body ? null : cur?.exitLinVel ?? null
161
+ exitLinVel: cur?.exitLinVel ?? null
246
162
  });
247
- }, [ref]);
163
+ if (isFoot) applyPendingExit(handle);
164
+ }, [
165
+ ref,
166
+ enable,
167
+ activeWorld,
168
+ applyPendingExit
169
+ ]);
248
170
  const assignCamRef = useCallback((ctrl) => {
249
171
  camCtrlRef.current = ctrl;
250
- assignRefValue$2(cameraRef, ctrl);
172
+ assignRef(cameraRef, ctrl);
251
173
  }, [cameraRef]);
252
174
  const mergedUserData = useMemo(() => {
253
175
  const base = userData ?? {};
@@ -260,9 +182,7 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
260
182
  }
261
183
  };
262
184
  }, [userData]);
263
- const clonedScene = useMemo(() => bundle ? bundle.scene.clone(true) : null, [bundle]);
264
- const onFoot = enable && !pilotedVehEnt;
265
- if (!onFoot) camSyncedRef.current = false;
185
+ const clonedScene = useMemo(() => bundle ? clone(bundle.scene) : null, [bundle]);
266
186
  useFrame((state, delta) => {
267
187
  if (!enable) return;
268
188
  const dt = rapierWorld.timestep > 0 ? rapierWorld.timestep : Math.min(Math.max(delta, 1e-4), 1 / 30);
@@ -303,968 +223,88 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
303
223
  }
304
224
  const cam = camCtrlRef.current;
305
225
  if (cam && handle.currPos.lengthSq() > 0) {
306
- const hasValidUp = handle.upAxis.lengthSq() > .25;
307
- if (hasValidUp) followUp.current.copy(handle.upAxis).normalize();
226
+ if (handle.upAxis.lengthSq() > .25) followUp.current.copy(handle.upAxis).normalize();
227
+ else followUp.current.copy(_worldUp);
308
228
  followPos.current.copy(handle.currPos).addScaledVector(followUp.current, .55);
309
229
  if (!camSyncedRef.current) {
310
230
  camSyncedRef.current = true;
311
- if (hasValidUp) {
312
- state.camera.up.copy(followUp.current);
313
- cam.setUp(followUp.current);
314
- }
231
+ state.camera.up.copy(followUp.current);
232
+ cam.setUp(followUp.current);
315
233
  _camFwd.copy(handle.bodyZAxis).projectOnPlane(followUp.current);
316
234
  if (_camFwd.lengthSq() < 1e-4) _camFwd.set(0, 0, -1).projectOnPlane(followUp.current);
317
235
  _camFwd.normalize();
318
236
  cam.setLookAt(followPos.current.x - _camFwd.x * 7.5 + followUp.current.x * 2.4, followPos.current.y - _camFwd.y * 7.5 + followUp.current.y * 2.4, followPos.current.z - _camFwd.z * 7.5 + followUp.current.z * 2.4, followPos.current.x, followPos.current.y, followPos.current.z, false);
319
237
  } else {
320
238
  cam.moveTo(followPos.current.x, followPos.current.y, followPos.current.z, true);
321
- if (hasValidUp) {
239
+ if (effCustomGravity && state.camera.up.distanceToSquared(followUp.current) > 1e-6) {
322
240
  state.camera.up.lerp(followUp.current, 1 - Math.exp(-8 * dt)).normalize();
323
241
  cam.setUp(state.camera.up);
324
242
  }
325
243
  }
326
244
  }
327
245
  });
328
- if (!onFoot) return null;
329
- const spawnPos = exitOverrideRef.current.pos ?? position;
330
- const spawnRot = rotation ?? (exitOverrideRef.current.pos ? [
331
- 0,
332
- exitOverrideRef.current.yaw,
333
- 0
334
- ] : void 0);
335
246
  return /* @__PURE__ */ jsxs(Fragment, { children: [hasDom && cameraProps !== false && cameraProps !== null && /* @__PURE__ */ jsx(EcctrlCameraControls, {
336
247
  ref: assignCamRef,
337
248
  makeDefault: true,
249
+ enabled: onFoot,
338
250
  minPolarAngle: .12,
339
251
  maxPolarAngle: Math.PI - .12,
340
252
  smoothTime: .08,
341
253
  ...cameraProps ?? {}
342
- }), /* @__PURE__ */ jsx(Ecctrl, {
343
- ref: assignEcctrlRef,
344
- enable,
345
- enableCustomGravity: enableCustomGravity ?? ctxCustomGravity,
346
- position: spawnPos,
347
- ...spawnRot === void 0 ? {} : { rotation: spawnRot },
348
- userData: mergedUserData,
349
- ...ecctrlRest,
350
- children: children ?? (clonedScene ? /* @__PURE__ */ jsx("primitive", { object: clonedScene }) : null)
351
- })] });
352
- }
353
- // src/engine/vehicle.tsx
354
- function assignRefValue$1(ref, value) {
355
- if (typeof ref === "function") ref(value);
356
- else if (ref && typeof ref === "object") ref.current = value;
357
- }
358
- function createEmptyVehicleCmd() {
359
- return {
360
- forward: false,
361
- backward: false,
362
- steerLeft: false,
363
- steerRight: false,
364
- brake: false,
365
- throttleUp: false,
366
- throttleDown: false,
367
- yawLeft: false,
368
- yawRight: false,
369
- pitchForward: false,
370
- pitchBackward: false,
371
- rollLeft: false,
372
- rollRight: false,
373
- joystickL: {
374
- x: 0,
375
- y: 0
376
- },
377
- joystickR: {
378
- x: 0,
379
- y: 0
380
- }
381
- };
382
- }
383
- function hasActiveCmd(c) {
384
- return Boolean(c.forward || c.backward || c.steerLeft || c.steerRight || c.brake || c.throttleUp || c.throttleDown || c.yawLeft || c.yawRight || c.pitchForward || c.pitchBackward || c.rollLeft || c.rollRight || c.joystickL && (c.joystickL.x !== 0 || c.joystickL.y !== 0) || c.joystickR && (c.joystickR.x !== 0 || c.joystickR.y !== 0));
385
- }
386
- var _up = new THREE.Vector3();
387
- var _fwd = new THREE.Vector3();
388
- var _camGoal = new THREE.Vector3();
389
- var _lookGoal = new THREE.Vector3();
390
- function KolmoVehicleMount({ ref, vehicleRef, jointsRef: outerJointsRef, id, sourceBundle, piloted = false, flightMode = false, vehicleMode, interactRadius = 4.2, enable = true, enableCustomGravity, wheelConfig, propellerConfig, droneConfig, getInput, driver, cameraController, children, ...khrRest }) {
391
- const ctxCustomGravity = useContext(KolmoGravityContext);
392
- const activeWorld = useActiveKolmoWorld();
393
- useLayoutEffect(() => {
394
- ensureWorldSession(activeWorld);
395
- }, [activeWorld]);
396
- const readInput = useKolmoInput(getInput);
397
- const bundle = useMemo(() => cloneKhrBundle(sourceBundle), [sourceBundle]);
398
- const jointsRef = useRef(null);
399
- const innerRef = useRef(null);
400
- const canHybridToggle = vehicleMode === void 0 && bundle.wheels.length > 0 && bundle.propellers.length > 0;
401
- const [hybridFlight, setHybridFlight] = useState(flightMode);
402
- useLayoutEffect(() => {
403
- setHybridFlight(flightMode);
404
- }, [flightMode]);
405
- const [boostThrustActive, setBoostThrustActive] = useState(false);
406
- const boostThrustRef = useRef(false);
407
- const isFlight = Boolean(vehicleMode === "rocket" || (canHybridToggle ? hybridFlight : flightMode) || vehicleMode !== "drive" && bundle.propellers.length > 0 && bundle.wheels.length === 0);
408
- const seatOffset = useMemo(() => {
409
- const dot = bundle.sockets.butt ?? bundle.sockets.driver_butt ?? bundle.sockets.seat ?? bundle.sockets.IK_Seat;
410
- return dot ? [
411
- dot[0],
412
- dot[1],
413
- dot[2]
414
- ] : [
415
- 0,
416
- .65,
417
- 0
418
- ];
419
- }, [bundle.sockets]);
420
- const exitOffset = useMemo(() => {
421
- const dot = bundle.sockets.exit ?? bundle.sockets.Socket_Exit;
422
- return dot ? [
423
- dot[0],
424
- dot[1],
425
- dot[2]
426
- ] : [
427
- -1.55,
428
- .45,
429
- 0
430
- ];
431
- }, [bundle.sockets]);
432
- const propActive = bundle.propellers.length > 0 && (isFlight || vehicleMode !== "drive" && boostThrustActive);
433
- const mergedWheelConfig = useMemo(() => {
434
- const wheelOverride = bundle.wheels.length > 0 && vehicleMode === "rocket" ? { enable: false } : void 0;
435
- return !wheelConfig && !wheelOverride ? void 0 : {
436
- ...wheelOverride,
437
- ...wheelConfig ?? {}
438
- };
439
- }, [
440
- bundle.wheels.length,
441
- vehicleMode,
442
- wheelConfig
443
- ]);
444
- const mergedPropellerConfig = useMemo(() => {
445
- const propOverride = bundle.propellers.length > 0 && !propActive ? { enable: false } : void 0;
446
- return !propellerConfig && !propOverride ? void 0 : {
447
- ...propOverride,
448
- ...propellerConfig ?? {}
449
- };
450
- }, [
451
- bundle.propellers.length,
452
- propActive,
453
- propellerConfig
454
- ]);
455
- const [vehEnt, setVehEnt] = useState(null);
456
- const vehEntRef = useRef(null);
457
- const camTargetRef = useRef(new THREE.Vector3());
458
- const cmdRef = useRef(createEmptyVehicleCmd());
459
- const stRef = useRef({
460
- camInit: false,
461
- cockpit: false,
462
- prevCam: false,
463
- prevReset: false,
464
- prevMode: false,
465
- wasPiloted: false
466
- });
467
- useLayoutEffect(() => {
468
- const ent = activeWorld.spawn(VehicleTrait({
469
- id,
470
- handle: innerRef.current,
471
- seatOffset,
472
- exitOffset,
473
- isFlight
474
- }), InteractableTrait({
475
- id,
476
- radius: interactRadius,
477
- kind: "vehicle"
478
- }), TransformTrait, VelocityTrait, VehicleTelemetryTrait);
479
- vehEntRef.current = ent;
480
- setVehEnt(ent);
481
- if (piloted && !activeWorld.queryFirst(pilotedVehicleQuery)) kolmoActions(activeWorld).boardVehicle(id);
482
- return () => {
483
- if (ent.isAlive() && ent.has(PilotedTag)) kolmoActions(activeWorld).exitVehicle();
484
- vehEntRef.current = null;
485
- ent.destroy();
486
- };
487
- }, [
488
- activeWorld,
489
- id,
490
- seatOffset,
491
- exitOffset,
492
- interactRadius,
493
- piloted
494
- ]);
495
- useLayoutEffect(() => {
496
- const ent = vehEntRef.current;
497
- if (!ent?.isAlive()) return;
498
- const v = ent.get(VehicleTrait);
499
- if (v && v.isFlight !== isFlight) ent.set(VehicleTrait, {
500
- ...v,
501
- isFlight
502
- });
503
- }, [isFlight]);
504
- const assignVehicleRef = useCallback((handle) => {
505
- innerRef.current = handle;
506
- assignRefValue$1(vehicleRef, handle);
507
- assignRefValue$1(ref, handle);
508
- const ent = vehEntRef.current;
509
- if (ent?.isAlive()) {
510
- const v = ent.get(VehicleTrait);
511
- if (v) ent.set(VehicleTrait, {
512
- ...v,
513
- handle
514
- });
515
- }
516
- }, [ref, vehicleRef]);
517
- const assignJointsRef = useCallback((jh) => {
518
- jointsRef.current = jh;
519
- assignRefValue$1(outerJointsRef, jh);
520
- }, [outerJointsRef]);
521
- const { world: rapierWorld } = useRapier();
522
- const isPiloted = useHas(vehEnt, PilotedTag) || piloted && vehEnt === null;
523
- useFrame((state, delta) => {
524
- const dt = rapierWorld.timestep > 0 ? rapierWorld.timestep : Math.min(Math.max(delta, 1e-4), 1 / 30);
525
- const veh = innerRef.current;
526
- if (!veh?.body) return;
527
- if (driver) {
528
- driver(veh, dt, state);
529
- cameraController?.(veh, dt, state);
530
- return;
531
- }
532
- const keys = readInput();
533
- const st = stRef.current;
534
- const cmd = cmdRef.current;
535
- const wantBoostProp = isPiloted && !isFlight && vehicleMode !== "drive" && bundle.propellers.length > 0 && keys.boost && (keys.forward || keys.brake);
536
- if (wantBoostProp !== boostThrustRef.current) {
537
- boostThrustRef.current = wantBoostProp;
538
- setBoostThrustActive(wantBoostProp);
539
- }
540
- if (isPiloted) {
541
- st.wasPiloted = true;
542
- if (keys.cameraView && !st.prevCam) st.cockpit = !st.cockpit;
543
- st.prevCam = keys.cameraView;
544
- if (keys.reset && !st.prevReset) {
545
- flipVehicleBodyUpright(veh);
546
- jointsRef.current?.syncBodiesToParent();
547
- }
548
- st.prevReset = keys.reset;
549
- if (keys.modeToggle && !st.prevMode && canHybridToggle) setHybridFlight((f) => !f);
550
- st.prevMode = keys.modeToggle;
551
- let anyGrounded = false;
552
- for (const w of veh.wheelsInfo.values()) if (w.current.rayHit) {
553
- anyGrounded = true;
554
- break;
555
- }
556
- if (isFlight) {
557
- cmd.pitchForward = keys.forward;
558
- cmd.pitchBackward = keys.backward;
559
- cmd.yawLeft = keys.left;
560
- cmd.yawRight = keys.right;
561
- cmd.rollLeft = keys.turnLeft;
562
- cmd.rollRight = keys.turnRight;
563
- cmd.throttleUp = keys.brake;
564
- cmd.throttleDown = keys.descend;
565
- cmd.forward = anyGrounded && keys.forward;
566
- cmd.backward = anyGrounded && keys.backward;
567
- cmd.steerLeft = anyGrounded && keys.left;
568
- cmd.steerRight = anyGrounded && keys.right;
569
- cmd.brake = false;
570
- cmd.joystickL = {
571
- x: 0,
572
- y: 0
573
- };
574
- cmd.joystickR = {
575
- x: keys.stickX,
576
- y: keys.stickY
577
- };
578
- veh.setMovement(cmd);
579
- } else {
580
- const fwdVel = veh.currLinVel.dot(veh.bodyZAxis);
581
- const revBraking = keys.backward && !keys.forward && fwdVel > 1;
582
- const fwdBraking = keys.forward && !keys.backward && fwdVel < -1;
583
- if ((keys.backward && !revBraking || keys.forward && Math.abs(fwdVel) < 2.5) && veh.gearIndex !== 0) veh.setGear(0);
584
- const boostProp = keys.boost && (bundle.propellers.length > 0 || veh.propellersInfo.size > 0) && veh.gravityMag > 1e-4;
585
- cmd.forward = keys.forward && !fwdBraking;
586
- cmd.backward = keys.backward && !revBraking;
587
- cmd.steerLeft = keys.left;
588
- cmd.steerRight = keys.right;
589
- cmd.brake = keys.brake || revBraking || fwdBraking;
590
- cmd.pitchForward = boostProp && keys.forward;
591
- cmd.pitchBackward = false;
592
- cmd.throttleUp = boostProp && !keys.forward && keys.brake;
593
- cmd.throttleDown = false;
594
- cmd.yawLeft = boostProp && keys.left;
595
- cmd.yawRight = boostProp && keys.right;
596
- cmd.rollLeft = cmd.rollRight = false;
597
- cmd.joystickL = {
598
- x: keys.stickX,
599
- y: 0
600
- };
601
- cmd.joystickR = {
602
- x: 0,
603
- y: 0
604
- };
605
- veh.setMovement(cmd);
606
- }
607
- } else {
608
- st.prevCam = st.prevReset = st.prevMode = false;
609
- if (st.wasPiloted || hasActiveCmd(cmd)) {
610
- st.wasPiloted = false;
611
- Object.assign(cmd, createEmptyVehicleCmd());
612
- veh.setMovement(cmd);
613
- }
614
- }
615
- let maxSlip = 0;
616
- for (const w of veh.wheelsInfo.values()) if (w.current.rayHit && w.current.slipStrength > maxSlip) maxSlip = w.current.slipStrength;
617
- const speedKmh = veh.currLinVel.length() * 3.6;
618
- const throttle = isPiloted ? +(keys.forward || isFlight && keys.brake) : 0;
619
- const boost = isPiloted && keys.boost && throttle > 0 ? 1 : 0;
620
- const rpm = Math.round(veh.engineRPM);
621
- const gear = veh.gearIndex + 1;
622
- if (vehEntRef.current?.isAlive()) {
623
- writeEntityKinematics(activeWorld, vehEntRef.current, veh.currPos, veh.currQuat, veh.currLinVel, speedKmh);
624
- writeVehicleTelemetry(activeWorld, vehEntRef.current, rpm, gear, throttle, boost, Math.min(1, maxSlip));
625
- }
626
- if (!isPiloted) return;
627
- if (cameraController) {
628
- cameraController(veh, dt, state);
629
- return;
630
- }
631
- _up.copy(veh.upAxis);
632
- if (_up.lengthSq() < 1e-6) _up.copy(veh.bodyYAxis);
633
- if (st.cockpit) {
634
- _camGoal.set(seatOffset[0], seatOffset[1] + .32, seatOffset[2]).applyQuaternion(veh.currQuat).add(veh.currPos);
635
- _lookGoal.copy(_camGoal).addScaledVector(veh.bodyZAxis, 24);
636
- easing.damp3(state.camera.position, _camGoal, .04, dt);
637
- easing.damp3(state.camera.up, veh.bodyYAxis, .08, dt);
638
- state.camera.lookAt(_lookGoal);
639
- return;
640
- }
641
- _fwd.copy(veh.bodyZAxis);
642
- if (!isFlight) _fwd.projectOnPlane(_up).normalize();
643
- if (_fwd.lengthSq() < 1e-6) _fwd.copy(veh.bodyZAxis);
644
- _camGoal.copy(veh.currPos).addScaledVector(_fwd, isFlight ? -11.2 : -6.8).addScaledVector(_up, isFlight ? 3.1 : 2.15);
645
- _lookGoal.copy(veh.currPos).addScaledVector(_fwd, isFlight ? 7.5 : 3.6).addScaledVector(_up, .65);
646
- if (!st.camInit) {
647
- state.camera.position.copy(_camGoal);
648
- camTargetRef.current.copy(_lookGoal);
649
- st.camInit = true;
650
- }
651
- easing.damp3(state.camera.position, _camGoal, .14, dt);
652
- easing.damp3(camTargetRef.current, _lookGoal, .08, dt);
653
- easing.damp3(state.camera.up, _up, .16, dt);
654
- state.camera.lookAt(camTargetRef.current);
655
- });
656
- return /* @__PURE__ */ jsx("group", {
657
- onClick: (e) => {
658
- if (e.delta <= 5 && jointsRef.current?.toggleHitObject(e.object)) e.stopPropagation();
659
- },
660
- children: /* @__PURE__ */ jsx(KhrVehicle, {
661
- ref: assignVehicleRef,
662
- jointsRef: assignJointsRef,
663
- bundle,
664
- enable,
665
- enableCustomGravity: enableCustomGravity ?? ctxCustomGravity,
666
- ...mergedWheelConfig === void 0 ? {} : { wheelConfig: mergedWheelConfig },
667
- ...mergedPropellerConfig === void 0 ? {} : { propellerConfig: mergedPropellerConfig },
668
- ...droneConfig === void 0 ? {} : { droneConfig },
669
- ...khrRest,
670
- children
254
+ }), /* @__PURE__ */ jsx("group", {
255
+ visible: onFoot,
256
+ children: /* @__PURE__ */ jsx(Ecctrl, {
257
+ ref: assignEcctrlRef,
258
+ enable: onFoot,
259
+ enableCustomGravity: effCustomGravity,
260
+ position,
261
+ ...rotation === void 0 ? {} : { rotation },
262
+ userData: mergedUserData,
263
+ ...ecctrlRest,
264
+ children: children ?? (clonedScene ? /* @__PURE__ */ jsx("primitive", { object: clonedScene }) : null)
671
265
  })
672
- });
673
- }
674
- function KolmoVehicleFromUrl(props) {
675
- const { src, ...rest } = props;
676
- const bundle = useKhrGlb(src);
677
- return /* @__PURE__ */ jsx(KolmoVehicleMount, {
678
- ...rest,
679
- sourceBundle: bundle
680
- });
681
- }
682
- function KolmoVehicle(props) {
683
- const reactId = useId();
684
- const id = props.id ?? `vehicle_${reactId.replace(/:/g, "")}`;
685
- const { src, bundle, ...rest } = props;
686
- if (bundle) return /* @__PURE__ */ jsx(KolmoVehicleMount, {
687
- ...rest,
688
- id,
689
- sourceBundle: bundle
690
- });
691
- if (src) return /* @__PURE__ */ jsx(KolmoVehicleFromUrl, {
692
- ...rest,
693
- id,
694
- src
695
- });
696
- return null;
697
- }
698
- // src/engine/surface.tsx
699
- function assignRefValue(ref, value) {
700
- if (typeof ref === "function") ref(value);
701
- else if (ref && typeof ref === "object") ref.current = value;
702
- }
703
- function ArenaSlab({ size, position, color = "#252b36" }) {
704
- const res = useMemo(() => ({
705
- geo: new THREE.BoxGeometry(size, 1, size),
706
- mat: new THREE.MeshStandardMaterial({
707
- color,
708
- roughness: .9,
709
- metalness: .05
710
- })
711
- }), [size, color]);
712
- useEffect(() => () => {
713
- res.geo.dispose();
714
- res.mat.dispose();
715
- }, [res]);
716
- return /* @__PURE__ */ jsxs(RigidBody, {
717
- type: "fixed",
718
- colliders: false,
719
- position: [
720
- position[0],
721
- position[1] - .5,
722
- position[2]
723
- ],
724
- friction: .9,
725
- children: [/* @__PURE__ */ jsx(CuboidCollider, {
726
- args: [
727
- size * .5,
728
- .5,
729
- size * .5
730
- ],
731
- restitution: .04
732
- }), /* @__PURE__ */ jsx("mesh", {
733
- geometry: res.geo,
734
- material: res.mat,
735
- receiveShadow: true
736
- })]
737
- });
738
- }
739
- function BundleSurface({ ref, bundle, position, ...rest }) {
740
- const cloned = useMemo(() => cloneKhrBundle(bundle), [bundle]);
741
- return /* @__PURE__ */ jsx(KhrAssembly, {
742
- ref,
743
- bundle: cloned,
744
- position,
745
- fixedRoot: true,
746
- ...rest
747
- });
748
- }
749
- function UrlSurface({ src, ...rest }) {
750
- const bundle = useKhrGlb(src);
751
- return /* @__PURE__ */ jsx(BundleSurface, {
752
- bundle,
753
- ...rest
754
- });
755
- }
756
- function KolmoSurface({ ref, src, bundle, size = 200, color, position = [
757
- 0,
758
- 0,
759
- 0
760
- ], ...rest }) {
761
- if (bundle) return /* @__PURE__ */ jsx(BundleSurface, {
762
- ref,
763
- bundle,
764
- position,
765
- ...rest
766
- });
767
- if (src) return /* @__PURE__ */ jsx(UrlSurface, {
768
- ref,
769
- src,
770
- position,
771
- ...rest
772
- });
773
- return /* @__PURE__ */ jsx(ArenaSlab, {
774
- size,
775
- position,
776
- color
777
- });
778
- }
779
- function resolveJointTargets(limits) {
780
- if (!limits) return {
781
- open: Math.PI / 2,
782
- closed: 0
783
- };
784
- const [lo, hi] = limits;
785
- return {
786
- open: Math.abs(hi) >= Math.abs(lo) ? hi : lo,
787
- closed: Math.min(hi, Math.max(lo, 0))
788
- };
789
- }
790
- function togglePropJoint(handle, bundle, openState, clickedObj, perBodyOpen) {
791
- if (!handle) return openState;
792
- if (clickedObj && perBodyOpen) {
793
- let cur = clickedObj;
794
- while (cur) {
795
- const hit = bundle.bodies.find((b) => b.object === cur && b.joint?.drive?.stiffness !== void 0);
796
- if (hit) {
797
- const nextOpen = !(perBodyOpen.get(hit.nodeName) ?? false);
798
- perBodyOpen.set(hit.nodeName, nextOpen);
799
- const { open, closed } = resolveJointTargets(hit.joint?.limits ?? null);
800
- handle.setJointTarget(hit.nodeName, nextOpen ? open : closed);
801
- return nextOpen;
802
- }
803
- cur = cur.parent;
804
- }
805
- }
806
- const nextAll = !openState;
807
- for (const b of bundle.bodies) {
808
- if (!b.joint?.drive || b.joint.drive.stiffness === void 0) continue;
809
- const { open, closed } = resolveJointTargets(b.joint.limits);
810
- perBodyOpen?.set(b.nodeName, nextAll);
811
- handle.setJointTarget(b.nodeName, nextAll ? open : closed);
812
- }
813
- return nextAll;
814
- }
815
- function BundleProp({ ref, bundle, fixed = false, onClick: userOnClick, ...rest }) {
816
- const asmRef = useRef(null);
817
- const openRef = useRef(false);
818
- const perBodyRef = useRef(/* @__PURE__ */ new Map());
819
- const cloned = useMemo(() => cloneKhrBundle(bundle), [bundle]);
820
- const assignAsmRef = useCallback((h) => {
821
- asmRef.current = h;
822
- assignRefValue(ref, h);
823
- }, [ref]);
824
- const onClick = useCallback((e) => {
825
- e.stopPropagation();
826
- openRef.current = togglePropJoint(asmRef.current, cloned, openRef.current, e.object, perBodyRef.current);
827
- userOnClick?.(e);
828
- }, [cloned, userOnClick]);
829
- return /* @__PURE__ */ jsx(KhrAssembly, {
830
- ref: assignAsmRef,
831
- bundle: cloned,
832
- fixedRoot: fixed,
833
- onClick,
834
- ...rest
835
- });
836
- }
837
- function UrlProp({ src, ...rest }) {
838
- const bundle = useKhrGlb(src);
839
- return /* @__PURE__ */ jsx(BundleProp, {
840
- bundle,
841
- ...rest
842
- });
843
- }
844
- function KolmoProp({ src, bundle, ...rest }) {
845
- if (bundle) return /* @__PURE__ */ jsx(BundleProp, {
846
- bundle,
847
- ...rest
848
- });
849
- if (src) return /* @__PURE__ */ jsx(UrlProp, {
850
- src,
851
- ...rest
852
- });
853
- return null;
854
- }
855
- // src/engine/world.tsx
856
- var KolmoInCanvasContext = createContext(false);
857
- var KolmoOverlayContext = createContext(null);
858
- function RoomEnvRig({ intensity = .65 }) {
859
- const { gl, scene } = useThree();
860
- useEffect(() => {
861
- const pmrem = new THREE.PMREMGenerator(gl);
862
- const room = new RoomEnvironment();
863
- const rt = pmrem.fromScene(room, .04);
864
- const prevEnv = scene.environment;
865
- const prevInt = scene.environmentIntensity;
866
- scene.environment = rt.texture;
867
- scene.environmentIntensity = intensity;
868
- room.dispose();
869
- pmrem.dispose();
870
- return () => {
871
- scene.environment = prevEnv;
872
- scene.environmentIntensity = prevInt;
873
- rt.dispose();
874
- };
875
- }, [
876
- gl,
877
- scene,
878
- intensity
879
- ]);
880
- return null;
881
- }
882
- function KolmoCanvas({ children, className, style, fov = 56, near = .15, far = 4e3, cameraPosition = [
883
- 0,
884
- 3.2,
885
- -8.5
886
- ], dpr = [1, 1.5], frameloop = "always", shadows = true, antialias = true, toneMapping, roomEnv = .65 }) {
887
- return /* @__PURE__ */ jsxs(Canvas, {
888
- className,
889
- style: {
890
- width: "100%",
891
- height: "100%",
892
- display: "block",
893
- touchAction: "none",
894
- userSelect: "none",
895
- ...style
896
- },
897
- shadows,
898
- dpr,
899
- frameloop,
900
- gl: {
901
- antialias,
902
- powerPreference: "high-performance",
903
- ...toneMapping === void 0 ? {} : { toneMapping }
904
- },
905
- camera: {
906
- fov,
907
- near,
908
- far,
909
- position: cameraPosition
910
- },
911
- onCreated: ({ gl }) => {
912
- gl.outputColorSpace = THREE.SRGBColorSpace;
913
- },
914
- children: [roomEnv !== false && /* @__PURE__ */ jsx(RoomEnvRig, { intensity: typeof roomEnv === "number" ? roomEnv : .65 }), children]
915
- });
916
- }
917
- function KolmoWorld({ gravity = "planar", paused = false, timeScale = 1, maxDelta, physicsDebug = false, skybox = "day", lighting = "default", fogExp2, sunLightRef, world = kolmoWorld, keyboardMap = KOLMO_KEY_MAP, children }) {
918
- const outerWorld = useOptionalKootaWorld();
919
- const effectiveWorld = world ?? outerWorld ?? kolmoWorld;
920
- useLayoutEffect(() => {
921
- ensureWorldSession(effectiveWorld);
922
- }, [effectiveWorld]);
923
- const inner = /* @__PURE__ */ jsxs(KolmoInCanvasContext.Provider, {
924
- value: true,
925
- children: [
926
- skybox === "day" && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("color", {
927
- attach: "background",
928
- args: ["#6ba6d6"]
929
- }), !fogExp2 && /* @__PURE__ */ jsx("fog", {
930
- attach: "fog",
931
- args: [
932
- "#9dc4e2",
933
- 110,
934
- 520
935
- ]
936
- })] }),
937
- skybox === "night" && /* @__PURE__ */ jsx("color", {
938
- attach: "background",
939
- args: ["#090d16"]
940
- }),
941
- fogExp2 && /* @__PURE__ */ jsx("fogExp2", {
942
- attach: "fog",
943
- args: fogExp2
944
- }),
945
- lighting === "default" && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("hemisphereLight", { args: [
946
- "#b8dcff",
947
- "#241d30",
948
- .8
949
- ] }), /* @__PURE__ */ jsx("directionalLight", {
950
- ref: sunLightRef,
951
- position: [
952
- 48,
953
- 76,
954
- 36
955
- ],
956
- intensity: 1.85,
957
- color: "#fff3dc",
958
- castShadow: true,
959
- "shadow-mapSize": [1024, 1024]
960
- })] }),
961
- /* @__PURE__ */ jsx(KolmoPhysics, {
962
- gravity,
963
- paused,
964
- timeScale,
965
- maxDelta,
966
- physicsDebug,
967
- world: null,
968
- children
969
- })
970
- ]
971
- });
972
- const withKeyboard = keyboardMap ? /* @__PURE__ */ jsx(KeyboardControls, {
973
- map: keyboardMap,
974
- children: /* @__PURE__ */ jsx(KolmoKeyboardBridge, { children: inner })
975
- }) : /* @__PURE__ */ jsx(KolmoKeyboardContext.Provider, {
976
- value: null,
977
- children: inner
978
- });
979
- return effectiveWorld !== outerWorld ? /* @__PURE__ */ jsx(WorldProvider, {
980
- world: effectiveWorld,
981
- children: withKeyboard
982
- }) : withKeyboard;
983
- }
984
- function useKolmoGame(explicitWorld) {
985
- const active = useActiveKolmoWorld();
986
- const targetWorld = explicitWorld ?? active;
987
- const [, bump] = useReducer((x) => x + 1, 0);
988
- useEffect(() => {
989
- ensureWorldSession(targetWorld);
990
- const onChange = () => bump();
991
- const u1 = targetWorld.onChange(WorldSessionTrait, onChange);
992
- const u2 = targetWorld.onAdd(PilotedTag, onChange);
993
- const u3 = targetWorld.onRemove(PilotedTag, onChange);
994
- const u4 = targetWorld.onAdd(PilotLink, onChange);
995
- const u5 = targetWorld.onRemove(PilotLink, onChange);
996
- const u6 = targetWorld.onChange(VehicleTrait, onChange);
997
- return () => {
998
- u1();
999
- u2();
1000
- u3();
1001
- u4();
1002
- u5();
1003
- u6();
1004
- };
1005
- }, [targetWorld]);
1006
- const session = targetWorld.has(WorldSessionTrait) ? targetWorld.get(WorldSessionTrait) : void 0;
1007
- const pilotedData = (targetWorld.queryFirst(ActorTrait)?.targetFor(PilotLink) ?? targetWorld.queryFirst(pilotedVehicleQuery))?.get(VehicleTrait);
1008
- const actions = kolmoActions(targetWorld);
1009
- return {
1010
- world: targetWorld,
1011
- mode: pilotedData ? pilotedData.isFlight ? "flight" : "car" : "foot",
1012
- activeVehicleId: pilotedData?.id ?? "",
1013
- nearVehicleId: session?.nearVehicleId || null,
1014
- boardVehicle: actions.boardVehicle,
1015
- exitVehicle: actions.exitVehicle,
1016
- resetVehicle: actions.resetVehicle
1017
- };
1018
- }
1019
- function detectTouchDevice() {
1020
- if (typeof window === "undefined") return false;
1021
- return navigator.maxTouchPoints > 0 || window.matchMedia?.("(pointer: coarse)")?.matches === true;
1022
- }
1023
- function KolmoHudDom({ showTouchControls, style }) {
1024
- const world = useActiveKolmoWorld();
1025
- const telemetryRef = useRef(null);
1026
- const promptRef = useRef(null);
1027
- const [isTouch, setIsTouch] = useState(detectTouchDevice);
1028
- useEffect(() => {
1029
- setIsTouch(detectTouchDevice());
1030
- }, []);
1031
- const touchEnabled = showTouchControls ?? isTouch;
1032
- useEffect(() => {
1033
- let raf = 0;
1034
- let lastLine = "";
1035
- let lastPrompt = "";
1036
- const tick = () => {
1037
- const actor = world.queryFirst(ActorTrait);
1038
- const vehEnt = actor?.targetFor(PilotLink) ?? world.queryFirst(pilotedVehicleQuery);
1039
- let line;
1040
- let prompt;
1041
- if (vehEnt) {
1042
- const vd = vehEnt.get(VehicleTrait);
1043
- const vel = vehEnt.get(VelocityTrait);
1044
- const tel = vehEnt.get(VehicleTelemetryTrait);
1045
- const kmh = Math.round(vel?.speedKmh ?? 0);
1046
- const rpm = Math.round(tel?.rpm ?? 0);
1047
- const gear = tel?.gear ?? 1;
1048
- line = `${vd?.isFlight ? "Flight" : "Car"} · ${kmh} km/h · G${gear} · ${rpm} rpm`;
1049
- prompt = vd?.isFlight ? "[WASD] Fly · [Space/X] Rise/Dive · [Shift] Boost · [G] Mode · [V] Cam · [F] Exit" : "[WASD] Drive · [Shift] Boost · [Space] Brake · [V] Cam · [R] Flip · [F] Exit";
1050
- } else {
1051
- const vel = actor?.get(VelocityTrait);
1052
- const near = world.has(WorldSessionTrait) ? world.get(WorldSessionTrait)?.nearVehicleId : "";
1053
- line = `On foot · ${Math.round(vel?.speedKmh ?? 0)} km/h`;
1054
- prompt = near ? "[F] Board vehicle · [WASD] Walk · [Shift] Sprint · [Space] Jump" : "[WASD] Walk · [Shift] Sprint · [Space] Jump";
1055
- }
1056
- if (line !== lastLine && telemetryRef.current) {
1057
- telemetryRef.current.textContent = line;
1058
- lastLine = line;
1059
- }
1060
- if (prompt !== lastPrompt && promptRef.current) {
1061
- promptRef.current.textContent = prompt;
1062
- lastPrompt = prompt;
1063
- }
1064
- raf = requestAnimationFrame(tick);
1065
- };
1066
- raf = requestAnimationFrame(tick);
1067
- return () => cancelAnimationFrame(raf);
1068
- }, [world]);
1069
- return /* @__PURE__ */ jsxs("div", {
1070
- style: {
1071
- position: "fixed",
1072
- inset: 0,
1073
- pointerEvents: "none",
1074
- zIndex: 30,
1075
- fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
1076
- color: "#e6edf3",
1077
- ...style
1078
- },
1079
- children: [/* @__PURE__ */ jsx("div", {
1080
- ref: telemetryRef,
1081
- style: {
1082
- position: "absolute",
1083
- top: "max(10px, env(safe-area-inset-top))",
1084
- left: "max(12px, env(safe-area-inset-left))",
1085
- padding: "6px 10px",
1086
- background: "rgba(9, 13, 22, 0.82)",
1087
- border: "1px solid #38bdf8",
1088
- borderRadius: 4,
1089
- fontSize: 12,
1090
- fontWeight: 700
1091
- },
1092
- children: "On foot · 0 km/h"
1093
- }), !touchEnabled ? /* @__PURE__ */ jsx("div", {
1094
- ref: promptRef,
1095
- style: {
1096
- position: "absolute",
1097
- bottom: "max(12px, env(safe-area-inset-bottom))",
1098
- left: "50%",
1099
- transform: "translateX(-50%)",
1100
- padding: "5px 10px",
1101
- background: "rgba(9, 13, 22, 0.78)",
1102
- border: "1px solid rgba(255,255,255,0.16)",
1103
- borderRadius: 4,
1104
- fontSize: 11,
1105
- whiteSpace: "nowrap"
1106
- },
1107
- children: "[WASD] Walk · [Shift] Sprint · [Space] Jump"
1108
- }) : /* @__PURE__ */ jsxs("div", {
1109
- style: { pointerEvents: "auto" },
1110
- children: [
1111
- /* @__PURE__ */ jsx(Joystick, {}),
1112
- /* @__PURE__ */ jsx(VirtualButton, {
1113
- id: "jump",
1114
- label: "JMP",
1115
- buttonWrapperStyle: {
1116
- position: "fixed",
1117
- right: 20,
1118
- bottom: 24
1119
- }
1120
- }),
1121
- /* @__PURE__ */ jsx(VirtualButton, {
1122
- id: "boost",
1123
- label: "BST",
1124
- buttonWrapperStyle: {
1125
- position: "fixed",
1126
- right: 88,
1127
- bottom: 24
1128
- }
1129
- }),
1130
- /* @__PURE__ */ jsx(VirtualButton, {
1131
- id: "interact",
1132
- label: "USE",
1133
- buttonWrapperStyle: {
1134
- position: "fixed",
1135
- right: 20,
1136
- bottom: 92
1137
- }
1138
- })
1139
- ]
1140
- })]
1141
- });
1142
- }
1143
- function KolmoHud(props) {
1144
- const inCanvas = useContext(KolmoInCanvasContext);
1145
- const registerOverlay = useContext(KolmoOverlayContext);
1146
- const outerWorld = useOptionalKootaWorld();
1147
- const id = useId();
1148
- useLayoutEffect(() => {
1149
- if (!inCanvas || !registerOverlay) return;
1150
- const node = outerWorld ? /* @__PURE__ */ jsx(WorldProvider, {
1151
- world: outerWorld,
1152
- children: /* @__PURE__ */ jsx(KolmoHudDom, { ...props })
1153
- }) : /* @__PURE__ */ jsx(KolmoHudDom, { ...props });
1154
- registerOverlay(id, node);
1155
- return () => registerOverlay(id, null);
1156
- }, [
1157
- inCanvas,
1158
- registerOverlay,
1159
- outerWorld,
1160
- id,
1161
- props.showTouchControls,
1162
- props.style
1163
- ]);
1164
- return inCanvas ? null : /* @__PURE__ */ jsx(KolmoHudDom, { ...props });
1165
- }
1166
- function createOverlayStore() {
1167
- const map = /* @__PURE__ */ new Map();
1168
- const listeners = /* @__PURE__ */ new Set();
1169
- let snap = [];
1170
- return {
1171
- set(id, node) {
1172
- if (node === null) {
1173
- if (!map.delete(id)) return;
1174
- } else map.set(id, node);
1175
- snap = [...map.entries()];
1176
- for (const l of listeners) l();
1177
- },
1178
- subscribe(listener) {
1179
- listeners.add(listener);
1180
- return () => {
1181
- listeners.delete(listener);
1182
- };
1183
- },
1184
- getSnapshot: () => snap
1185
- };
1186
- }
1187
- function KolmoOverlayHost({ store }) {
1188
- const entries = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
1189
- if (entries.length === 0) return null;
1190
- return /* @__PURE__ */ jsx(Fragment, { children: entries.map(([id, node]) => /* @__PURE__ */ jsx(React.Fragment, { children: node }, id)) });
1191
- }
1192
- function KolmoGame({ gravity = "planar", skybox = "day", lighting = "default", fogExp2, paused = false, timeScale = 1, maxDelta, physicsDebug = false, dpr, roomEnv = .65, kootaWorld = kolmoWorld, style, className, children }) {
1193
- const outerWorld = useOptionalKootaWorld();
1194
- const store = useMemo(createOverlayStore, []);
1195
- const shell = /* @__PURE__ */ jsx(KolmoOverlayContext.Provider, {
1196
- value: store.set,
1197
- children: /* @__PURE__ */ jsxs("div", {
1198
- className,
1199
- style: {
1200
- position: "relative",
1201
- width: "100vw",
1202
- height: "100dvh",
1203
- overflow: "hidden",
1204
- touchAction: "none",
1205
- userSelect: "none",
1206
- ...style
1207
- },
1208
- children: [/* @__PURE__ */ jsx(KolmoCanvas, {
1209
- dpr,
1210
- roomEnv,
1211
- children: /* @__PURE__ */ jsx(KolmoWorld, {
1212
- gravity,
1213
- paused,
1214
- timeScale,
1215
- maxDelta,
1216
- skybox,
1217
- lighting,
1218
- fogExp2,
1219
- physicsDebug,
1220
- world: kootaWorld,
1221
- children
1222
- })
1223
- }), /* @__PURE__ */ jsx(KolmoOverlayHost, { store })]
1224
- })
1225
- });
1226
- return kootaWorld !== outerWorld ? /* @__PURE__ */ jsx(WorldProvider, {
1227
- world: kootaWorld,
1228
- children: shell
1229
- }) : shell;
266
+ })] });
1230
267
  }
1231
268
  // src/engine/gltfLoader.ts
1232
- var sharedKtx2Loader = null;
1233
- var sharedKtx2Path = "";
1234
- function getOrCreateKtx2Loader(renderer, transcoderPath) {
1235
- if (!sharedKtx2Loader || sharedKtx2Path !== transcoderPath) {
1236
- sharedKtx2Loader?.dispose();
1237
- sharedKtx2Loader = new KTX2Loader();
1238
- sharedKtx2Loader.setTranscoderPath(transcoderPath);
1239
- sharedKtx2Path = transcoderPath;
269
+ var ktx2ByRenderer = /* @__PURE__ */ new WeakMap();
270
+ function getScopedKtx2Loader(renderer, transcoderPath) {
271
+ let byPath = ktx2ByRenderer.get(renderer);
272
+ if (!byPath) {
273
+ byPath = /* @__PURE__ */ new Map();
274
+ ktx2ByRenderer.set(renderer, byPath);
1240
275
  }
1241
- sharedKtx2Loader.detectSupport(renderer);
1242
- return sharedKtx2Loader;
276
+ let ktx2 = byPath.get(transcoderPath);
277
+ if (!ktx2) {
278
+ ktx2 = new KTX2Loader();
279
+ ktx2.setTranscoderPath(transcoderPath);
280
+ ktx2.detectSupport(renderer);
281
+ byPath.set(transcoderPath, ktx2);
282
+ }
283
+ return ktx2;
1243
284
  }
1244
285
  /**
1245
- * Khronos-compliant `GLTFLoader` configured with `EXT_meshopt_compression` (`MeshoptDecoder`),
1246
- * `KHR_texture_basisu` (`KTX2Loader` when a renderer is supplied), and `@khr3/core` physics plugin.
1247
- * Never mounts legacy `DRACOLoader`.
286
+ * Khronos-compliant `GLTFLoader` configured with `EXT_meshopt_compression` (`MeshoptDecoder`)
287
+ * and `KHR_texture_basisu` (`KTX2Loader` when a renderer is supplied).
1248
288
  */
1249
289
  function createKolmoGltfLoader(options) {
1250
290
  const loader = new GLTFLoader();
1251
291
  loader.setMeshoptDecoder(MeshoptDecoder);
1252
- loader.register(createKhrGltfPlugin(options?.khrOptions));
1253
- if (options?.renderer) loader.setKTX2Loader(getOrCreateKtx2Loader(options.renderer, options.basisTranscoderPath ?? "/basis/"));
292
+ if (options?.renderer) loader.setKTX2Loader(getScopedKtx2Loader(options.renderer, options.basisTranscoderPath ?? "/basis/"));
1254
293
  return loader;
1255
294
  }
1256
295
  async function parseKolmoGlbBuffer(buffer, options) {
1257
- if (buffer.byteLength < 12) throw new Error("Invalid binary .glb buffer: truncated header (< 12 bytes).");
1258
- const view = new DataView(buffer);
1259
- if (view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2) throw new Error("Invalid binary .glb magic or glTF version (expected glTF 2.0).");
1260
- if (typeof MeshoptDecoder.ready?.then === "function") await MeshoptDecoder.ready;
1261
- return (await createKolmoGltfLoader(options).parseAsync(buffer, "")).scene;
296
+ await MeshoptDecoder.ready;
297
+ const loader = createKolmoGltfLoader(options);
298
+ return loadKhrGlb(buffer, {
299
+ ...options?.khrOptions,
300
+ loader
301
+ });
1262
302
  }
1263
303
  async function loadKolmoGlbUrl(url, options) {
1264
304
  const res = await fetch(url);
1265
305
  if (!res.ok) throw new Error(`Failed to fetch GLB (${res.status}): ${url}`);
1266
306
  return parseKolmoGlbBuffer(await res.arrayBuffer(), options);
1267
307
  }
1268
- export { ActorTrait, EMPTY_KOLMO_INPUT, G_SI, InteractableTrait, KOLMO_KEY_MAP, KOLMO_STICK_DEADZONE, KolmoActor, KolmoCanvas, KolmoGame, KolmoGravityContext, KolmoHud, KolmoInCanvasContext, KolmoKeyboardBridge, KolmoKeyboardContext, KolmoOverlayContext, KolmoPhysics, KolmoProp, KolmoSurface, KolmoVehicle, KolmoWorld, PilotLink, PilotedTag, RoomEnvRig, TransformTrait, VehicleTelemetryTrait, VehicleTrait, VelocityTrait, WorldSessionTrait, computeCircularOrbitSpeed, createKolmoGltfLoader, createNBodyGravityField, ensureWorldSession, evaluateNBodyGravity, flipVehicleBodyUpright, kolmoActions, kolmoWorld, loadKolmoGlbUrl, parseKolmoGlbBuffer, pilotedVehicleQuery, resolveAttractorMu, togglePropJoint, useActiveKolmoWorld, useIsKolmoCustomGravity, useKolmoGame, useKolmoInput, useOptionalKootaWorld, vehicleSimQuery, writeEntityKinematics, writeVehicleTelemetry };
308
+ export { ActorTrait, EMPTY_KOLMO_INPUT, G_SI, InteractableTrait, KOLMO_KEY_MAP, KOLMO_STICK_DEADZONE, KolmoActor, KolmoCanvas, KolmoGame, KolmoGravityContext, KolmoHud, KolmoInCanvasContext, KolmoKeyboardBridge, KolmoKeyboardContext, KolmoOverlayPortalContext, KolmoPhysics, KolmoProp, KolmoSurface, KolmoVehicle, KolmoWorld, KolmoWorldContext, PilotLink, PilotedTag, RoomEnvRig, TransformTrait, VehicleTelemetryTrait, VehicleTrait, VelocityTrait, WorldSessionTrait, computeCircularOrbitSpeed, createEmptyVehicleCmd, createKolmoGltfLoader, createNBodyGravityField, ensureWorldSession, evaluateNBodyGravity, evaluatePreparedNBodyGravity, flipVehicleBodyUpright, kolmoActions, kolmoWorld, loadKolmoGlbUrl, parseKolmoGlbBuffer, pilotedVehicleQuery, prepareAttractors, resolveAttractorMu, useActiveKolmoWorld, useIsKolmoCustomGravity, useKolmoGame, useKolmoInput, useOptionalKootaWorld, vehicleSimQuery, writeEntityKinematics, writeVehicleTelemetry };
1269
309
 
1270
310
  //# sourceMappingURL=index.js.map