@bendyline/molen-client 0.0.10 → 0.0.11

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.
package/dist/aircraft.mjs CHANGED
@@ -1,6 +1,675 @@
1
1
  import { t as createModelSignalVisual } from "./model-signals-DLgvjBeZ.mjs";
2
+ import { t as applyLivery } from "./livery-C0abgthY.mjs";
2
3
  import { t as createVehicleInteriorVisual } from "./vehicle-interior-DfpZwWEh.mjs";
3
4
  import * as THREE from "three";
5
+ //#region src/aircraft-controls.ts
6
+ /** Discover moving controls from their authored input bindings, never from instrument needles. */
7
+ function createAircraftCockpit(model, spec) {
8
+ const controls = [];
9
+ let interior = spec.visual.interior === void 0 ? void 0 : structuredClone(spec.visual.interior);
10
+ const nodes = /* @__PURE__ */ new Map();
11
+ model.traverse((node) => nodes.set(node.name, [...nodes.get(node.name) ?? [], node]));
12
+ const add = (action, label, names, engine) => {
13
+ const control = {
14
+ id: `${action}:${engine ?? controls.length}`,
15
+ action,
16
+ label,
17
+ nodes: names,
18
+ ...engine === void 0 ? {} : { engine }
19
+ };
20
+ controls.push(control);
21
+ return control;
22
+ };
23
+ const bound = (source, pattern) => [...new Set((interior?.bindings ?? []).filter((b) => b.source === source && b.property !== "visible" && pattern.test(b.node) && nodes.has(b.node)).map((b) => b.node))];
24
+ const sticks = [...new Set([...bound("pitchInput", /stick|yoke|cyclic|column|control|wheel/i), ...bound("rollInput", /stick|yoke|cyclic|column|control|wheel/i)])];
25
+ if (!sticks.length && spec.visual.controlStick) sticks.push(spec.visual.controlStick.node);
26
+ add("stick", "Yoke / stick", sticks);
27
+ add("yaw", "Rudder pedals", bound("yawInput", /pedal/i));
28
+ const powerNodes = bound("power", /throttle|power|lever|quadrant|collective|thrust/i).filter((name) => !/pointer|needle|gauge|indicator/i.test(name));
29
+ if (!powerNodes.length && spec.visual.collective) powerNodes.push(spec.visual.collective.node);
30
+ const engines = [...spec.engines ?? []].sort((a, b) => b.position[0] - a.position[0]);
31
+ const independent = engines.length > 1 && powerNodes.length === engines.length && !powerNodes.some((name) => /collective|thrust/i.test(name));
32
+ model.updateMatrixWorld(true);
33
+ const localX = (name) => {
34
+ const node = nodes.get(name)?.[0];
35
+ return node ? model.worldToLocal(node.getWorldPosition(new THREE.Vector3())).x : 0;
36
+ };
37
+ powerNodes.sort((a, b) => localX(b) - localX(a));
38
+ add("power", spec.model === "helicopter" ? "Collective" : "All throttles", independent ? [] : powerNodes);
39
+ for (const [index, engine] of engines.entries()) {
40
+ if (engines.length < 2) break;
41
+ const names = independent ? [powerNodes[index]] : [];
42
+ add("power", `Engine ${index + 1} throttle`, names, engine.id);
43
+ for (const binding of interior?.bindings ?? []) if (binding.source === "power" && names.includes(binding.node)) binding.source = `engines.${engine.id}.power`;
44
+ }
45
+ add("engine", "Engine master", []);
46
+ const bank = spec.engines ?? (spec.engine ? [{
47
+ ...spec.engine,
48
+ id: "main"
49
+ }] : []);
50
+ for (const action of ["mixture", "propeller"]) {
51
+ const supported = bank.filter((e) => e.propulsion !== "jet" && (action === "mixture" ? e.mixtureControl : e.propellerControl));
52
+ const label = action === "mixture" ? "Mixture" : "Propeller RPM";
53
+ if (bank.length === 1 && supported.length) add(action, label, bound(action, /mixture|prop/i));
54
+ else for (const engine of supported) add(action, `Engine ${engines.findIndex((e) => e.id === engine.id) + 1} ${label.toLowerCase()}`, bound(`engines.${engine.id}.${action}`, /mixture|prop|condition/i), engine.id);
55
+ }
56
+ if (engines.length > 1) for (const [index, engine] of engines.entries()) add("engine", `Engine ${index + 1}`, [], engine.id);
57
+ if (spec.model === "airplane" && !spec.airplane?.fixedGear) add("gear", "Landing gear", [...bound("gear", /handle|lever|selector/i), ...bound("gearPosition", /handle|lever|selector/i)]);
58
+ if (spec.model === "airplane" && (spec.airplane?.flapLift ?? 0) > 0) add("flaps", "Flaps", bound("flapPosition", /flap.*(?:handle|lever|selector|pump)|(?:lever|handle).*flap|Skylane-flap|ATR72-power-lever-4/i));
59
+ if (spec.model === "airplane") add("brake", "Parking brake", []);
60
+ if (spec.poweredLift) add("thrustVector", "Nozzle / nacelle angle", bound("thrustVector", /lever|thumb/i));
61
+ model.traverse((node) => {
62
+ const authored = node.userData.aircraftControl;
63
+ if (!authored || !node.name) return;
64
+ const control = controls.find((entry) => entry.action === authored.action && entry.engine === authored.engine);
65
+ if (!control) return;
66
+ if (!control.nodes.includes(node.name)) control.nodes.push(node.name);
67
+ const motion = authored.motion;
68
+ if (!motion || !["position", "rotation"].includes(motion.property) || ![
69
+ "x",
70
+ "y",
71
+ "z"
72
+ ].includes(motion.axis) || !Number.isFinite(motion.scale) || motion.offset !== void 0 && !Number.isFinite(motion.offset)) return;
73
+ interior ??= {
74
+ nodes: [],
75
+ bindings: []
76
+ };
77
+ const source = authored.engine ? `engines.${authored.engine}.${authored.action === "engine" ? "enabled" : authored.action}` : {
78
+ yaw: "yawInput",
79
+ gear: "gearCommand",
80
+ flaps: "flapCommand",
81
+ thrustVector: "vectorCommand"
82
+ }[authored.action] ?? authored.action;
83
+ interior.bindings.push({
84
+ node: node.name,
85
+ source,
86
+ ...motion
87
+ });
88
+ });
89
+ const targets = /* @__PURE__ */ new Map();
90
+ for (const control of controls) for (const name of control.nodes) for (const node of nodes.get(name) ?? []) targets.set(node, control);
91
+ const caster = new THREE.Raycaster();
92
+ return {
93
+ controls,
94
+ interior,
95
+ pick(ray) {
96
+ caster.ray.copy(ray);
97
+ model.updateWorldMatrix(true, true);
98
+ for (const hit of caster.intersectObject(model, true)) {
99
+ let hidden = false;
100
+ for (let node = hit.object; node; node = node.parent) if (!node.visible) hidden = true;
101
+ if (hidden) continue;
102
+ for (let node = hit.object; node; node = node.parent) {
103
+ const control = targets.get(node);
104
+ if (control) return control;
105
+ }
106
+ const mesh = hit.object;
107
+ if ((Array.isArray(mesh.material) ? mesh.material : [mesh.material]).some((material) => material && !(material.transparent && material.opacity < .8))) return void 0;
108
+ }
109
+ }
110
+ };
111
+ }
112
+ function aircraftControlValue(input, control) {
113
+ if (control.action === "stick") return input.roll;
114
+ if (control.action === "power") return control.engine ? input.engines?.[control.engine]?.power ?? input.power : input.power;
115
+ if (control.action === "mixture" || control.action === "propeller") return (control.engine ? input.engines?.[control.engine]?.[control.action] : void 0) ?? input[control.action] ?? 1;
116
+ if (control.action === "engine") return Number(control.engine ? input.engines?.[control.engine]?.enabled ?? true : input.engine);
117
+ return Number(input[control.action] ?? 0);
118
+ }
119
+ /** Immutable pilot input update; hosts still submit it through flyAircraft's seat/authority checks. */
120
+ function applyAircraftControl(input, change, spec, state) {
121
+ if (!Number.isFinite(change.value) || change.pitch !== void 0 && !Number.isFinite(change.pitch)) return input;
122
+ const { control, value } = change;
123
+ const bank = spec.engines ?? (spec.engine ? [{
124
+ ...spec.engine,
125
+ id: "main"
126
+ }] : []);
127
+ if (control.engine && !bank.some((engine) => engine.id === control.engine)) return input;
128
+ const clamp = (v, low = 0) => Math.max(low, Math.min(1, v));
129
+ const next = { ...input };
130
+ switch (control.action) {
131
+ case "stick":
132
+ next.roll = clamp(value, -1);
133
+ next.pitch = clamp(change.pitch ?? input.pitch, -1);
134
+ break;
135
+ case "yaw":
136
+ next.yaw = clamp(value, -1);
137
+ break;
138
+ case "power":
139
+ if (control.engine) next.engines = {
140
+ ...input.engines,
141
+ [control.engine]: {
142
+ ...input.engines?.[control.engine],
143
+ power: clamp(value)
144
+ }
145
+ };
146
+ else {
147
+ next.power = clamp(value);
148
+ if (input.engines) next.engines = Object.fromEntries(Object.entries(input.engines).map(([id, entry]) => [id, Object.fromEntries(Object.entries(entry).filter(([key]) => key !== "power"))]));
149
+ }
150
+ break;
151
+ case "mixture":
152
+ case "propeller": {
153
+ const action = control.action;
154
+ const supported = bank.filter((e) => e.propulsion !== "jet" && (action === "mixture" ? e.mixtureControl : e.propellerControl));
155
+ if (!supported.length || control.engine && !supported.some((e) => e.id === control.engine)) return input;
156
+ if (control.engine) next.engines = {
157
+ ...input.engines,
158
+ [control.engine]: {
159
+ ...input.engines?.[control.engine],
160
+ [action]: clamp(value)
161
+ }
162
+ };
163
+ else {
164
+ next[action] = clamp(value);
165
+ if (input.engines) next.engines = Object.fromEntries(Object.entries(input.engines).map(([id, entry]) => [id, Object.fromEntries(Object.entries(entry).filter(([key]) => key !== action))]));
166
+ }
167
+ break;
168
+ }
169
+ case "engine":
170
+ if (control.engine) next.engines = {
171
+ ...input.engines,
172
+ [control.engine]: {
173
+ ...input.engines?.[control.engine],
174
+ enabled: value > 0
175
+ }
176
+ };
177
+ else next.engine = value > 0;
178
+ break;
179
+ case "gear":
180
+ if (spec.model !== "airplane" || spec.airplane?.fixedGear || !state || state.grounded) return input;
181
+ next.gear = value > 0;
182
+ break;
183
+ case "flaps":
184
+ if (spec.model !== "airplane" || !spec.airplane?.flapLift) return input;
185
+ next.flaps = clamp(value);
186
+ break;
187
+ case "brake":
188
+ next.brake = value > 0;
189
+ break;
190
+ case "thrustVector":
191
+ if (!spec.poweredLift) return input;
192
+ next.thrustVector = clamp(value);
193
+ break;
194
+ }
195
+ return next;
196
+ }
197
+ /** Transient pointer axes are mixed with keyboard/gamepad axes without latching after release. */
198
+ var AircraftPointerAxes = class {
199
+ pitch = 0;
200
+ roll = 0;
201
+ yaw = 0;
202
+ set(change) {
203
+ if (change.control.action === "stick") {
204
+ this.roll = change.value;
205
+ this.pitch = change.pitch ?? 0;
206
+ }
207
+ if (change.control.action === "yaw") this.yaw = change.value;
208
+ }
209
+ clear() {
210
+ this.pitch = this.roll = this.yaw = 0;
211
+ }
212
+ };
213
+ //#endregion
214
+ //#region src/aircraft-damage.ts
215
+ function createAircraftDamageVisual(model, spec) {
216
+ model.updateWorldMatrix(true, true);
217
+ const modelInverse = new THREE.Matrix4().copy(model.matrixWorld).invert();
218
+ const sections = (spec.collisionParts ?? []).map((part) => {
219
+ const nodes = [];
220
+ model.traverse((node) => {
221
+ if (part.nodes.includes(node.userData.name ?? node.name)) nodes.push(node);
222
+ });
223
+ return {
224
+ part,
225
+ nodes: nodes.filter((node) => {
226
+ for (let parent = node.parent; parent && parent !== model; parent = parent.parent) if (nodes.includes(parent)) return false;
227
+ return true;
228
+ })
229
+ };
230
+ });
231
+ const shared = [];
232
+ const fragments = [];
233
+ model.traverse((node) => {
234
+ if (node instanceof THREE.Mesh && sections.some(({ part }) => part.fragments?.nodes.includes(node.userData.name ?? node.name))) shared.push(node);
235
+ });
236
+ const vertex = new THREE.Vector3(), centroid = new THREE.Vector3();
237
+ for (const mesh of shared) {
238
+ const matching = sections.filter(({ part }) => part.fragments?.nodes.includes(mesh.userData.name ?? mesh.name));
239
+ const matrix = new THREE.Matrix4().multiplyMatrices(modelInverse, mesh.matrixWorld);
240
+ const source = mesh.geometry, positions = source.getAttribute("position");
241
+ const count = source.index?.count ?? positions.count;
242
+ const buckets = /* @__PURE__ */ new Map();
243
+ for (let i = 0; i < count; i += 3) {
244
+ centroid.set(0, 0, 0);
245
+ const indices = [
246
+ 0,
247
+ 1,
248
+ 2
249
+ ].map((j) => source.index?.getX(i + j) ?? i + j);
250
+ for (const index of indices) centroid.add(vertex.fromBufferAttribute(positions, index));
251
+ centroid.multiplyScalar(1 / 3).applyMatrix4(matrix);
252
+ const key = matching.find(({ part }) => {
253
+ const bounds = part.fragments;
254
+ return bounds && centroid.x >= bounds.min[0] && centroid.x <= bounds.max[0] && centroid.y >= bounds.min[1] && centroid.y <= bounds.max[1] && centroid.z >= bounds.min[2] && centroid.z <= bounds.max[2];
255
+ })?.part.id ?? "";
256
+ let bucket = buckets.get(key);
257
+ if (!bucket) {
258
+ bucket = {
259
+ indices: [],
260
+ groups: []
261
+ };
262
+ buckets.set(key, bucket);
263
+ }
264
+ const materialIndex = source.groups.find((group) => i >= group.start && i < group.start + group.count)?.materialIndex ?? 0;
265
+ const last = bucket.groups.at(-1);
266
+ if (last?.materialIndex === materialIndex) last.count += 3;
267
+ else bucket.groups.push({
268
+ start: bucket.indices.length,
269
+ count: 3,
270
+ materialIndex
271
+ });
272
+ bucket.indices.push(...indices);
273
+ }
274
+ for (const [key, bucket] of buckets) {
275
+ const fragment = mesh.clone(false);
276
+ fragment.name = `section:${key || "body"}:${mesh.name}`;
277
+ fragment.geometry = source.clone();
278
+ fragment.geometry.setIndex(bucket.indices);
279
+ fragment.geometry.clearGroups();
280
+ for (const group of bucket.groups) fragment.geometry.addGroup(group.start, group.count, group.materialIndex);
281
+ mesh.parent?.add(fragment);
282
+ fragments.push({
283
+ source: mesh,
284
+ fragment
285
+ });
286
+ sections.find(({ part }) => part.id === key)?.nodes.push(fragment);
287
+ }
288
+ mesh.visible = false;
289
+ }
290
+ const hidden = /* @__PURE__ */ new Map();
291
+ const pieces = /* @__PURE__ */ new Map();
292
+ const inverse = new THREE.Matrix4();
293
+ const pose = new THREE.Matrix4();
294
+ const position = new THREE.Vector3();
295
+ const rotation = new THREE.Quaternion();
296
+ const unit = new THREE.Vector3(1, 1, 1);
297
+ const reset = () => {
298
+ for (const [node, visible] of hidden) node.visible = visible;
299
+ hidden.clear();
300
+ for (const { source, fragment } of fragments) fragment.material = source.material;
301
+ for (const piece of pieces.values()) piece.removeFromParent();
302
+ pieces.clear();
303
+ };
304
+ return {
305
+ reset,
306
+ update(state) {
307
+ if (!state.damage && hidden.size === 0 && pieces.size === 0) return;
308
+ for (const [node, visible] of hidden) if (!sections.some(({ part, nodes }) => state.damage?.[part.id]?.detached && nodes.includes(node))) {
309
+ node.visible = visible;
310
+ hidden.delete(node);
311
+ }
312
+ model.updateWorldMatrix(true, true);
313
+ model.updateMatrix();
314
+ inverse.copy(model.matrix).invert();
315
+ for (const { part, nodes } of sections) {
316
+ const detached = state.damage?.[part.id]?.detached;
317
+ const debris = detached ? state.debris?.find((piece) => piece.part === part.id) : void 0;
318
+ let group = pieces.get(part.id);
319
+ if (!debris && group) {
320
+ group.removeFromParent();
321
+ pieces.delete(part.id);
322
+ group = void 0;
323
+ }
324
+ if (debris && !group) {
325
+ group = new THREE.Group();
326
+ group.name = `debris:${part.id}`;
327
+ const local = new THREE.Matrix4().copy(model.matrixWorld).invert();
328
+ const offset = new THREE.Matrix4().makeTranslation(-part.center[0], -part.center[1], -part.center[2]);
329
+ for (const node of nodes) {
330
+ const clone = node.clone(true);
331
+ clone.matrixAutoUpdate = false;
332
+ clone.matrix.copy(offset).multiply(local).multiply(node.matrixWorld);
333
+ clone.visible = hidden.get(node) ?? node.visible;
334
+ group.add(clone);
335
+ }
336
+ model.add(group);
337
+ pieces.set(part.id, group);
338
+ }
339
+ if (debris && group) {
340
+ group.matrixAutoUpdate = false;
341
+ pose.compose(position.fromArray(debris.pos), rotation.fromArray(debris.rot), unit);
342
+ group.matrix.copy(inverse).multiply(pose);
343
+ group.matrixWorldNeedsUpdate = true;
344
+ }
345
+ for (const node of nodes) if (detached) {
346
+ if (!hidden.has(node)) hidden.set(node, node.visible);
347
+ node.visible = false;
348
+ }
349
+ }
350
+ }
351
+ };
352
+ }
353
+ //#endregion
354
+ //#region src/aircraft-cockpit-pointer.ts
355
+ function bindAircraftCockpitPointer(options) {
356
+ let binding;
357
+ return {
358
+ update() {
359
+ if (!binding && options.session()) binding = bindActiveCockpitPointer(options);
360
+ binding?.update();
361
+ },
362
+ dispose() {
363
+ binding?.dispose();
364
+ binding = void 0;
365
+ }
366
+ };
367
+ }
368
+ function bindActiveCockpitPointer(options) {
369
+ const { element } = options;
370
+ const doc = element.ownerDocument;
371
+ const win = doc.defaultView;
372
+ const panel = doc.createElement("details");
373
+ panel.className = "molen-cockpit-controls";
374
+ panel.style.cssText = "position:absolute;right:12px;bottom:16px;z-index:20;max-width:320px;max-height:55%;overflow:auto;background:#101a22ed;color:#edf3f6;border:1px solid #647783;border-radius:8px;padding:9px 12px;font:12px/1.5 system-ui;box-shadow:0 4px 16px #0005;";
375
+ const summary = doc.createElement("summary");
376
+ summary.textContent = "Cockpit controls";
377
+ summary.style.cursor = "pointer";
378
+ panel.append(summary);
379
+ const content = doc.createElement("div");
380
+ panel.append(content);
381
+ if (options.companionPanel) (options.container ?? element.parentElement)?.append(panel);
382
+ panel.hidden = true;
383
+ const hint = doc.createElement("div");
384
+ hint.setAttribute("role", "status");
385
+ hint.style.cssText = "position:absolute;left:50%;bottom:18px;transform:translateX(-50%);z-index:21;pointer-events:none;background:#101a22e8;color:#fff;padding:5px 10px;border-radius:5px;font:12px system-ui;";
386
+ hint.hidden = true;
387
+ (options.container ?? element.parentElement)?.append(hint);
388
+ const caster = new THREE.Raycaster();
389
+ let active;
390
+ let drag;
391
+ const fields = [];
392
+ const originalCursor = element.style.cursor;
393
+ const cancel = () => {
394
+ const previous = drag;
395
+ drag = void 0;
396
+ previous?.session.release();
397
+ active?.release();
398
+ if (previous && element.hasPointerCapture(previous.pointer)) element.releasePointerCapture(previous.pointer);
399
+ element.style.cursor = originalCursor;
400
+ hint.hidden = true;
401
+ };
402
+ const usable = () => doc.hidden ? void 0 : options.session();
403
+ const showHint = (control, session) => {
404
+ hint.hidden = control === void 0;
405
+ if (control) {
406
+ const value = session ? aircraftControlValue(session.input, control) : 0;
407
+ hint.textContent = control.action === "gear" && session?.state?.grounded ? `${control.label} · locked while on the ground` : control.action === "stick" ? `${control.label} · drag to steer; release to center` : control.action === "yaw" ? `${control.label} · drag sideways; release to center` : `${control.label} · ${[
408
+ "gear",
409
+ "engine",
410
+ "brake"
411
+ ].includes(control.action) ? `${value ? "on" : "off"} · click to toggle` : `${Math.round(value * 100)}%${control.action === "mixture" && value === 0 ? " · idle cutoff" : ""} · drag up to increase`}`;
412
+ }
413
+ };
414
+ const pick = (event, session) => {
415
+ const rect = element.getBoundingClientRect();
416
+ if (!rect.width || !rect.height) return void 0;
417
+ options.camera.updateWorldMatrix(true, false);
418
+ caster.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1, 1 - (event.clientY - rect.top) / rect.height * 2), options.camera);
419
+ return session.cockpit.pick(caster.ray);
420
+ };
421
+ const stop = (event) => {
422
+ event.preventDefault();
423
+ event.stopImmediatePropagation();
424
+ };
425
+ const down = (event) => {
426
+ if (event.button !== 0 || drag) return;
427
+ const session = usable();
428
+ if (!session) return;
429
+ const control = pick(event, session);
430
+ if (!control) return;
431
+ stop(event);
432
+ element.focus({ preventScroll: true });
433
+ const value = aircraftControlValue(session.input, control);
434
+ if ([
435
+ "gear",
436
+ "engine",
437
+ "brake"
438
+ ].includes(control.action)) {
439
+ session.change({
440
+ control,
441
+ value: Number(!value)
442
+ });
443
+ showHint(control, usable());
444
+ return;
445
+ }
446
+ drag = {
447
+ session,
448
+ control,
449
+ pointer: event.pointerId,
450
+ x: event.clientX,
451
+ y: event.clientY,
452
+ value,
453
+ pitch: session.input.pitch
454
+ };
455
+ element.setPointerCapture(event.pointerId);
456
+ element.style.cursor = "grabbing";
457
+ showHint(control, session);
458
+ };
459
+ const move = (event) => {
460
+ const session = usable();
461
+ if (drag && (!session || session.id !== drag.session.id || session.cockpit !== drag.session.cockpit)) cancel();
462
+ if (drag && event.pointerId === drag.pointer) {
463
+ stop(event);
464
+ const x = (event.clientX - drag.x) / 120, y = (event.clientY - drag.y) / 160;
465
+ const action = drag.control.action;
466
+ const value = action === "stick" || action === "yaw" ? Math.max(-1, Math.min(1, drag.value + x)) : Math.max(0, Math.min(1, drag.value - y));
467
+ drag.session.change({
468
+ control: drag.control,
469
+ value,
470
+ ...action === "stick" ? { pitch: Math.max(-1, Math.min(1, drag.pitch + y)) } : {}
471
+ });
472
+ showHint(drag.control, usable());
473
+ } else if (session && event.buttons === 0) {
474
+ const control = pick(event, session);
475
+ element.style.cursor = control ? "pointer" : originalCursor;
476
+ showHint(control, session);
477
+ }
478
+ };
479
+ const up = (event) => {
480
+ if (drag?.pointer === event.pointerId) {
481
+ stop(event);
482
+ cancel();
483
+ }
484
+ };
485
+ const lost = (event) => {
486
+ if (drag?.pointer === event.pointerId) cancel();
487
+ };
488
+ const rebuild = (session) => {
489
+ content.replaceChildren();
490
+ fields.length = 0;
491
+ const help = doc.createElement("p");
492
+ help.textContent = "Drag the yoke, pedals or throttle in the cockpit. Common power synchronizes all engines.";
493
+ content.append(help);
494
+ for (const control of session.cockpit.controls) {
495
+ if (control.action === "stick" || control.action === "yaw") continue;
496
+ const row = doc.createElement("label");
497
+ row.style.cssText = "display:grid;grid-template-columns:125px 1fr 38px;align-items:center;gap:7px;margin:6px 0;";
498
+ const name = doc.createElement("span");
499
+ name.textContent = control.label;
500
+ const output = doc.createElement("output");
501
+ const field = [
502
+ "gear",
503
+ "engine",
504
+ "brake"
505
+ ].includes(control.action) ? doc.createElement("button") : doc.createElement("input");
506
+ field.setAttribute("aria-label", control.label);
507
+ field.style.cssText = "min-width:0;width:100%;accent-color:#62c9ec;";
508
+ if (field instanceof HTMLInputElement) {
509
+ field.type = "range";
510
+ field.min = "0";
511
+ field.max = "1";
512
+ field.step = "0.01";
513
+ field.addEventListener("input", () => {
514
+ const current = usable();
515
+ if (current?.id === session.id && current.cockpit === session.cockpit) current.change({
516
+ control,
517
+ value: Number(field.value)
518
+ });
519
+ });
520
+ } else {
521
+ field.type = "button";
522
+ field.addEventListener("click", () => {
523
+ const current = usable();
524
+ if (current?.id === session.id && current.cockpit === session.cockpit) current.change({
525
+ control,
526
+ value: Number(!aircraftControlValue(current.input, control))
527
+ });
528
+ });
529
+ }
530
+ row.append(name, field, output);
531
+ content.append(row);
532
+ fields.push({
533
+ control,
534
+ field,
535
+ output
536
+ });
537
+ }
538
+ };
539
+ element.addEventListener("pointerdown", down, true);
540
+ element.addEventListener("pointermove", move, true);
541
+ element.addEventListener("pointerup", up, true);
542
+ element.addEventListener("pointercancel", up, true);
543
+ element.addEventListener("lostpointercapture", lost);
544
+ panel.addEventListener("keydown", (event) => event.stopPropagation());
545
+ panel.addEventListener("keyup", (event) => event.stopPropagation());
546
+ win?.addEventListener("blur", cancel);
547
+ doc.addEventListener("visibilitychange", cancel);
548
+ return {
549
+ update() {
550
+ const session = usable();
551
+ if (session?.id !== active?.id || session?.cockpit !== active?.cockpit) {
552
+ cancel();
553
+ active = session;
554
+ if (session) {
555
+ if (doc.pointerLockElement === element) doc.exitPointerLock();
556
+ rebuild(session);
557
+ }
558
+ }
559
+ panel.hidden = !session;
560
+ if (!session) return;
561
+ for (const { control, field, output } of fields) {
562
+ const value = aircraftControlValue(session.input, control);
563
+ const locked = control.action === "gear" && (!session.state || session.state.grounded);
564
+ field.disabled = locked;
565
+ if (field instanceof HTMLInputElement) {
566
+ field.value = String(value);
567
+ output.value = `${Math.round(value * 100)}%`;
568
+ } else {
569
+ field.textContent = control.action === "gear" ? value ? "Down" : "Up" : value ? "On" : "Off";
570
+ field.setAttribute("aria-pressed", String(value > 0));
571
+ output.value = locked ? "Locked" : "";
572
+ }
573
+ }
574
+ },
575
+ dispose() {
576
+ cancel();
577
+ element.removeEventListener("pointerdown", down, true);
578
+ element.removeEventListener("pointermove", move, true);
579
+ element.removeEventListener("pointerup", up, true);
580
+ element.removeEventListener("pointercancel", up, true);
581
+ element.removeEventListener("lostpointercapture", lost);
582
+ win?.removeEventListener("blur", cancel);
583
+ doc.removeEventListener("visibilitychange", cancel);
584
+ panel.remove();
585
+ hint.remove();
586
+ }
587
+ };
588
+ }
589
+ //#endregion
590
+ //#region src/aircraft-collision.ts
591
+ /** Contact normals from streamed geometry and nearby parked vehicles, in absolute coordinates. */
592
+ function aircraftObstacleContacts(probes, scene) {
593
+ const contacts = [];
594
+ for (const probe of probes) {
595
+ const point = probe.center;
596
+ const hit = (normal, depth) => {
597
+ contacts.push({
598
+ part: probe.part,
599
+ point: new THREE.Vector3().fromArray(point).addScaledVector(normal, -probe.radius).toArray(),
600
+ normal: normal.toArray(),
601
+ depth
602
+ });
603
+ };
604
+ const sphere = new THREE.Sphere(new THREE.Vector3().fromArray(point).sub(scene.origin), probe.radius);
605
+ if (scene.octree.getSphereTriangles) {
606
+ const triangles = [];
607
+ scene.octree.getSphereTriangles(sphere, triangles);
608
+ const faceNormal = new THREE.Vector3(), nearest = new THREE.Vector3();
609
+ const faces = [];
610
+ for (const triangle of triangles) {
611
+ triangle.getNormal(faceNormal);
612
+ if (faceNormal.dot(sphere.center.clone().sub(triangle.a)) < -1e-7) continue;
613
+ triangle.closestPointToPoint(sphere.center, nearest);
614
+ const offset = sphere.center.clone().sub(nearest);
615
+ const distance = offset.length();
616
+ if (distance >= probe.radius) continue;
617
+ const normal = distance > 1e-7 ? offset.multiplyScalar(1 / distance) : faceNormal.clone();
618
+ const depth = probe.radius - distance;
619
+ const same = faces.find((face) => face.normal.dot(normal) > .9999);
620
+ if (same) same.depth = Math.max(same.depth, depth);
621
+ else faces.push({
622
+ normal,
623
+ depth
624
+ });
625
+ }
626
+ faces.sort((a, b) => b.depth - a.depth || a.normal.x - b.normal.x || a.normal.y - b.normal.y || a.normal.z - b.normal.z);
627
+ const nearestFace = faces[0];
628
+ if (nearestFace) hit(nearestFace.normal, nearestFace.depth);
629
+ } else {
630
+ const obstacle = scene.octree.sphereIntersect(sphere);
631
+ if (obstacle) hit(obstacle.normal, obstacle.depth);
632
+ }
633
+ for (const { transform, spec } of scene.cars) {
634
+ if (Math.hypot(transform.pos[0] - point[0], transform.pos[2] - point[2]) > Math.max(spec.width, spec.length) + probe.radius) continue;
635
+ const orientation = new THREE.Quaternion().fromArray(transform.rot);
636
+ const local = new THREE.Vector3().fromArray(point).sub(new THREE.Vector3().fromArray(transform.pos)).applyQuaternion(orientation.clone().invert());
637
+ const bounds = new THREE.Box3(new THREE.Vector3(-spec.width / 2, 0, -spec.length / 2), new THREE.Vector3(spec.width / 2, spec.height, spec.length / 2));
638
+ const normal = local.clone().sub(bounds.clampPoint(local, new THREE.Vector3()));
639
+ const distance = normal.length();
640
+ if (distance >= probe.radius) continue;
641
+ let depth = probe.radius - distance;
642
+ if (distance > 1e-4) normal.multiplyScalar(1 / distance);
643
+ else {
644
+ const face = [
645
+ "x",
646
+ "y",
647
+ "z"
648
+ ].flatMap((axis) => [{
649
+ axis,
650
+ sign: -1,
651
+ distance: local[axis] - bounds.min[axis]
652
+ }, {
653
+ axis,
654
+ sign: 1,
655
+ distance: bounds.max[axis] - local[axis]
656
+ }]).sort((a, b) => a.distance - b.distance)[0];
657
+ if (!face) continue;
658
+ normal.set(0, 0, 0);
659
+ normal[face.axis] = face.sign;
660
+ depth += face.distance;
661
+ }
662
+ hit(normal.applyQuaternion(orientation), depth);
663
+ }
664
+ for (const other of scene.aircraft) {
665
+ const normal = new THREE.Vector3().fromArray(point).sub(new THREE.Vector3().fromArray(other));
666
+ const distance = normal.length();
667
+ if (distance < 1.2 + probe.radius) hit(distance > 1e-4 ? normal.multiplyScalar(1 / distance) : new THREE.Vector3(0, 1, 0), 1.2 + probe.radius - distance);
668
+ }
669
+ }
670
+ return contacts;
671
+ }
672
+ //#endregion
4
673
  //#region src/aircraft.ts
5
674
  /**
6
675
  * Takes ownership of a loaded library GLB. The named nodes remain editable in a DCC.
@@ -8,8 +677,9 @@ import * as THREE from "three";
8
677
  * The gear and flaps follow `state.gearPosition` and `state.flapPosition` as they travel, or the
9
678
  * selection in `input` when the state has no positions (helicopters, hosts that animate only).
10
679
  */
11
- function createAircraftVisual(model, spec) {
12
- const interior = spec.visual.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, spec.visual.interior);
680
+ function createAircraftVisual(model, spec, livery) {
681
+ const cockpit = createAircraftCockpit(model, spec);
682
+ const interior = cockpit.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, cockpit.interior);
13
683
  const animation = spec.visual.animation === void 0 ? void 0 : createModelSignalVisual(model, spec.visual.animation);
14
684
  const moving = /* @__PURE__ */ new Map();
15
685
  model.traverse((o) => {
@@ -25,8 +695,22 @@ function createAircraftVisual(model, spec) {
25
695
  const turn = (name, axis, angle) => {
26
696
  for (const node of moving.get(name) ?? []) node.rotation[axis] = angle;
27
697
  };
698
+ let appearance = livery === void 0 ? void 0 : applyLivery(model, livery);
699
+ const cabin = (spec.visual.interior?.nodes ?? []).flatMap((name) => moving.get(name) ?? []);
700
+ for (const node of cabin) node.traverse((object) => {
701
+ if (object.isMesh) object.userData.walkIgnore = true;
702
+ });
703
+ const cabinRange = Math.max(60, 3 * Math.max(spec.length, spec.span));
704
+ const damage = createAircraftDamageVisual(model, spec);
705
+ let cabinShown = true;
28
706
  return {
707
+ setLivery(data) {
708
+ appearance?.dispose();
709
+ damage.reset();
710
+ appearance = data === void 0 ? void 0 : applyLivery(model, data);
711
+ },
29
712
  object: model,
713
+ cockpit,
30
714
  interior,
31
715
  animation,
32
716
  update(state, input, altitude, signals, timeSeconds) {
@@ -39,13 +723,17 @@ function createAircraftVisual(model, spec) {
39
723
  for (const name of spec.visual.gearNodes) for (const node of moving.get(name) ?? []) node.visible = gear > 0;
40
724
  for (const binding of spec.visual.flaps) turn(binding.node, binding.axis, flaps * binding.multiplier);
41
725
  for (const binding of spec.visual.ailerons) turn(binding.node, binding.axis, input.roll * binding.multiplier);
42
- if (interior === void 0 && spec.visual.controlStick !== void 0) {
726
+ if (spec.visual.interior === void 0 && spec.visual.controlStick !== void 0) {
43
727
  turn(spec.visual.controlStick.node, spec.visual.controlStick.pitchAxis, input.pitch * .22);
44
728
  turn(spec.visual.controlStick.node, spec.visual.controlStick.rollAxis, input.roll * .22);
45
729
  }
46
- if (interior === void 0 && spec.visual.collective !== void 0) turn(spec.visual.collective.node, spec.visual.collective.axis, input.power * spec.visual.collective.multiplier);
730
+ if (spec.visual.interior === void 0 && spec.visual.collective !== void 0) turn(spec.visual.collective.node, spec.visual.collective.axis, input.power * spec.visual.collective.multiplier);
47
731
  const engineSignals = Object.create(null);
48
- for (const engine of spec.engines ?? []) {
732
+ const bank = spec.engines ?? (spec.engine ? [{
733
+ ...spec.engine,
734
+ id: "main"
735
+ }] : []);
736
+ for (const engine of bank) {
49
737
  const reading = state.engines?.[engine.id];
50
738
  const prefix = `engines.${engine.id}.`;
51
739
  engineSignals[`${prefix}rpmNormalized`] = reading?.rpm;
@@ -53,6 +741,8 @@ function createAircraftVisual(model, spec) {
53
741
  engineSignals[`${prefix}failed`] = reading === void 0 ? void 0 : Number(reading.failed);
54
742
  engineSignals[`${prefix}thrustN`] = reading?.thrust;
55
743
  engineSignals[`${prefix}afterburner`] = reading?.afterburner ?? 0;
744
+ engineSignals[`${prefix}shaftPowerW`] = reading?.shaftPower;
745
+ engineSignals[`${prefix}combustion`] = reading?.combustion;
56
746
  }
57
747
  const telemetry = {
58
748
  airspeed: state.airspeed,
@@ -95,10 +785,35 @@ function createAircraftVisual(model, spec) {
95
785
  ...engineSignals,
96
786
  ...signals
97
787
  };
788
+ for (const engine of bank) {
789
+ telemetry[`engines.${engine.id}.power`] = input.engines?.[engine.id]?.power ?? input.power;
790
+ telemetry[`engines.${engine.id}.enabled`] = Number(input.engines?.[engine.id]?.enabled ?? true);
791
+ for (const action of ["mixture", "propeller"]) telemetry[`engines.${engine.id}.${action}`] = input.engines?.[engine.id]?.[action] ?? input[action] ?? 1;
792
+ }
793
+ Object.assign(telemetry, {
794
+ gearCommand: Number(input.gear),
795
+ flapCommand: Number(input.flaps),
796
+ vectorCommand: input.thrustVector ?? 0,
797
+ engine: Number(input.engine),
798
+ brake: Number(input.brake),
799
+ mixture: input.mixture ?? 1,
800
+ propeller: input.propeller ?? 1
801
+ });
98
802
  interior?.update(telemetry, timeSeconds);
99
803
  animation?.update(telemetry, timeSeconds);
804
+ damage.update(state);
805
+ },
806
+ updateView(camera) {
807
+ if (cabin.length === 0) return;
808
+ const p = model.position;
809
+ const shown = Math.hypot(p.x - camera[0], p.y - camera[1], p.z - camera[2]) < cabinRange * (cabinShown ? 1.1 : 1);
810
+ if (shown === cabinShown) return;
811
+ cabinShown = shown;
812
+ for (const node of cabin) node.visible = shown;
100
813
  },
101
814
  dispose() {
815
+ damage.reset();
816
+ appearance?.dispose();
102
817
  const geometries = /* @__PURE__ */ new Set(), materials = /* @__PURE__ */ new Set();
103
818
  model.traverse((o) => {
104
819
  if (o instanceof THREE.Mesh) {
@@ -142,4 +857,4 @@ function aircraftCameraPose(transform, spec, options) {
142
857
  };
143
858
  }
144
859
  //#endregion
145
- export { aircraftCameraPose, createAircraftVisual };
860
+ export { AircraftPointerAxes, aircraftCameraPose, aircraftControlValue, aircraftObstacleContacts, applyAircraftControl, bindAircraftCockpitPointer, createAircraftCockpit, createAircraftVisual };