@gamepadly/sdk 0.1.1 → 0.4.0
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/README.md +163 -8
- package/dist/audio/index.d.ts +10 -0
- package/dist/audio/index.d.ts.map +1 -0
- package/dist/audio/index.js +15 -0
- package/dist/audio/index.js.map +7 -0
- package/dist/audio/routing.d.ts +40 -0
- package/dist/audio/routing.d.ts.map +1 -0
- package/dist/audio/routing.js +26 -0
- package/dist/audio/routing.js.map +7 -0
- package/dist/audio/sampleBank.d.ts +29 -0
- package/dist/audio/sampleBank.d.ts.map +1 -0
- package/dist/audio/sampleBank.js +354 -0
- package/dist/audio/sampleBank.js.map +7 -0
- package/dist/bridge/index.js +5 -93
- package/dist/bridge/index.js.map +3 -3
- package/dist/bridge/profiles.js +89 -0
- package/dist/bridge/profiles.js.map +7 -0
- package/dist/browser.d.ts +6 -2
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +2654 -68
- package/dist/browser.js.map +4 -4
- package/dist/browser.min.js +1 -1
- package/dist/diagnostics/circularity.d.ts +26 -0
- package/dist/diagnostics/circularity.d.ts.map +1 -0
- package/dist/diagnostics/circularity.js +56 -0
- package/dist/diagnostics/circularity.js.map +7 -0
- package/dist/diagnostics/index.d.ts +15 -0
- package/dist/diagnostics/index.d.ts.map +1 -0
- package/dist/diagnostics/index.js +31 -0
- package/dist/diagnostics/index.js.map +7 -0
- package/dist/diagnostics/stick.d.ts +73 -0
- package/dist/diagnostics/stick.d.ts.map +1 -0
- package/dist/diagnostics/stick.js +134 -0
- package/dist/diagnostics/stick.js.map +7 -0
- package/dist/diagnostics/telemetry.d.ts +65 -0
- package/dist/diagnostics/telemetry.d.ts.map +1 -0
- package/dist/diagnostics/telemetry.js +98 -0
- package/dist/diagnostics/telemetry.js.map +7 -0
- package/dist/game/host.d.ts +40 -0
- package/dist/game/host.d.ts.map +1 -0
- package/dist/game/host.js +206 -0
- package/dist/game/host.js.map +7 -0
- package/dist/game/index.d.ts +12 -0
- package/dist/game/index.d.ts.map +1 -0
- package/dist/game/index.js +27 -0
- package/dist/game/index.js.map +7 -0
- package/dist/game/mock.d.ts +35 -0
- package/dist/game/mock.d.ts.map +1 -0
- package/dist/game/mock.js +221 -0
- package/dist/game/mock.js.map +7 -0
- package/dist/game/seats.d.ts +27 -0
- package/dist/game/seats.d.ts.map +1 -0
- package/dist/game/seats.js +66 -0
- package/dist/game/seats.js.map +7 -0
- package/dist/game/types.d.ts +85 -0
- package/dist/game/types.d.ts.map +1 -0
- package/dist/game/types.js +7 -0
- package/dist/game/types.js.map +7 -0
- package/dist/haptics/presets.js +133 -0
- package/dist/haptics/presets.js.map +7 -0
- package/dist/haptics/router.d.ts +16 -0
- package/dist/haptics/router.d.ts.map +1 -1
- package/dist/haptics/router.js +146 -0
- package/dist/haptics/router.js.map +7 -0
- package/dist/haptics/samples.d.ts +68 -0
- package/dist/haptics/samples.d.ts.map +1 -0
- package/dist/haptics/samples.js +124 -0
- package/dist/haptics/samples.js.map +7 -0
- package/dist/haptics/triggerWrites.d.ts +41 -0
- package/dist/haptics/triggerWrites.d.ts.map +1 -0
- package/dist/haptics/triggerWrites.js +127 -0
- package/dist/haptics/triggerWrites.js.map +7 -0
- package/dist/hid/index.d.ts +20 -2
- package/dist/hid/index.d.ts.map +1 -1
- package/dist/{chunks/chunk-GMU2WEFE.js → hid/index.js} +120 -172
- package/dist/hid/index.js.map +7 -0
- package/dist/hub.d.ts +26 -2
- package/dist/hub.d.ts.map +1 -1
- package/dist/hub.js +472 -0
- package/dist/hub.js.map +7 -0
- package/dist/index.d.ts +13 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +45 -793
- package/dist/index.js.map +4 -4
- package/dist/input/actions.js +244 -0
- package/dist/input/actions.js.map +7 -0
- package/dist/input/motion.d.ts +70 -0
- package/dist/input/motion.d.ts.map +1 -0
- package/dist/input/motion.js +175 -0
- package/dist/input/motion.js.map +7 -0
- package/dist/input/slotSwitcher.d.ts +31 -0
- package/dist/input/slotSwitcher.d.ts.map +1 -0
- package/dist/input/slotSwitcher.js +118 -0
- package/dist/input/slotSwitcher.js.map +7 -0
- package/dist/input/touchpad.d.ts +92 -0
- package/dist/input/touchpad.d.ts.map +1 -0
- package/dist/input/touchpad.js +268 -0
- package/dist/input/touchpad.js.map +7 -0
- package/dist/lifecycle.d.ts +37 -0
- package/dist/lifecycle.d.ts.map +1 -0
- package/dist/lifecycle.js +55 -0
- package/dist/lifecycle.js.map +7 -0
- package/dist/link/connect.d.ts +67 -0
- package/dist/link/connect.d.ts.map +1 -0
- package/dist/link/connect.js +123 -0
- package/dist/link/connect.js.map +7 -0
- package/dist/link/engine.d.ts +7 -1
- package/dist/link/engine.d.ts.map +1 -1
- package/dist/link/engine.js +985 -0
- package/dist/link/engine.js.map +7 -0
- package/dist/link/index.d.ts +15 -4
- package/dist/link/index.d.ts.map +1 -1
- package/dist/link/index.js +29 -958
- package/dist/link/index.js.map +4 -4
- package/dist/loop/index.js +0 -1
- package/dist/loop/index.js.map +1 -1
- package/dist/mic/blow.d.ts +72 -0
- package/dist/mic/blow.d.ts.map +1 -0
- package/dist/mic/blow.js +152 -0
- package/dist/mic/blow.js.map +7 -0
- package/dist/mic/index.d.ts +9 -0
- package/dist/mic/index.d.ts.map +1 -0
- package/dist/mic/index.js +23 -0
- package/dist/mic/index.js.map +7 -0
- package/dist/mic/input.d.ts +37 -0
- package/dist/mic/input.d.ts.map +1 -0
- package/dist/mic/input.js +109 -0
- package/dist/mic/input.js.map +7 -0
- package/dist/mic/level.d.ts +33 -0
- package/dist/mic/level.d.ts.map +1 -0
- package/dist/mic/level.js +61 -0
- package/dist/mic/level.js.map +7 -0
- package/package.json +17 -1
- package/dist/chunks/chunk-GMU2WEFE.js.map +0 -7
package/dist/browser.js
CHANGED
|
@@ -46,6 +46,9 @@ function applyDeadzone(value, threshold = 0.06) {
|
|
|
46
46
|
function parseGamepadVendorId(lower) {
|
|
47
47
|
return (lower.match(/vendor:\s*([0-9a-f]{4})/) ?? lower.match(/^([0-9a-f]{1,4})-[0-9a-f]{1,4}-/))?.[1]?.padStart(4, "0");
|
|
48
48
|
}
|
|
49
|
+
function parseGamepadProductId(lower) {
|
|
50
|
+
return (lower.match(/product:\s*([0-9a-f]{4})/) ?? lower.match(/^[0-9a-f]{1,4}-([0-9a-f]{1,4})-/))?.[1]?.padStart(4, "0");
|
|
51
|
+
}
|
|
49
52
|
function detectGamepadBrand(lower) {
|
|
50
53
|
const vendor = parseGamepadVendorId(lower);
|
|
51
54
|
if (vendor === "054c") return "sony";
|
|
@@ -59,39 +62,50 @@ function detectGamepadBrand(lower) {
|
|
|
59
62
|
}
|
|
60
63
|
function identifyGamepadFromId(rawId) {
|
|
61
64
|
const lower = (rawId || "").toLowerCase();
|
|
65
|
+
const parsedVidHex = parseGamepadVendorId(lower);
|
|
66
|
+
const parsedPidHex = parseGamepadProductId(lower);
|
|
67
|
+
const parsedVid = parsedVidHex ? Number.parseInt(parsedVidHex, 16) : void 0;
|
|
68
|
+
const parsedPid = parsedPidHex ? Number.parseInt(parsedPidHex, 16) : void 0;
|
|
62
69
|
const brand = detectGamepadBrand(lower);
|
|
63
70
|
if (brand === "sony") {
|
|
64
71
|
if (/0df2|edge/.test(lower)) {
|
|
65
|
-
return { brand: "sony", model: "dualsense_edge", displayName: "DualSense Edge", rawId, vendorId: 1356, productId: 3570 };
|
|
72
|
+
return { brand: "sony", model: "dualsense_edge", displayName: "DualSense Edge", rawId, vendorId: 1356, productId: parsedPid ?? 3570 };
|
|
66
73
|
}
|
|
67
74
|
if (/0ce6|dualsense/.test(lower)) {
|
|
68
|
-
return { brand: "sony", model: "dualsense", displayName: "PlayStation DualSense", rawId, vendorId: 1356, productId: 3302 };
|
|
75
|
+
return { brand: "sony", model: "dualsense", displayName: "PlayStation DualSense", rawId, vendorId: 1356, productId: parsedPid ?? 3302 };
|
|
69
76
|
}
|
|
70
77
|
if (/05c4|09cc|dualshock/.test(lower)) {
|
|
71
|
-
return { brand: "sony", model: "dualshock4", displayName: "DualShock 4", rawId, vendorId: 1356 };
|
|
78
|
+
return { brand: "sony", model: "dualshock4", displayName: "DualShock 4", rawId, vendorId: 1356, productId: parsedPid };
|
|
72
79
|
}
|
|
73
|
-
return { brand: "sony", model: "dualsense", displayName: "PlayStation Controller", rawId, vendorId: 1356 };
|
|
80
|
+
return { brand: "sony", model: "dualsense", displayName: "PlayStation Controller", rawId, vendorId: 1356, productId: parsedPid };
|
|
74
81
|
}
|
|
75
82
|
if (brand === "xbox") {
|
|
76
83
|
if (/0b12|0b13|0b20|0b21|0b22|series/.test(lower)) {
|
|
77
|
-
return { brand: "xbox", model: "xbox_series", displayName: "Xbox Wireless Controller", rawId, vendorId: 1118 };
|
|
84
|
+
return { brand: "xbox", model: "xbox_series", displayName: "Xbox Wireless Controller", rawId, vendorId: 1118, productId: parsedPid };
|
|
78
85
|
}
|
|
79
86
|
if (/028e|360/.test(lower)) {
|
|
80
|
-
return { brand: "xbox", model: "xbox_360", displayName: "Xbox 360 Controller", rawId, vendorId: 1118 };
|
|
87
|
+
return { brand: "xbox", model: "xbox_360", displayName: "Xbox 360 Controller", rawId, vendorId: 1118, productId: parsedPid };
|
|
81
88
|
}
|
|
82
|
-
return { brand: "xbox", model: "xbox_series", displayName: "Xbox Controller", rawId, vendorId: 1118 };
|
|
89
|
+
return { brand: "xbox", model: "xbox_series", displayName: "Xbox Controller", rawId, vendorId: 1118, productId: parsedPid };
|
|
83
90
|
}
|
|
84
91
|
if (brand === "nintendo") {
|
|
85
92
|
if (/2069|pro 2|switch 2/.test(lower)) {
|
|
86
|
-
return { brand: "nintendo", model: "switch2_pro", displayName: "Nintendo Switch 2 Pro Controller", rawId, vendorId: 1406, productId: 8297 };
|
|
93
|
+
return { brand: "nintendo", model: "switch2_pro", displayName: "Nintendo Switch 2 Pro Controller", rawId, vendorId: 1406, productId: parsedPid ?? 8297 };
|
|
87
94
|
}
|
|
88
95
|
if (/joy-con|2006|2007/.test(lower)) {
|
|
89
|
-
return { brand: "nintendo", model: "joycon", displayName: "Nintendo Joy-Con", rawId, vendorId: 1406 };
|
|
96
|
+
return { brand: "nintendo", model: "joycon", displayName: "Nintendo Joy-Con", rawId, vendorId: 1406, productId: parsedPid };
|
|
90
97
|
}
|
|
91
|
-
return { brand: "nintendo", model: "switch_pro", displayName: "Nintendo Switch Pro Controller", rawId, vendorId: 1406, productId: 8201 };
|
|
98
|
+
return { brand: "nintendo", model: "switch_pro", displayName: "Nintendo Switch Pro Controller", rawId, vendorId: 1406, productId: parsedPid ?? 8201 };
|
|
92
99
|
}
|
|
93
100
|
if (rawId) {
|
|
94
|
-
return {
|
|
101
|
+
return {
|
|
102
|
+
brand: "generic",
|
|
103
|
+
model: "generic",
|
|
104
|
+
displayName: rawId.split("(")[0].trim() || rawId,
|
|
105
|
+
rawId,
|
|
106
|
+
vendorId: parsedVid,
|
|
107
|
+
productId: parsedPid
|
|
108
|
+
};
|
|
95
109
|
}
|
|
96
110
|
return { brand: "none", model: "none", displayName: "No Controller Detected", rawId: "" };
|
|
97
111
|
}
|
|
@@ -224,7 +238,12 @@ function createEmptyInput() {
|
|
|
224
238
|
create: false,
|
|
225
239
|
options: false,
|
|
226
240
|
ps: false,
|
|
227
|
-
touchpadClick: false
|
|
241
|
+
touchpadClick: false,
|
|
242
|
+
mute: false,
|
|
243
|
+
fnL: false,
|
|
244
|
+
fnR: false,
|
|
245
|
+
paddleL: false,
|
|
246
|
+
paddleR: false
|
|
228
247
|
},
|
|
229
248
|
touch: { active: false, x: 0.5, y: 0.5 },
|
|
230
249
|
touch2: { active: false, x: 0.5, y: 0.5 },
|
|
@@ -251,6 +270,7 @@ function createDefaultOutState(playerIndex = 0) {
|
|
|
251
270
|
speakerPreamp: 7,
|
|
252
271
|
lightbar: [23, 23, 23],
|
|
253
272
|
playerLeds: PS5_PLAYER_LED_PATTERNS[playerIndex % PS5_PLAYER_LED_PATTERNS.length],
|
|
273
|
+
muteLed: "off",
|
|
254
274
|
leftTrigger: encodeTriggerEffect({ type: "off" }),
|
|
255
275
|
rightTrigger: encodeTriggerEffect({ type: "off" }),
|
|
256
276
|
legacyRumbleActive: false,
|
|
@@ -290,6 +310,10 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
290
310
|
get device() {
|
|
291
311
|
return this.getActiveHidSession()?.device ?? null;
|
|
292
312
|
}
|
|
313
|
+
/** WebHID device behind a slot (default: active slot), or null for Gamepad API / unknown slots. */
|
|
314
|
+
getHidDevice(slotId) {
|
|
315
|
+
return this.getHidSessionForSlot(slotId)?.device ?? null;
|
|
316
|
+
}
|
|
293
317
|
/** Active slot's WebHID transport (or 'disconnected' when active slot is not WebHID). */
|
|
294
318
|
get transport() {
|
|
295
319
|
return this.getActiveHidSession()?.transport ?? "disconnected";
|
|
@@ -838,9 +862,27 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
838
862
|
await sleepMs(20);
|
|
839
863
|
await this.sendSwitchSubcommand(session, 16, [61, 96, 0, 0, 18]).catch(() => {
|
|
840
864
|
});
|
|
865
|
+
await sleepMs(20);
|
|
866
|
+
await this.sendSwitchSubcommand(session, 2).catch(() => {
|
|
867
|
+
});
|
|
841
868
|
} catch {
|
|
842
869
|
}
|
|
843
870
|
}
|
|
871
|
+
parseSwitchDeviceInfo(session, data) {
|
|
872
|
+
if (data.byteLength < 17) return;
|
|
873
|
+
if (data.getUint8(13) !== 2) return;
|
|
874
|
+
const major = data.getUint8(14);
|
|
875
|
+
const minor = data.getUint8(15);
|
|
876
|
+
if (major === 0 && minor === 0) return;
|
|
877
|
+
const fw = {
|
|
878
|
+
buildDate: "",
|
|
879
|
+
buildTime: "",
|
|
880
|
+
hwInfoHex: "",
|
|
881
|
+
fwVersionHex: `v${major}.${minor}`
|
|
882
|
+
};
|
|
883
|
+
session.firmwareInfo = fw;
|
|
884
|
+
session.input.identity.firmwareInfo = fw;
|
|
885
|
+
}
|
|
844
886
|
parseSwitchStickCalibration(session, data) {
|
|
845
887
|
if (data.byteLength < 37) return;
|
|
846
888
|
if (data.getUint8(13) !== 16) return;
|
|
@@ -872,6 +914,7 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
872
914
|
const { reportId, data } = event;
|
|
873
915
|
if (reportId === 33) {
|
|
874
916
|
this.parseSwitchStickCalibration(session, data);
|
|
917
|
+
this.parseSwitchDeviceInfo(session, data);
|
|
875
918
|
}
|
|
876
919
|
if (reportId !== 48 && reportId !== 33 || data.byteLength < 11) {
|
|
877
920
|
return;
|
|
@@ -969,8 +1012,10 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
969
1012
|
}
|
|
970
1013
|
/**
|
|
971
1014
|
* Disconnects a specific WebHID controller slot, or the active WebHID slot when `slotId` is omitted.
|
|
1015
|
+
* With `forget: true` the browser permission is revoked too (`HIDDevice.forget()`), so the controller
|
|
1016
|
+
* is not silently re-attached by `reconnectAuthorized()` on the next visit.
|
|
972
1017
|
*/
|
|
973
|
-
async disconnect(slotId) {
|
|
1018
|
+
async disconnect(slotId, options = {}) {
|
|
974
1019
|
const targetId = slotId ?? this.activeSlotId ?? Array.from(this.hidSessions.keys())[0];
|
|
975
1020
|
if (!targetId) return;
|
|
976
1021
|
const session = this.hidSessions.get(targetId);
|
|
@@ -1008,6 +1053,11 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
1008
1053
|
this.activeSlotId = remaining[0]?.id ?? null;
|
|
1009
1054
|
}
|
|
1010
1055
|
this.emit({ type: "disconnected", slotId: targetId });
|
|
1056
|
+
if (options.forget) {
|
|
1057
|
+
const device = session.device;
|
|
1058
|
+
if (typeof device.forget === "function") await device.forget().catch(() => {
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1011
1061
|
}
|
|
1012
1062
|
async disconnectAll() {
|
|
1013
1063
|
const ids = Array.from(this.hidSessions.keys());
|
|
@@ -1087,7 +1137,12 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
1087
1137
|
input.buttons.r3 = Boolean(btn1 & 128);
|
|
1088
1138
|
input.buttons.ps = Boolean(btn2 & 1);
|
|
1089
1139
|
input.buttons.touchpadClick = Boolean(btn2 & 2);
|
|
1090
|
-
|
|
1140
|
+
input.buttons.mute = Boolean(btn2 & 4);
|
|
1141
|
+
input.buttons.fnL = Boolean(btn2 & 16);
|
|
1142
|
+
input.buttons.fnR = Boolean(btn2 & 32);
|
|
1143
|
+
input.buttons.paddleL = Boolean(btn2 & 64);
|
|
1144
|
+
input.buttons.paddleR = Boolean(btn2 & 128);
|
|
1145
|
+
const btnMask = btn0 & 240 | (dpad < 8 ? 1 : 0) | btn1 << 8 | (btn2 & 247) << 16;
|
|
1091
1146
|
if ((btnMask & ~session.prevBtnMask) !== 0) {
|
|
1092
1147
|
session.lastActivityAt = now;
|
|
1093
1148
|
}
|
|
@@ -1121,14 +1176,14 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
1121
1176
|
const battByte = data.getUint8(offset + 52);
|
|
1122
1177
|
const level = battByte & 15;
|
|
1123
1178
|
const state = battByte >> 4 & 15;
|
|
1124
|
-
input.battery.percent = Math.min(100, Math.round((level + 0.5) / 10 * 100));
|
|
1125
1179
|
input.battery.charging = state === 1;
|
|
1126
1180
|
input.battery.full = state === 2;
|
|
1181
|
+
input.battery.percent = state === 2 ? 100 : Math.min(100, Math.round((level + 0.5) / 10 * 100));
|
|
1127
1182
|
input.battery.known = true;
|
|
1128
1183
|
}
|
|
1129
1184
|
}
|
|
1130
1185
|
populateGamepadInput(pad, out) {
|
|
1131
|
-
const
|
|
1186
|
+
const clamp5 = (v) => Math.max(-1, Math.min(1, Number.isFinite(v) ? v : 0));
|
|
1132
1187
|
const baseId = identifyGamepadFromId(pad.id || "");
|
|
1133
1188
|
out.connected = true;
|
|
1134
1189
|
out.source = "gamepad";
|
|
@@ -1139,10 +1194,10 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
1139
1194
|
transport: "unknown",
|
|
1140
1195
|
source: "gamepad"
|
|
1141
1196
|
};
|
|
1142
|
-
out.lx =
|
|
1143
|
-
out.ly =
|
|
1144
|
-
out.rx =
|
|
1145
|
-
out.ry =
|
|
1197
|
+
out.lx = clamp5(pad.axes[0] ?? 0);
|
|
1198
|
+
out.ly = clamp5(pad.axes[1] ?? 0);
|
|
1199
|
+
out.rx = clamp5(pad.axes[2] ?? 0);
|
|
1200
|
+
out.ry = clamp5(pad.axes[3] ?? 0);
|
|
1146
1201
|
out.l2 = Math.max(0, Math.min(1, pad.buttons[6]?.value ?? 0));
|
|
1147
1202
|
out.r2 = Math.max(0, Math.min(1, pad.buttons[7]?.value ?? 0));
|
|
1148
1203
|
out.buttons.cross = Boolean(pad.buttons[0]?.pressed);
|
|
@@ -1560,7 +1615,8 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
1560
1615
|
common[37] = outState.speakerPreamp & 7;
|
|
1561
1616
|
}
|
|
1562
1617
|
if (includeLeds) {
|
|
1563
|
-
flag1 |= 4 | 16;
|
|
1618
|
+
flag1 |= 1 | 4 | 16;
|
|
1619
|
+
common[8] = outState.muteLed === "on" ? 1 : outState.muteLed === "pulse" ? 2 : 0;
|
|
1564
1620
|
common[38] = 2;
|
|
1565
1621
|
common[41] = 2;
|
|
1566
1622
|
common[42] = 0;
|
|
@@ -1668,6 +1724,7 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
1668
1724
|
session.outState.legacyLeft = 0;
|
|
1669
1725
|
session.outState.legacyRight = 0;
|
|
1670
1726
|
session.outState.lightbar = [23, 23, 23];
|
|
1727
|
+
session.outState.muteLed = "off";
|
|
1671
1728
|
void this.flushSessionOutput(session, { includeTriggers: true, includeLeds: true }).catch(() => {
|
|
1672
1729
|
});
|
|
1673
1730
|
}
|
|
@@ -1678,6 +1735,30 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
|
|
|
1678
1735
|
session.outState.lightbar = [r & 255, g & 255, b & 255];
|
|
1679
1736
|
return this.flushSessionOutput(session, { includeLeds: true });
|
|
1680
1737
|
}
|
|
1738
|
+
/**
|
|
1739
|
+
* Sets the player indicator LED bitmask over WebHID:
|
|
1740
|
+
* - DualSense / DualSense Edge: 5 white LEDs below touchpad (`0x00..0x1f`, e.g. `0x04` = center, `0x1f` = all 5).
|
|
1741
|
+
* - Switch Pro: 4 green LEDs on bottom edge (`0x00..0x0f`, e.g. `0x01`, `0x03`, `0x07`, `0x0f`).
|
|
1742
|
+
*/
|
|
1743
|
+
async setPlayerLeds(mask, slotId) {
|
|
1744
|
+
const session = this.getHidSessionForSlot(slotId);
|
|
1745
|
+
if (!session || !session.device.opened) return false;
|
|
1746
|
+
if (session.kind === "switch_pro") {
|
|
1747
|
+
await this.sendSwitchSubcommand(session, 48, [mask & 15]);
|
|
1748
|
+
return true;
|
|
1749
|
+
}
|
|
1750
|
+
session.outState.playerLeds = mask & 31;
|
|
1751
|
+
return this.flushSessionOutput(session, { includeLeds: true });
|
|
1752
|
+
}
|
|
1753
|
+
/**
|
|
1754
|
+
* Controls the DualSense / DualSense Edge orange microphone mute button LED (`'off' | 'on' | 'pulse'`).
|
|
1755
|
+
*/
|
|
1756
|
+
async setMuteLed(mode, slotId) {
|
|
1757
|
+
const session = this.getHidSessionForSlot(slotId);
|
|
1758
|
+
if (!session || session.kind !== "dualsense") return false;
|
|
1759
|
+
session.outState.muteLed = mode;
|
|
1760
|
+
return this.flushSessionOutput(session, { includeLeds: true });
|
|
1761
|
+
}
|
|
1681
1762
|
async pulseLegacyRumble(left = 200, right = 200, durationMs = 250, slotId) {
|
|
1682
1763
|
const session = this.getHidSessionForSlot(slotId);
|
|
1683
1764
|
if (!session || session.kind !== "dualsense" || !session.device.opened) return false;
|
|
@@ -1973,6 +2054,127 @@ function routeTactilePreset(ctx, presetId, opts = {}) {
|
|
|
1973
2054
|
});
|
|
1974
2055
|
}
|
|
1975
2056
|
|
|
2057
|
+
// src/haptics/samples.ts
|
|
2058
|
+
var NOOP_SAMPLE_HANDLE = {
|
|
2059
|
+
update() {
|
|
2060
|
+
},
|
|
2061
|
+
stop() {
|
|
2062
|
+
},
|
|
2063
|
+
get active() {
|
|
2064
|
+
return false;
|
|
2065
|
+
}
|
|
2066
|
+
};
|
|
2067
|
+
function clamp(v, min, max) {
|
|
2068
|
+
return Math.max(min, Math.min(max, v));
|
|
2069
|
+
}
|
|
2070
|
+
function makeSeededNoise(seed) {
|
|
2071
|
+
let s = seed >>> 0;
|
|
2072
|
+
return () => {
|
|
2073
|
+
s = s * 1664525 + 1013904223 >>> 0;
|
|
2074
|
+
return s / 4294967296 * 2 - 1;
|
|
2075
|
+
};
|
|
2076
|
+
}
|
|
2077
|
+
function createTactileBuffer(preset, sampleRate = 48e3) {
|
|
2078
|
+
const sr = Math.max(8e3, Math.round(sampleRate));
|
|
2079
|
+
const noise = makeSeededNoise(preset.length * 9973 + 1337);
|
|
2080
|
+
const durationSec = {
|
|
2081
|
+
footstep_ice: 0.09,
|
|
2082
|
+
footstep_metal: 0.14,
|
|
2083
|
+
footstep_gravel: 0.11,
|
|
2084
|
+
footstep_water: 0.16,
|
|
2085
|
+
zipper_tick: 0.032,
|
|
2086
|
+
spring_boing: 0.28,
|
|
2087
|
+
engine_hum: 0.5
|
|
2088
|
+
};
|
|
2089
|
+
const len = Math.max(64, Math.round(durationSec[preset] * sr));
|
|
2090
|
+
const spkL = new Float32Array(len);
|
|
2091
|
+
const spkR = new Float32Array(len);
|
|
2092
|
+
const vcmL = new Float32Array(len);
|
|
2093
|
+
const vcmR = new Float32Array(len);
|
|
2094
|
+
let lp = 0;
|
|
2095
|
+
let phaseVcm = 0;
|
|
2096
|
+
let phaseSpk = 0;
|
|
2097
|
+
for (let i = 0; i < len; i++) {
|
|
2098
|
+
const t = i / sr;
|
|
2099
|
+
const u = i / len;
|
|
2100
|
+
const rawN = noise();
|
|
2101
|
+
lp = lp * 0.72 + rawN * 0.28;
|
|
2102
|
+
let spk = 0;
|
|
2103
|
+
let vcm = 0;
|
|
2104
|
+
switch (preset) {
|
|
2105
|
+
case "footstep_ice": {
|
|
2106
|
+
const env = Math.pow(1 - u, 2.2) * Math.min(1, t / 3e-3);
|
|
2107
|
+
phaseVcm += 2 * Math.PI * (240 - u * 90) / sr;
|
|
2108
|
+
phaseSpk += 2 * Math.PI * (2400 - u * 950) / sr;
|
|
2109
|
+
vcm = (Math.sin(phaseVcm) * 0.65 + (rawN - lp) * 0.45) * env;
|
|
2110
|
+
spk = (Math.sin(phaseSpk) * 0.45 + (rawN - lp) * 0.65) * env;
|
|
2111
|
+
break;
|
|
2112
|
+
}
|
|
2113
|
+
case "footstep_metal": {
|
|
2114
|
+
const envVcm = Math.pow(1 - u, 1.8) * Math.min(1, t / 2e-3);
|
|
2115
|
+
const envSpk = Math.pow(1 - u, 1.4) * Math.min(1, t / 2e-3);
|
|
2116
|
+
phaseVcm += 2 * Math.PI * (148 - u * 35) / sr;
|
|
2117
|
+
phaseSpk += 2 * Math.PI * 1380 / sr;
|
|
2118
|
+
vcm = (Math.sin(phaseVcm) * 0.78 + Math.sin(phaseVcm * 2.13) * 0.22) * envVcm;
|
|
2119
|
+
spk = (Math.sin(phaseSpk) * 0.55 + Math.sin(phaseSpk * 1.47) * 0.35 + (rawN - lp) * 0.2) * envSpk;
|
|
2120
|
+
break;
|
|
2121
|
+
}
|
|
2122
|
+
case "footstep_gravel": {
|
|
2123
|
+
const env = Math.pow(1 - u, 1.9) * Math.min(1, t / 4e-3);
|
|
2124
|
+
const grain = 0.55 + 0.45 * Math.sin(2 * Math.PI * 62 * t);
|
|
2125
|
+
phaseVcm += 2 * Math.PI * (118 + lp * 40) / sr;
|
|
2126
|
+
vcm = (Math.sin(phaseVcm) * 0.5 + lp * 0.65) * grain * env;
|
|
2127
|
+
spk = (rawN * 0.72 + lp * 0.28) * grain * env;
|
|
2128
|
+
break;
|
|
2129
|
+
}
|
|
2130
|
+
case "footstep_water": {
|
|
2131
|
+
const env = Math.sin(Math.PI * Math.pow(u, 0.7)) * (1 - u * 0.35);
|
|
2132
|
+
phaseVcm += 2 * Math.PI * (78 - u * 32) / sr;
|
|
2133
|
+
phaseSpk += 2 * Math.PI * (520 + u * 640) / sr;
|
|
2134
|
+
vcm = (Math.sin(phaseVcm) * 0.75 + lp * 0.35) * env;
|
|
2135
|
+
spk = (Math.sin(phaseSpk) * 0.35 + lp * 0.6) * env;
|
|
2136
|
+
break;
|
|
2137
|
+
}
|
|
2138
|
+
case "zipper_tick": {
|
|
2139
|
+
const env = Math.pow(1 - u, 2.8) * Math.min(1, t / 15e-4);
|
|
2140
|
+
phaseVcm += 2 * Math.PI * (260 - u * 110) / sr;
|
|
2141
|
+
phaseSpk += 2 * Math.PI * (2850 - u * 900) / sr;
|
|
2142
|
+
vcm = Math.sin(phaseVcm) * env;
|
|
2143
|
+
spk = (Math.sin(phaseSpk) * 0.7 + (rawN - lp) * 0.3) * env;
|
|
2144
|
+
break;
|
|
2145
|
+
}
|
|
2146
|
+
case "spring_boing": {
|
|
2147
|
+
const env = Math.pow(1 - u, 1.35) * Math.min(1, t / 4e-3);
|
|
2148
|
+
const wobble = Math.sin(2 * Math.PI * 19 * t);
|
|
2149
|
+
phaseVcm += 2 * Math.PI * (68 + u * 115 + wobble * 18) / sr;
|
|
2150
|
+
phaseSpk += 2 * Math.PI * (260 + u * 540 + wobble * 45) / sr;
|
|
2151
|
+
vcm = Math.sin(phaseVcm) * env * 0.92;
|
|
2152
|
+
spk = Math.sin(phaseSpk) * env * 0.78;
|
|
2153
|
+
break;
|
|
2154
|
+
}
|
|
2155
|
+
case "engine_hum": {
|
|
2156
|
+
const fBase = 48;
|
|
2157
|
+
const w1 = Math.sin(2 * Math.PI * fBase * t);
|
|
2158
|
+
const w2 = Math.sin(2 * Math.PI * (fBase * 2) * t) * 0.45;
|
|
2159
|
+
const w3 = Math.sin(2 * Math.PI * (fBase * 3) * t) * 0.22;
|
|
2160
|
+
vcm = (w1 + w2 + w3) * 0.58;
|
|
2161
|
+
spk = (w2 * 0.5 + w3 * 0.5) * 0.35;
|
|
2162
|
+
break;
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
const sClamped = clamp(spk, -0.95, 0.95);
|
|
2166
|
+
const vClamped = clamp(vcm, -0.95, 0.95);
|
|
2167
|
+
spkL[i] = sClamped;
|
|
2168
|
+
spkR[i] = sClamped;
|
|
2169
|
+
vcmL[i] = vClamped;
|
|
2170
|
+
vcmR[i] = vClamped;
|
|
2171
|
+
}
|
|
2172
|
+
return {
|
|
2173
|
+
sampleRate: sr,
|
|
2174
|
+
channels: [spkL, spkR, vcmL, vcmR]
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
|
|
1976
2178
|
// src/input/actions.ts
|
|
1977
2179
|
var BUTTON_NAMES = /* @__PURE__ */ new Set([
|
|
1978
2180
|
"cross",
|
|
@@ -2214,6 +2416,739 @@ function createActionTracker(spec) {
|
|
|
2214
2416
|
};
|
|
2215
2417
|
}
|
|
2216
2418
|
|
|
2419
|
+
// src/input/motion.ts
|
|
2420
|
+
function clamp2(v, min, max) {
|
|
2421
|
+
return Math.max(min, Math.min(max, v));
|
|
2422
|
+
}
|
|
2423
|
+
function createMotionTracker(options = {}) {
|
|
2424
|
+
const gyroWeight = clamp2(options.gyroWeight ?? 0.94, 0, 0.995);
|
|
2425
|
+
const gyroScale = Math.max(0.5, options.gyroScaleRadPerSec ?? 4.5);
|
|
2426
|
+
const fullTiltRad = Math.max(0.2, options.fullTiltRad ?? Math.PI / 4);
|
|
2427
|
+
const flickThreshold = Math.max(0.15, options.flickThreshold ?? 0.62);
|
|
2428
|
+
const flickCooldownMs = Math.max(80, options.flickCooldownMs ?? 320);
|
|
2429
|
+
const shakeDecay = Math.max(0.2, options.shakeDecay ?? 2.4);
|
|
2430
|
+
const shakeThreshold = clamp2(options.shakeThreshold ?? 0.35, 0.05, 0.95);
|
|
2431
|
+
let initialized = false;
|
|
2432
|
+
let active = false;
|
|
2433
|
+
let rawPitch = 0;
|
|
2434
|
+
let rawRoll = 0;
|
|
2435
|
+
let rawYaw = 0;
|
|
2436
|
+
let zeroPitch = 0;
|
|
2437
|
+
let zeroRoll = 0;
|
|
2438
|
+
let zeroYaw = 0;
|
|
2439
|
+
let gravX = 0;
|
|
2440
|
+
let gravY = 1;
|
|
2441
|
+
let gravZ = 0;
|
|
2442
|
+
let shakeIntensity = 0;
|
|
2443
|
+
let lastFlickAt = -1e9;
|
|
2444
|
+
let lastNowMs = 0;
|
|
2445
|
+
const state = {
|
|
2446
|
+
active: false,
|
|
2447
|
+
pitch: 0,
|
|
2448
|
+
roll: 0,
|
|
2449
|
+
yaw: 0,
|
|
2450
|
+
pitchNorm: 0,
|
|
2451
|
+
rollNorm: 0,
|
|
2452
|
+
angularSpeed: 0,
|
|
2453
|
+
linearAccelDelta: 0,
|
|
2454
|
+
shakeIntensity: 0,
|
|
2455
|
+
shaking: false,
|
|
2456
|
+
justFlicked: false,
|
|
2457
|
+
flickDirection: "none"
|
|
2458
|
+
};
|
|
2459
|
+
function writePose() {
|
|
2460
|
+
const pitch = clamp2(rawPitch - zeroPitch, -Math.PI / 2, Math.PI / 2);
|
|
2461
|
+
const roll = clamp2(rawRoll - zeroRoll, -Math.PI / 2, Math.PI / 2);
|
|
2462
|
+
const yaw = rawYaw - zeroYaw;
|
|
2463
|
+
state.active = active;
|
|
2464
|
+
state.pitch = pitch;
|
|
2465
|
+
state.roll = roll;
|
|
2466
|
+
state.yaw = yaw;
|
|
2467
|
+
state.pitchNorm = clamp2(pitch / fullTiltRad, -1, 1);
|
|
2468
|
+
state.rollNorm = clamp2(roll / fullTiltRad, -1, 1);
|
|
2469
|
+
}
|
|
2470
|
+
return {
|
|
2471
|
+
update(input, dtSec, nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) {
|
|
2472
|
+
const dt = dtSec !== void 0 ? clamp2(dtSec, 1e-3, 0.1) : lastNowMs > 0 ? clamp2((nowMs - lastNowMs) / 1e3, 1e-3, 0.1) : 1 / 60;
|
|
2473
|
+
lastNowMs = nowMs;
|
|
2474
|
+
const { gx, gy, gz, ax, ay, az } = {
|
|
2475
|
+
gx: input.gyro.x,
|
|
2476
|
+
gy: input.gyro.y,
|
|
2477
|
+
gz: input.gyro.z,
|
|
2478
|
+
ax: input.accel.x,
|
|
2479
|
+
ay: input.accel.y,
|
|
2480
|
+
az: input.accel.z
|
|
2481
|
+
};
|
|
2482
|
+
const accelMag = Math.hypot(ax, ay, az);
|
|
2483
|
+
const angularSpeed = Math.hypot(gx, gy, gz);
|
|
2484
|
+
const hasSignal = input.connected && (accelMag > 0.02 || angularSpeed > 2e-3);
|
|
2485
|
+
if (!hasSignal) {
|
|
2486
|
+
active = false;
|
|
2487
|
+
shakeIntensity = Math.max(0, shakeIntensity - shakeDecay * dt);
|
|
2488
|
+
state.active = false;
|
|
2489
|
+
state.angularSpeed = 0;
|
|
2490
|
+
state.linearAccelDelta = 0;
|
|
2491
|
+
state.shakeIntensity = shakeIntensity;
|
|
2492
|
+
state.shaking = shakeIntensity >= shakeThreshold;
|
|
2493
|
+
state.justFlicked = false;
|
|
2494
|
+
state.flickDirection = "none";
|
|
2495
|
+
return state;
|
|
2496
|
+
}
|
|
2497
|
+
active = true;
|
|
2498
|
+
const accelRoll = Math.atan2(-ax, Math.hypot(ay, az) || 1e-4);
|
|
2499
|
+
const accelPitch = Math.atan2(az, Math.hypot(ax, ay) || 1e-4);
|
|
2500
|
+
if (!initialized) {
|
|
2501
|
+
initialized = true;
|
|
2502
|
+
rawPitch = accelPitch;
|
|
2503
|
+
rawRoll = accelRoll;
|
|
2504
|
+
rawYaw = 0;
|
|
2505
|
+
gravX = ax;
|
|
2506
|
+
gravY = ay;
|
|
2507
|
+
gravZ = az;
|
|
2508
|
+
} else {
|
|
2509
|
+
const alpha = accelMag > 0.45 && accelMag < 1.65 ? gyroWeight : 0.99;
|
|
2510
|
+
rawPitch = alpha * (rawPitch + gx * gyroScale * dt) + (1 - alpha) * accelPitch;
|
|
2511
|
+
rawRoll = alpha * (rawRoll + gz * gyroScale * dt) + (1 - alpha) * accelRoll;
|
|
2512
|
+
const yawRate = Math.abs(gy) > 0.012 ? gy : 0;
|
|
2513
|
+
rawYaw += yawRate * gyroScale * dt;
|
|
2514
|
+
}
|
|
2515
|
+
const gravAlpha = 0.84;
|
|
2516
|
+
gravX = gravAlpha * gravX + (1 - gravAlpha) * ax;
|
|
2517
|
+
gravY = gravAlpha * gravY + (1 - gravAlpha) * ay;
|
|
2518
|
+
gravZ = gravAlpha * gravZ + (1 - gravAlpha) * az;
|
|
2519
|
+
const linX = ax - gravX;
|
|
2520
|
+
const linY = ay - gravY;
|
|
2521
|
+
const linZ = az - gravZ;
|
|
2522
|
+
const linearDelta = Math.hypot(linX, linY, linZ);
|
|
2523
|
+
const rawAgitation = clamp2((linearDelta * 1.15 + angularSpeed * 0.72 - 0.12) * 1.35, 0, 1);
|
|
2524
|
+
if (rawAgitation > shakeIntensity) {
|
|
2525
|
+
shakeIntensity = Math.min(1, shakeIntensity + (rawAgitation - shakeIntensity) * Math.min(1, dt * 16));
|
|
2526
|
+
} else {
|
|
2527
|
+
shakeIntensity = Math.max(0, shakeIntensity - shakeDecay * dt);
|
|
2528
|
+
}
|
|
2529
|
+
const flickImpulse = angularSpeed * 0.85 + linearDelta * 0.55;
|
|
2530
|
+
let justFlicked = false;
|
|
2531
|
+
let flickDirection = "none";
|
|
2532
|
+
if (flickImpulse >= flickThreshold && nowMs - lastFlickAt >= flickCooldownMs) {
|
|
2533
|
+
lastFlickAt = nowMs;
|
|
2534
|
+
justFlicked = true;
|
|
2535
|
+
const absPitch = Math.abs(gx) + Math.abs(linY) * 0.6;
|
|
2536
|
+
const absSide = Math.abs(gy) + Math.abs(gz) * 0.7 + Math.abs(linX) * 0.6;
|
|
2537
|
+
if (absPitch >= absSide) {
|
|
2538
|
+
flickDirection = gx + linY * 0.5 >= 0 ? "up" : "down";
|
|
2539
|
+
} else {
|
|
2540
|
+
flickDirection = gy + gz * 0.5 - linX * 0.4 >= 0 ? "right" : "left";
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
writePose();
|
|
2544
|
+
state.angularSpeed = angularSpeed;
|
|
2545
|
+
state.linearAccelDelta = linearDelta;
|
|
2546
|
+
state.shakeIntensity = shakeIntensity;
|
|
2547
|
+
state.shaking = shakeIntensity >= shakeThreshold;
|
|
2548
|
+
state.justFlicked = justFlicked;
|
|
2549
|
+
state.flickDirection = flickDirection;
|
|
2550
|
+
return state;
|
|
2551
|
+
},
|
|
2552
|
+
getState() {
|
|
2553
|
+
return state;
|
|
2554
|
+
},
|
|
2555
|
+
recenter() {
|
|
2556
|
+
zeroPitch = rawPitch;
|
|
2557
|
+
zeroRoll = rawRoll;
|
|
2558
|
+
zeroYaw = rawYaw;
|
|
2559
|
+
writePose();
|
|
2560
|
+
},
|
|
2561
|
+
reset() {
|
|
2562
|
+
initialized = false;
|
|
2563
|
+
active = false;
|
|
2564
|
+
rawPitch = 0;
|
|
2565
|
+
rawRoll = 0;
|
|
2566
|
+
rawYaw = 0;
|
|
2567
|
+
zeroPitch = 0;
|
|
2568
|
+
zeroRoll = 0;
|
|
2569
|
+
zeroYaw = 0;
|
|
2570
|
+
gravX = 0;
|
|
2571
|
+
gravY = 1;
|
|
2572
|
+
gravZ = 0;
|
|
2573
|
+
shakeIntensity = 0;
|
|
2574
|
+
lastFlickAt = -1e9;
|
|
2575
|
+
lastNowMs = 0;
|
|
2576
|
+
state.active = false;
|
|
2577
|
+
state.pitch = 0;
|
|
2578
|
+
state.roll = 0;
|
|
2579
|
+
state.yaw = 0;
|
|
2580
|
+
state.pitchNorm = 0;
|
|
2581
|
+
state.rollNorm = 0;
|
|
2582
|
+
state.angularSpeed = 0;
|
|
2583
|
+
state.linearAccelDelta = 0;
|
|
2584
|
+
state.shakeIntensity = 0;
|
|
2585
|
+
state.shaking = false;
|
|
2586
|
+
state.justFlicked = false;
|
|
2587
|
+
state.flickDirection = "none";
|
|
2588
|
+
}
|
|
2589
|
+
};
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
// src/input/touchpad.ts
|
|
2593
|
+
function clamp3(v, min, max) {
|
|
2594
|
+
return Math.max(min, Math.min(max, v));
|
|
2595
|
+
}
|
|
2596
|
+
function createTouchpadGestures(options = {}) {
|
|
2597
|
+
const tapMaxMs = Math.max(40, options.tapMaxMs ?? 240);
|
|
2598
|
+
const tapMaxMove = Math.max(0.01, options.tapMaxMove ?? 0.06);
|
|
2599
|
+
const doubleTapWindowMs = Math.max(100, options.doubleTapWindowMs ?? 320);
|
|
2600
|
+
const swipeMinSpeed = Math.max(0.2, options.swipeMinSpeed ?? 1.15);
|
|
2601
|
+
const swipeMinDistance = Math.max(0.03, options.swipeMinDistance ?? 0.12);
|
|
2602
|
+
const velAlpha = clamp3(options.velocitySmoothing ?? 0.45, 0.05, 1);
|
|
2603
|
+
let prev1Active = false;
|
|
2604
|
+
let prev1X = 0.5;
|
|
2605
|
+
let prev1Y = 0.5;
|
|
2606
|
+
let start1X = 0.5;
|
|
2607
|
+
let start1Y = 0.5;
|
|
2608
|
+
let start1At = 0;
|
|
2609
|
+
let maxMove1 = 0;
|
|
2610
|
+
let hadSecondDuringTouch = false;
|
|
2611
|
+
let lastTapAt = -1e9;
|
|
2612
|
+
let lastTapX = 0.5;
|
|
2613
|
+
let lastTapY = 0.5;
|
|
2614
|
+
let prev2Active = false;
|
|
2615
|
+
let prev2X = 0.5;
|
|
2616
|
+
let prev2Y = 0.5;
|
|
2617
|
+
let start2At = 0;
|
|
2618
|
+
let maxMove2 = 0;
|
|
2619
|
+
let start2X = 0.5;
|
|
2620
|
+
let start2Y = 0.5;
|
|
2621
|
+
let prevPinchActive = false;
|
|
2622
|
+
let startPinchDist = 0;
|
|
2623
|
+
let prevPinchDist = 0;
|
|
2624
|
+
let prevClicked = false;
|
|
2625
|
+
let lastNowMs = 0;
|
|
2626
|
+
let vx = 0;
|
|
2627
|
+
let vy = 0;
|
|
2628
|
+
const state = {
|
|
2629
|
+
fingerCount: 0,
|
|
2630
|
+
active: false,
|
|
2631
|
+
x: 0.5,
|
|
2632
|
+
y: 0.5,
|
|
2633
|
+
justTouched: false,
|
|
2634
|
+
justReleased: false,
|
|
2635
|
+
dx: 0,
|
|
2636
|
+
dy: 0,
|
|
2637
|
+
totalDx: 0,
|
|
2638
|
+
totalDy: 0,
|
|
2639
|
+
vx: 0,
|
|
2640
|
+
vy: 0,
|
|
2641
|
+
speed: 0,
|
|
2642
|
+
justTapped: false,
|
|
2643
|
+
justDoubleTapped: false,
|
|
2644
|
+
justTwoFingerTapped: false,
|
|
2645
|
+
justSwiped: false,
|
|
2646
|
+
swipeDirection: "none",
|
|
2647
|
+
pinchActive: false,
|
|
2648
|
+
pinchDistance: 0,
|
|
2649
|
+
pinchDelta: 0,
|
|
2650
|
+
pinchScale: 1,
|
|
2651
|
+
secondFinger: {
|
|
2652
|
+
active: false,
|
|
2653
|
+
justTouched: false,
|
|
2654
|
+
justReleased: false,
|
|
2655
|
+
x: 0.5,
|
|
2656
|
+
y: 0.5,
|
|
2657
|
+
dx: 0,
|
|
2658
|
+
dy: 0
|
|
2659
|
+
},
|
|
2660
|
+
clicked: false,
|
|
2661
|
+
justClicked: false
|
|
2662
|
+
};
|
|
2663
|
+
return {
|
|
2664
|
+
update(input, dtSec, nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) {
|
|
2665
|
+
const dt = dtSec !== void 0 ? clamp3(dtSec, 1e-3, 0.1) : lastNowMs > 0 ? clamp3((nowMs - lastNowMs) / 1e3, 1e-3, 0.1) : 1 / 60;
|
|
2666
|
+
lastNowMs = nowMs;
|
|
2667
|
+
const t1Active = Boolean(input.connected && input.touch.active);
|
|
2668
|
+
const t2Active = Boolean(input.connected && input.touch2.active);
|
|
2669
|
+
const t1X = clamp3(input.touch.x, 0, 1);
|
|
2670
|
+
const t1Y = clamp3(input.touch.y, 0, 1);
|
|
2671
|
+
const t2X = clamp3(input.touch2.x, 0, 1);
|
|
2672
|
+
const t2Y = clamp3(input.touch2.y, 0, 1);
|
|
2673
|
+
const justTouched1 = t1Active && !prev1Active;
|
|
2674
|
+
const justReleased1 = !t1Active && prev1Active;
|
|
2675
|
+
const justTouched2 = t2Active && !prev2Active;
|
|
2676
|
+
const justReleased2 = !t2Active && prev2Active;
|
|
2677
|
+
let dx1 = 0;
|
|
2678
|
+
let dy1 = 0;
|
|
2679
|
+
let justTapped = false;
|
|
2680
|
+
let justDoubleTapped = false;
|
|
2681
|
+
let justTwoFingerTapped = false;
|
|
2682
|
+
let justSwiped = false;
|
|
2683
|
+
let swipeDirection = "none";
|
|
2684
|
+
if (justTouched1) {
|
|
2685
|
+
start1X = t1X;
|
|
2686
|
+
start1Y = t1Y;
|
|
2687
|
+
start1At = nowMs;
|
|
2688
|
+
maxMove1 = 0;
|
|
2689
|
+
hadSecondDuringTouch = t2Active;
|
|
2690
|
+
vx = 0;
|
|
2691
|
+
vy = 0;
|
|
2692
|
+
} else if (t1Active) {
|
|
2693
|
+
dx1 = t1X - prev1X;
|
|
2694
|
+
dy1 = t1Y - prev1Y;
|
|
2695
|
+
if (t2Active) hadSecondDuringTouch = true;
|
|
2696
|
+
const distFromStart = Math.hypot(t1X - start1X, t1Y - start1Y);
|
|
2697
|
+
if (distFromStart > maxMove1) maxMove1 = distFromStart;
|
|
2698
|
+
const instVx = dx1 / dt;
|
|
2699
|
+
const instVy = dy1 / dt;
|
|
2700
|
+
vx = vx * (1 - velAlpha) + instVx * velAlpha;
|
|
2701
|
+
vy = vy * (1 - velAlpha) + instVy * velAlpha;
|
|
2702
|
+
} else if (justReleased1) {
|
|
2703
|
+
const heldMs = nowMs - start1At;
|
|
2704
|
+
const totalDist = Math.hypot(prev1X - start1X, prev1Y - start1Y);
|
|
2705
|
+
const speed = Math.hypot(vx, vy);
|
|
2706
|
+
if (heldMs <= tapMaxMs && maxMove1 <= tapMaxMove && !hadSecondDuringTouch) {
|
|
2707
|
+
justTapped = true;
|
|
2708
|
+
if (nowMs - lastTapAt <= doubleTapWindowMs && Math.hypot(prev1X - lastTapX, prev1Y - lastTapY) <= tapMaxMove * 2.5) {
|
|
2709
|
+
justDoubleTapped = true;
|
|
2710
|
+
lastTapAt = -1e9;
|
|
2711
|
+
} else {
|
|
2712
|
+
lastTapAt = nowMs;
|
|
2713
|
+
lastTapX = prev1X;
|
|
2714
|
+
lastTapY = prev1Y;
|
|
2715
|
+
}
|
|
2716
|
+
} else if (!hadSecondDuringTouch && speed >= swipeMinSpeed && totalDist >= swipeMinDistance) {
|
|
2717
|
+
justSwiped = true;
|
|
2718
|
+
const totalDx = prev1X - start1X;
|
|
2719
|
+
const totalDy = prev1Y - start1Y;
|
|
2720
|
+
if (Math.abs(totalDx) >= Math.abs(totalDy)) {
|
|
2721
|
+
swipeDirection = totalDx >= 0 ? "right" : "left";
|
|
2722
|
+
} else {
|
|
2723
|
+
swipeDirection = totalDy >= 0 ? "down" : "up";
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
} else {
|
|
2727
|
+
vx = 0;
|
|
2728
|
+
vy = 0;
|
|
2729
|
+
}
|
|
2730
|
+
let dx2 = 0;
|
|
2731
|
+
let dy2 = 0;
|
|
2732
|
+
if (justTouched2) {
|
|
2733
|
+
start2X = t2X;
|
|
2734
|
+
start2Y = t2Y;
|
|
2735
|
+
start2At = nowMs;
|
|
2736
|
+
maxMove2 = 0;
|
|
2737
|
+
} else if (t2Active) {
|
|
2738
|
+
dx2 = t2X - prev2X;
|
|
2739
|
+
dy2 = t2Y - prev2Y;
|
|
2740
|
+
const d2 = Math.hypot(t2X - start2X, t2Y - start2Y);
|
|
2741
|
+
if (d2 > maxMove2) maxMove2 = d2;
|
|
2742
|
+
}
|
|
2743
|
+
if (justReleased2 && prev1Active && nowMs - start2At <= tapMaxMs && maxMove2 <= tapMaxMove && maxMove1 <= tapMaxMove || justReleased1 && justReleased2 && nowMs - start1At <= tapMaxMs && nowMs - start2At <= tapMaxMs && maxMove1 <= tapMaxMove && maxMove2 <= tapMaxMove) {
|
|
2744
|
+
justTwoFingerTapped = true;
|
|
2745
|
+
}
|
|
2746
|
+
const pinchActive = t1Active && t2Active;
|
|
2747
|
+
let pinchDistance = 0;
|
|
2748
|
+
let pinchDelta = 0;
|
|
2749
|
+
let pinchScale = 1;
|
|
2750
|
+
if (pinchActive) {
|
|
2751
|
+
pinchDistance = Math.hypot(t2X - t1X, t2Y - t1Y);
|
|
2752
|
+
if (!prevPinchActive) {
|
|
2753
|
+
startPinchDist = Math.max(0.02, pinchDistance);
|
|
2754
|
+
prevPinchDist = pinchDistance;
|
|
2755
|
+
pinchDelta = 0;
|
|
2756
|
+
pinchScale = 1;
|
|
2757
|
+
} else {
|
|
2758
|
+
pinchDelta = pinchDistance - prevPinchDist;
|
|
2759
|
+
pinchScale = pinchDistance / Math.max(0.02, startPinchDist);
|
|
2760
|
+
prevPinchDist = pinchDistance;
|
|
2761
|
+
}
|
|
2762
|
+
} else {
|
|
2763
|
+
startPinchDist = 0;
|
|
2764
|
+
prevPinchDist = 0;
|
|
2765
|
+
}
|
|
2766
|
+
const clicked = Boolean(input.connected && input.buttons.touchpadClick);
|
|
2767
|
+
const justClicked = clicked && !prevClicked;
|
|
2768
|
+
prev1Active = t1Active;
|
|
2769
|
+
if (t1Active) {
|
|
2770
|
+
prev1X = t1X;
|
|
2771
|
+
prev1Y = t1Y;
|
|
2772
|
+
}
|
|
2773
|
+
prev2Active = t2Active;
|
|
2774
|
+
if (t2Active) {
|
|
2775
|
+
prev2X = t2X;
|
|
2776
|
+
prev2Y = t2Y;
|
|
2777
|
+
}
|
|
2778
|
+
prevPinchActive = pinchActive;
|
|
2779
|
+
prevClicked = clicked;
|
|
2780
|
+
const fingerCount = t1Active && t2Active ? 2 : t1Active || t2Active ? 1 : 0;
|
|
2781
|
+
state.fingerCount = fingerCount;
|
|
2782
|
+
state.active = t1Active;
|
|
2783
|
+
state.x = t1Active ? t1X : prev1X;
|
|
2784
|
+
state.y = t1Active ? t1Y : prev1Y;
|
|
2785
|
+
state.justTouched = justTouched1;
|
|
2786
|
+
state.justReleased = justReleased1;
|
|
2787
|
+
state.dx = dx1;
|
|
2788
|
+
state.dy = dy1;
|
|
2789
|
+
state.totalDx = t1Active ? t1X - start1X : 0;
|
|
2790
|
+
state.totalDy = t1Active ? t1Y - start1Y : 0;
|
|
2791
|
+
state.vx = t1Active || justReleased1 ? vx : 0;
|
|
2792
|
+
state.vy = t1Active || justReleased1 ? vy : 0;
|
|
2793
|
+
state.speed = Math.hypot(state.vx, state.vy);
|
|
2794
|
+
state.justTapped = justTapped;
|
|
2795
|
+
state.justDoubleTapped = justDoubleTapped;
|
|
2796
|
+
state.justTwoFingerTapped = justTwoFingerTapped;
|
|
2797
|
+
state.justSwiped = justSwiped;
|
|
2798
|
+
state.swipeDirection = swipeDirection;
|
|
2799
|
+
state.pinchActive = pinchActive;
|
|
2800
|
+
state.pinchDistance = pinchDistance;
|
|
2801
|
+
state.pinchDelta = pinchDelta;
|
|
2802
|
+
state.pinchScale = pinchScale;
|
|
2803
|
+
state.secondFinger.active = t2Active;
|
|
2804
|
+
state.secondFinger.justTouched = justTouched2;
|
|
2805
|
+
state.secondFinger.justReleased = justReleased2;
|
|
2806
|
+
state.secondFinger.x = t2Active ? t2X : prev2X;
|
|
2807
|
+
state.secondFinger.y = t2Active ? t2Y : prev2Y;
|
|
2808
|
+
state.secondFinger.dx = dx2;
|
|
2809
|
+
state.secondFinger.dy = dy2;
|
|
2810
|
+
state.clicked = clicked;
|
|
2811
|
+
state.justClicked = justClicked;
|
|
2812
|
+
return state;
|
|
2813
|
+
},
|
|
2814
|
+
getState() {
|
|
2815
|
+
return state;
|
|
2816
|
+
},
|
|
2817
|
+
reset() {
|
|
2818
|
+
prev1Active = false;
|
|
2819
|
+
prev2Active = false;
|
|
2820
|
+
prevPinchActive = false;
|
|
2821
|
+
prevClicked = false;
|
|
2822
|
+
hadSecondDuringTouch = false;
|
|
2823
|
+
lastTapAt = -1e9;
|
|
2824
|
+
lastNowMs = 0;
|
|
2825
|
+
vx = 0;
|
|
2826
|
+
vy = 0;
|
|
2827
|
+
state.fingerCount = 0;
|
|
2828
|
+
state.active = false;
|
|
2829
|
+
state.justTouched = false;
|
|
2830
|
+
state.justReleased = false;
|
|
2831
|
+
state.dx = 0;
|
|
2832
|
+
state.dy = 0;
|
|
2833
|
+
state.totalDx = 0;
|
|
2834
|
+
state.totalDy = 0;
|
|
2835
|
+
state.vx = 0;
|
|
2836
|
+
state.vy = 0;
|
|
2837
|
+
state.speed = 0;
|
|
2838
|
+
state.justTapped = false;
|
|
2839
|
+
state.justDoubleTapped = false;
|
|
2840
|
+
state.justTwoFingerTapped = false;
|
|
2841
|
+
state.justSwiped = false;
|
|
2842
|
+
state.swipeDirection = "none";
|
|
2843
|
+
state.pinchActive = false;
|
|
2844
|
+
state.pinchDistance = 0;
|
|
2845
|
+
state.pinchDelta = 0;
|
|
2846
|
+
state.pinchScale = 1;
|
|
2847
|
+
state.secondFinger.active = false;
|
|
2848
|
+
state.secondFinger.justTouched = false;
|
|
2849
|
+
state.secondFinger.justReleased = false;
|
|
2850
|
+
state.secondFinger.dx = 0;
|
|
2851
|
+
state.secondFinger.dy = 0;
|
|
2852
|
+
state.clicked = false;
|
|
2853
|
+
state.justClicked = false;
|
|
2854
|
+
}
|
|
2855
|
+
};
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
// src/input/slotSwitcher.ts
|
|
2859
|
+
var STICK_DELTA_THRESHOLD = 0.22;
|
|
2860
|
+
var STICK_MIN_MAGNITUDE = 0.25;
|
|
2861
|
+
var TRIGGER_DELTA_THRESHOLD = 0.25;
|
|
2862
|
+
var TRIGGER_MIN_VALUE = 0.25;
|
|
2863
|
+
var SWITCH_COOLDOWN_MS = 280;
|
|
2864
|
+
var SlotAutoSwitcher = class {
|
|
2865
|
+
anchors = /* @__PURE__ */ new Map();
|
|
2866
|
+
cooldownUntil = 0;
|
|
2867
|
+
notifyManualSelect(samples, now) {
|
|
2868
|
+
this.reanchorAll(samples);
|
|
2869
|
+
this.cooldownUntil = now + SWITCH_COOLDOWN_MS;
|
|
2870
|
+
}
|
|
2871
|
+
evaluate(samples, activeSlotId, now) {
|
|
2872
|
+
const liveIds = new Set(samples.map((s) => s.id));
|
|
2873
|
+
for (const id of this.anchors.keys()) {
|
|
2874
|
+
if (!liveIds.has(id)) this.anchors.delete(id);
|
|
2875
|
+
}
|
|
2876
|
+
if (samples.length === 0) {
|
|
2877
|
+
return { switchTo: null, triggeredSlotId: null };
|
|
2878
|
+
}
|
|
2879
|
+
let bestSwitchId = null;
|
|
2880
|
+
let bestSwitchScore = 0;
|
|
2881
|
+
let triggeredSlotId = null;
|
|
2882
|
+
for (const sample of samples) {
|
|
2883
|
+
const prev = this.anchors.get(sample.id);
|
|
2884
|
+
if (!prev) {
|
|
2885
|
+
this.anchors.set(sample.id, toAnchor(sample));
|
|
2886
|
+
continue;
|
|
2887
|
+
}
|
|
2888
|
+
const buttonPressed = sample.lastActivityAt > prev.lastActivityAt;
|
|
2889
|
+
const leftMag = Math.hypot(sample.lx, sample.ly);
|
|
2890
|
+
const leftDelta = Math.hypot(sample.lx - prev.lx, sample.ly - prev.ly);
|
|
2891
|
+
const rightMag = Math.hypot(sample.rx, sample.ry);
|
|
2892
|
+
const rightDelta = Math.hypot(sample.rx - prev.rx, sample.ry - prev.ry);
|
|
2893
|
+
const leftPush = leftMag >= STICK_MIN_MAGNITUDE && leftDelta >= STICK_DELTA_THRESHOLD;
|
|
2894
|
+
const rightPush = rightMag >= STICK_MIN_MAGNITUDE && rightDelta >= STICK_DELTA_THRESHOLD;
|
|
2895
|
+
const l2Push = sample.l2 >= TRIGGER_MIN_VALUE && sample.l2 - prev.l2 >= TRIGGER_DELTA_THRESHOLD;
|
|
2896
|
+
const r2Push = sample.r2 >= TRIGGER_MIN_VALUE && sample.r2 - prev.r2 >= TRIGGER_DELTA_THRESHOLD;
|
|
2897
|
+
const hasIntentionalInput = buttonPressed || leftPush || rightPush || l2Push || r2Push;
|
|
2898
|
+
if (sample.id === activeSlotId || samples.length === 1) {
|
|
2899
|
+
if (hasIntentionalInput) {
|
|
2900
|
+
triggeredSlotId = sample.id;
|
|
2901
|
+
this.anchors.set(sample.id, toAnchor(sample));
|
|
2902
|
+
} else {
|
|
2903
|
+
relaxAnchorTowardCenter(prev, sample, leftMag, rightMag);
|
|
2904
|
+
}
|
|
2905
|
+
continue;
|
|
2906
|
+
}
|
|
2907
|
+
if (now < this.cooldownUntil) {
|
|
2908
|
+
if (!hasIntentionalInput) {
|
|
2909
|
+
relaxAnchorTowardCenter(prev, sample, leftMag, rightMag);
|
|
2910
|
+
}
|
|
2911
|
+
continue;
|
|
2912
|
+
}
|
|
2913
|
+
if (buttonPressed) {
|
|
2914
|
+
const score = 10 + (sample.lastActivityAt - prev.lastActivityAt) * 1e-6;
|
|
2915
|
+
if (score > bestSwitchScore) {
|
|
2916
|
+
bestSwitchScore = score;
|
|
2917
|
+
bestSwitchId = sample.id;
|
|
2918
|
+
}
|
|
2919
|
+
} else if (leftPush || rightPush || l2Push || r2Push) {
|
|
2920
|
+
const score = Math.max(
|
|
2921
|
+
leftPush ? leftDelta : 0,
|
|
2922
|
+
rightPush ? rightDelta : 0,
|
|
2923
|
+
l2Push ? sample.l2 - prev.l2 : 0,
|
|
2924
|
+
r2Push ? sample.r2 - prev.r2 : 0
|
|
2925
|
+
);
|
|
2926
|
+
if (score > bestSwitchScore) {
|
|
2927
|
+
bestSwitchScore = score;
|
|
2928
|
+
bestSwitchId = sample.id;
|
|
2929
|
+
}
|
|
2930
|
+
} else {
|
|
2931
|
+
relaxAnchorTowardCenter(prev, sample, leftMag, rightMag);
|
|
2932
|
+
}
|
|
2933
|
+
}
|
|
2934
|
+
if (bestSwitchId) {
|
|
2935
|
+
this.reanchorAll(samples);
|
|
2936
|
+
this.cooldownUntil = now + SWITCH_COOLDOWN_MS;
|
|
2937
|
+
return { switchTo: bestSwitchId, triggeredSlotId: bestSwitchId };
|
|
2938
|
+
}
|
|
2939
|
+
return { switchTo: null, triggeredSlotId };
|
|
2940
|
+
}
|
|
2941
|
+
detectTargetSlot(samples, activeSlotId, now) {
|
|
2942
|
+
return this.evaluate(samples, activeSlotId, now).switchTo;
|
|
2943
|
+
}
|
|
2944
|
+
reanchorAll(samples) {
|
|
2945
|
+
for (const s of samples) {
|
|
2946
|
+
this.anchors.set(s.id, toAnchor(s));
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
};
|
|
2950
|
+
function relaxAnchorTowardCenter(prev, sample, leftMag, rightMag) {
|
|
2951
|
+
if (leftMag < Math.hypot(prev.lx, prev.ly)) {
|
|
2952
|
+
prev.lx = sample.lx;
|
|
2953
|
+
prev.ly = sample.ly;
|
|
2954
|
+
}
|
|
2955
|
+
if (rightMag < Math.hypot(prev.rx, prev.ry)) {
|
|
2956
|
+
prev.rx = sample.rx;
|
|
2957
|
+
prev.ry = sample.ry;
|
|
2958
|
+
}
|
|
2959
|
+
if (sample.l2 < prev.l2) prev.l2 = sample.l2;
|
|
2960
|
+
if (sample.r2 < prev.r2) prev.r2 = sample.r2;
|
|
2961
|
+
}
|
|
2962
|
+
function toAnchor(s) {
|
|
2963
|
+
return {
|
|
2964
|
+
lastActivityAt: s.lastActivityAt,
|
|
2965
|
+
lx: s.lx,
|
|
2966
|
+
ly: s.ly,
|
|
2967
|
+
rx: s.rx,
|
|
2968
|
+
ry: s.ry,
|
|
2969
|
+
l2: s.l2,
|
|
2970
|
+
r2: s.r2
|
|
2971
|
+
};
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2974
|
+
// src/haptics/triggerWrites.ts
|
|
2975
|
+
var TriggerFeedbackController = class {
|
|
2976
|
+
mounted = true;
|
|
2977
|
+
confirmedLeft = "off";
|
|
2978
|
+
confirmedRight = "off";
|
|
2979
|
+
pendingLeftSeq = 0;
|
|
2980
|
+
pendingRightSeq = 0;
|
|
2981
|
+
inFlightNonOff = 0;
|
|
2982
|
+
uncertainTriggerState = false;
|
|
2983
|
+
rumbleActive = false;
|
|
2984
|
+
get leftPreset() {
|
|
2985
|
+
return this.confirmedLeft;
|
|
2986
|
+
}
|
|
2987
|
+
get rightPreset() {
|
|
2988
|
+
return this.confirmedRight;
|
|
2989
|
+
}
|
|
2990
|
+
get hasActiveTrigger() {
|
|
2991
|
+
return this.confirmedLeft !== "off" || this.confirmedRight !== "off" || this.inFlightNonOff > 0 || this.uncertainTriggerState;
|
|
2992
|
+
}
|
|
2993
|
+
get needsCleanup() {
|
|
2994
|
+
return this.hasActiveTrigger || this.rumbleActive;
|
|
2995
|
+
}
|
|
2996
|
+
markMounted() {
|
|
2997
|
+
this.mounted = true;
|
|
2998
|
+
}
|
|
2999
|
+
markRumbleActive() {
|
|
3000
|
+
this.rumbleActive = true;
|
|
3001
|
+
}
|
|
3002
|
+
async applyPreset(hid, target, presetId, spec) {
|
|
3003
|
+
const isOff = presetId === "off";
|
|
3004
|
+
const hadActiveBefore = this.hasActiveTrigger;
|
|
3005
|
+
const hadActiveTargetBefore = this.uncertainTriggerState || (target === "left" ? this.confirmedLeft !== "off" : target === "right" ? this.confirmedRight !== "off" : this.confirmedLeft !== "off" || this.confirmedRight !== "off");
|
|
3006
|
+
const leftSeq = target === "left" || target === "both" ? ++this.pendingLeftSeq : 0;
|
|
3007
|
+
const rightSeq = target === "right" || target === "both" ? ++this.pendingRightSeq : 0;
|
|
3008
|
+
if (!isOff) {
|
|
3009
|
+
this.inFlightNonOff += 1;
|
|
3010
|
+
}
|
|
3011
|
+
let ok = false;
|
|
3012
|
+
let threw = false;
|
|
3013
|
+
try {
|
|
3014
|
+
if (target === "both") {
|
|
3015
|
+
ok = await hid.setTriggers(spec, spec);
|
|
3016
|
+
} else if (target === "left") {
|
|
3017
|
+
ok = await hid.setTriggers(spec, void 0);
|
|
3018
|
+
} else {
|
|
3019
|
+
ok = await hid.setTriggers(void 0, spec);
|
|
3020
|
+
}
|
|
3021
|
+
} catch {
|
|
3022
|
+
ok = false;
|
|
3023
|
+
threw = true;
|
|
3024
|
+
} finally {
|
|
3025
|
+
if (!isOff) {
|
|
3026
|
+
this.inFlightNonOff = Math.max(0, this.inFlightNonOff - 1);
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
const leftIsLatest = target === "right" || leftSeq === this.pendingLeftSeq;
|
|
3030
|
+
const rightIsLatest = target === "left" || rightSeq === this.pendingRightSeq;
|
|
3031
|
+
const stale = !(leftIsLatest && rightIsLatest);
|
|
3032
|
+
if (!this.mounted) {
|
|
3033
|
+
if (!isOff && (ok || threw) || isOff && !ok && hadActiveBefore) {
|
|
3034
|
+
void hid.resetTriggers().catch(() => {
|
|
3035
|
+
});
|
|
3036
|
+
}
|
|
3037
|
+
return {
|
|
3038
|
+
ok,
|
|
3039
|
+
stale,
|
|
3040
|
+
unmounted: true,
|
|
3041
|
+
hadActiveBefore,
|
|
3042
|
+
hadActiveTargetBefore,
|
|
3043
|
+
leftPreset: this.confirmedLeft,
|
|
3044
|
+
rightPreset: this.confirmedRight,
|
|
3045
|
+
needsReset: this.needsCleanup
|
|
3046
|
+
};
|
|
3047
|
+
}
|
|
3048
|
+
if (ok) {
|
|
3049
|
+
if (stale) {
|
|
3050
|
+
if (!isOff) {
|
|
3051
|
+
this.uncertainTriggerState = true;
|
|
3052
|
+
}
|
|
3053
|
+
} else {
|
|
3054
|
+
if (target === "left" || target === "both") this.confirmedLeft = presetId;
|
|
3055
|
+
if (target === "right" || target === "both") this.confirmedRight = presetId;
|
|
3056
|
+
if (this.confirmedLeft === "off" && this.confirmedRight === "off" && this.inFlightNonOff === 0) {
|
|
3057
|
+
this.uncertainTriggerState = false;
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
} else if (threw && !isOff) {
|
|
3061
|
+
this.uncertainTriggerState = true;
|
|
3062
|
+
}
|
|
3063
|
+
return {
|
|
3064
|
+
ok,
|
|
3065
|
+
stale,
|
|
3066
|
+
unmounted: false,
|
|
3067
|
+
hadActiveBefore,
|
|
3068
|
+
hadActiveTargetBefore,
|
|
3069
|
+
leftPreset: this.confirmedLeft,
|
|
3070
|
+
rightPreset: this.confirmedRight,
|
|
3071
|
+
needsReset: this.needsCleanup
|
|
3072
|
+
};
|
|
3073
|
+
}
|
|
3074
|
+
cleanupOnUnmount(hid) {
|
|
3075
|
+
this.mounted = false;
|
|
3076
|
+
if (!this.needsCleanup) return false;
|
|
3077
|
+
this.confirmedLeft = "off";
|
|
3078
|
+
this.confirmedRight = "off";
|
|
3079
|
+
this.uncertainTriggerState = false;
|
|
3080
|
+
this.rumbleActive = false;
|
|
3081
|
+
void hid.resetTriggers().catch(() => {
|
|
3082
|
+
});
|
|
3083
|
+
return true;
|
|
3084
|
+
}
|
|
3085
|
+
cleanupOnSlotChange(hid) {
|
|
3086
|
+
if (!this.needsCleanup) return false;
|
|
3087
|
+
this.pendingLeftSeq += 1;
|
|
3088
|
+
this.pendingRightSeq += 1;
|
|
3089
|
+
this.confirmedLeft = "off";
|
|
3090
|
+
this.confirmedRight = "off";
|
|
3091
|
+
this.uncertainTriggerState = false;
|
|
3092
|
+
this.rumbleActive = false;
|
|
3093
|
+
void hid.resetTriggers().catch(() => {
|
|
3094
|
+
});
|
|
3095
|
+
return true;
|
|
3096
|
+
}
|
|
3097
|
+
};
|
|
3098
|
+
|
|
3099
|
+
// src/lifecycle.ts
|
|
3100
|
+
function attachControllerLifecycle(hid, options = {}) {
|
|
3101
|
+
const onChange = options.onChange ?? (() => {
|
|
3102
|
+
});
|
|
3103
|
+
const autoHotplug = options.autoHotplug !== false;
|
|
3104
|
+
const autoReset = options.autoEmergencyReset !== false;
|
|
3105
|
+
const getAudio = () => typeof options.audio === "function" ? options.audio() : options.audio ?? null;
|
|
3106
|
+
if (autoHotplug) hid.attachHidHotplug();
|
|
3107
|
+
const unsubStatus = hid.onStatusChange(() => onChange("status"));
|
|
3108
|
+
const onGamepadEvent = () => onChange("gamepad");
|
|
3109
|
+
const onPageExit = () => {
|
|
3110
|
+
hid.emergencyReset();
|
|
3111
|
+
const audio = getAudio();
|
|
3112
|
+
audio?.stopAllContinuous?.();
|
|
3113
|
+
if (options.teardownAudioOnExit) void audio?.teardownDsOutput?.().catch(() => {
|
|
3114
|
+
});
|
|
3115
|
+
};
|
|
3116
|
+
const hasWindow = typeof window !== "undefined";
|
|
3117
|
+
if (hasWindow) {
|
|
3118
|
+
if (autoHotplug) {
|
|
3119
|
+
window.addEventListener("gamepadconnected", onGamepadEvent);
|
|
3120
|
+
window.addEventListener("gamepaddisconnected", onGamepadEvent);
|
|
3121
|
+
}
|
|
3122
|
+
if (autoReset) {
|
|
3123
|
+
window.addEventListener("pagehide", onPageExit);
|
|
3124
|
+
window.addEventListener("beforeunload", onPageExit);
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
3127
|
+
const pollMs = options.pollMs ?? 250;
|
|
3128
|
+
let poll = pollMs > 0 && typeof setInterval !== "undefined" ? setInterval(() => onChange("poll"), pollMs) : null;
|
|
3129
|
+
let cleaned = false;
|
|
3130
|
+
return () => {
|
|
3131
|
+
if (cleaned) return;
|
|
3132
|
+
cleaned = true;
|
|
3133
|
+
if (poll !== null) {
|
|
3134
|
+
clearInterval(poll);
|
|
3135
|
+
poll = null;
|
|
3136
|
+
}
|
|
3137
|
+
unsubStatus();
|
|
3138
|
+
if (hasWindow) {
|
|
3139
|
+
if (autoHotplug) {
|
|
3140
|
+
window.removeEventListener("gamepadconnected", onGamepadEvent);
|
|
3141
|
+
window.removeEventListener("gamepaddisconnected", onGamepadEvent);
|
|
3142
|
+
}
|
|
3143
|
+
if (autoReset) {
|
|
3144
|
+
window.removeEventListener("pagehide", onPageExit);
|
|
3145
|
+
window.removeEventListener("beforeunload", onPageExit);
|
|
3146
|
+
}
|
|
3147
|
+
}
|
|
3148
|
+
if (autoHotplug && options.detachHotplugOnCleanup !== false) hid.detachHidHotplug();
|
|
3149
|
+
};
|
|
3150
|
+
}
|
|
3151
|
+
|
|
2217
3152
|
// src/hub.ts
|
|
2218
3153
|
var NOOP_CONTINUOUS = {
|
|
2219
3154
|
update() {
|
|
@@ -2253,7 +3188,7 @@ function computeCapabilities(hid, audio, slotId, allow4ChAudio) {
|
|
|
2253
3188
|
};
|
|
2254
3189
|
}
|
|
2255
3190
|
function buildCapabilitySignature(slots, active) {
|
|
2256
|
-
const slotSig = slots.map((s) => `${s.id}:${s.source}:${s.identity.model}:${s.identity.transport}`).join(",");
|
|
3191
|
+
const slotSig = slots.map((s) => `${s.id}:${s.source}:${s.identity.model}:${s.identity.displayName}:${s.identity.transport}`).join(",");
|
|
2257
3192
|
return [
|
|
2258
3193
|
slotSig,
|
|
2259
3194
|
active.slotId ?? "",
|
|
@@ -2270,14 +3205,13 @@ function createGamepadly(options = {}) {
|
|
|
2270
3205
|
const ownsHid = !options.hid;
|
|
2271
3206
|
const hid = options.hid ?? new DualSenseControllerManager();
|
|
2272
3207
|
let audio = options.audio ?? null;
|
|
3208
|
+
const samples = options.samples ?? null;
|
|
2273
3209
|
let disposed = false;
|
|
2274
3210
|
const continuousHandles = /* @__PURE__ */ new Set();
|
|
3211
|
+
const sampleHandles = /* @__PURE__ */ new Set();
|
|
2275
3212
|
const timers = /* @__PURE__ */ new Set();
|
|
2276
3213
|
const trackers = /* @__PURE__ */ new Set();
|
|
2277
3214
|
const capListeners = /* @__PURE__ */ new Set();
|
|
2278
|
-
if (options.autoHotplug !== false) {
|
|
2279
|
-
hid.attachHidHotplug();
|
|
2280
|
-
}
|
|
2281
3215
|
if (options.attachKeyboardFallback && ownsHid) {
|
|
2282
3216
|
hid.attachKeyboardFallback();
|
|
2283
3217
|
}
|
|
@@ -2300,26 +3234,15 @@ function createGamepadly(options = {}) {
|
|
|
2300
3234
|
hid.getConnectedControllers(),
|
|
2301
3235
|
computeCapabilities(hid, audio, void 0, true)
|
|
2302
3236
|
);
|
|
2303
|
-
const
|
|
2304
|
-
|
|
3237
|
+
const detachLifecycle = attachControllerLifecycle(hid, {
|
|
3238
|
+
autoHotplug: options.autoHotplug,
|
|
3239
|
+
detachHotplugOnCleanup: ownsHid,
|
|
3240
|
+
autoEmergencyReset: options.autoEmergencyReset,
|
|
3241
|
+
teardownAudioOnExit: options.teardownAudioOnExit,
|
|
3242
|
+
audio: () => audio,
|
|
3243
|
+
pollMs: options.capabilityPollMs ?? 250,
|
|
3244
|
+
onChange: syncCapabilities
|
|
2305
3245
|
});
|
|
2306
|
-
const onGamepadEvent = () => syncCapabilities();
|
|
2307
|
-
const onPageHide = () => hid.emergencyReset();
|
|
2308
|
-
if (typeof window !== "undefined") {
|
|
2309
|
-
if (options.autoHotplug !== false) {
|
|
2310
|
-
window.addEventListener("gamepadconnected", onGamepadEvent);
|
|
2311
|
-
window.addEventListener("gamepaddisconnected", onGamepadEvent);
|
|
2312
|
-
}
|
|
2313
|
-
if (options.autoEmergencyReset !== false) {
|
|
2314
|
-
window.addEventListener("pagehide", onPageHide);
|
|
2315
|
-
window.addEventListener("beforeunload", onPageHide);
|
|
2316
|
-
}
|
|
2317
|
-
}
|
|
2318
|
-
let pollInterval = null;
|
|
2319
|
-
const pollMs = options.capabilityPollMs ?? 250;
|
|
2320
|
-
if (pollMs > 0 && typeof setInterval !== "undefined") {
|
|
2321
|
-
pollInterval = setInterval(syncCapabilities, pollMs);
|
|
2322
|
-
}
|
|
2323
3246
|
const createPlayerHandle = (target) => {
|
|
2324
3247
|
let lastLightbarColor = [23, 23, 23];
|
|
2325
3248
|
let lastLightbarSentAt = 0;
|
|
@@ -2485,6 +3408,66 @@ function createGamepadly(options = {}) {
|
|
|
2485
3408
|
},
|
|
2486
3409
|
playControllerSpeakerTone: (spec) => {
|
|
2487
3410
|
if (!disposed) audio?.playControllerSpeakerTone(spec);
|
|
3411
|
+
},
|
|
3412
|
+
loadSample: (id, source) => {
|
|
3413
|
+
const sink = samples ?? audio;
|
|
3414
|
+
if (disposed || !sink?.loadSample) return Promise.resolve(false);
|
|
3415
|
+
return sink.loadSample(id, source);
|
|
3416
|
+
},
|
|
3417
|
+
hasSample: (id) => {
|
|
3418
|
+
const sink = samples ?? audio;
|
|
3419
|
+
if (disposed || !sink?.hasSample) return false;
|
|
3420
|
+
return sink.hasSample(id);
|
|
3421
|
+
},
|
|
3422
|
+
unloadSample: (id) => {
|
|
3423
|
+
const sink = samples ?? audio;
|
|
3424
|
+
if (!disposed) sink?.unloadSample?.(id);
|
|
3425
|
+
},
|
|
3426
|
+
playSample: (id, opts = {}) => {
|
|
3427
|
+
if (disposed) return NOOP_SAMPLE_HANDLE;
|
|
3428
|
+
for (const h of sampleHandles) {
|
|
3429
|
+
if (!h.active) sampleHandles.delete(h);
|
|
3430
|
+
}
|
|
3431
|
+
const r = resolveTarget();
|
|
3432
|
+
const route = opts.route ?? "pc";
|
|
3433
|
+
const ownsControllerAudio = Boolean(audio && r.isPrimary && audio.dsMode !== "none");
|
|
3434
|
+
const can4Ch = Boolean(ownsControllerAudio && audio && audio.dsMaxChannelCount >= 4);
|
|
3435
|
+
if ((route === "vcm" || route === "quad") && !can4Ch) {
|
|
3436
|
+
const fb = opts.fallbackHaptic;
|
|
3437
|
+
routeHapticPulse(getRouteCtx(), {
|
|
3438
|
+
pan: opts.pan ?? 0,
|
|
3439
|
+
freqHz: fb?.freqHz ?? 145,
|
|
3440
|
+
durationMs: fb?.durationMs ?? (opts.loop ? 90 : 65),
|
|
3441
|
+
intensity: fb?.intensity ?? Math.min(1, (opts.gain ?? 0.85) * 0.72)
|
|
3442
|
+
});
|
|
3443
|
+
}
|
|
3444
|
+
const sink = samples ?? audio;
|
|
3445
|
+
if (!sink?.playSample) return NOOP_SAMPLE_HANDLE;
|
|
3446
|
+
let sinkOpts = opts;
|
|
3447
|
+
if (route !== "pc" && !ownsControllerAudio) {
|
|
3448
|
+
if (route === "vcm") return NOOP_SAMPLE_HANDLE;
|
|
3449
|
+
sinkOpts = {
|
|
3450
|
+
...opts,
|
|
3451
|
+
route: "pc",
|
|
3452
|
+
gain: (opts.gain ?? 0.85) * (route === "speaker" ? 0.45 : 0.5)
|
|
3453
|
+
};
|
|
3454
|
+
}
|
|
3455
|
+
const rawHandle = sink.playSample(id, sinkOpts);
|
|
3456
|
+
if (!rawHandle.active) return rawHandle;
|
|
3457
|
+
const tracked = {
|
|
3458
|
+
get active() {
|
|
3459
|
+
return !disposed && rawHandle.active;
|
|
3460
|
+
},
|
|
3461
|
+
update: (p) => {
|
|
3462
|
+
if (!disposed) rawHandle.update(p);
|
|
3463
|
+
},
|
|
3464
|
+
stop: (fadeOutMs) => {
|
|
3465
|
+
sampleHandles.delete(tracked);
|
|
3466
|
+
rawHandle.stop(fadeOutMs);
|
|
3467
|
+
}
|
|
3468
|
+
};
|
|
3469
|
+
sampleHandles.add(tracked);
|
|
3470
|
+
return tracked;
|
|
2488
3471
|
}
|
|
2489
3472
|
},
|
|
2490
3473
|
lightbar: {
|
|
@@ -2549,6 +3532,10 @@ function createGamepadly(options = {}) {
|
|
|
2549
3532
|
syncCapabilities();
|
|
2550
3533
|
return ok;
|
|
2551
3534
|
},
|
|
3535
|
+
async disconnectWebHID(slotId, opts) {
|
|
3536
|
+
await hid.disconnect(slotId, opts);
|
|
3537
|
+
syncCapabilities();
|
|
3538
|
+
},
|
|
2552
3539
|
async reconnectAuthorized() {
|
|
2553
3540
|
const ok = await hid.reconnectAuthorized();
|
|
2554
3541
|
syncCapabilities();
|
|
@@ -2578,22 +3565,8 @@ function createGamepadly(options = {}) {
|
|
|
2578
3565
|
dispose() {
|
|
2579
3566
|
if (disposed) return;
|
|
2580
3567
|
disposed = true;
|
|
2581
|
-
|
|
2582
|
-
clearInterval(pollInterval);
|
|
2583
|
-
pollInterval = null;
|
|
2584
|
-
}
|
|
2585
|
-
unsubHidStatus();
|
|
3568
|
+
detachLifecycle();
|
|
2586
3569
|
capListeners.clear();
|
|
2587
|
-
if (typeof window !== "undefined") {
|
|
2588
|
-
if (options.autoHotplug !== false) {
|
|
2589
|
-
window.removeEventListener("gamepadconnected", onGamepadEvent);
|
|
2590
|
-
window.removeEventListener("gamepaddisconnected", onGamepadEvent);
|
|
2591
|
-
}
|
|
2592
|
-
if (options.autoEmergencyReset !== false) {
|
|
2593
|
-
window.removeEventListener("pagehide", onPageHide);
|
|
2594
|
-
window.removeEventListener("beforeunload", onPageHide);
|
|
2595
|
-
}
|
|
2596
|
-
}
|
|
2597
3570
|
for (const t of timers) clearTimeout(t);
|
|
2598
3571
|
timers.clear();
|
|
2599
3572
|
for (const tr of trackers) {
|
|
@@ -2610,15 +3583,19 @@ function createGamepadly(options = {}) {
|
|
|
2610
3583
|
}
|
|
2611
3584
|
}
|
|
2612
3585
|
continuousHandles.clear();
|
|
3586
|
+
for (const s of sampleHandles) {
|
|
3587
|
+
try {
|
|
3588
|
+
s.stop();
|
|
3589
|
+
} catch {
|
|
3590
|
+
}
|
|
3591
|
+
}
|
|
3592
|
+
sampleHandles.clear();
|
|
2613
3593
|
hid.stopGamepadRumble();
|
|
2614
3594
|
hid.resetTriggers().catch(() => {
|
|
2615
3595
|
});
|
|
2616
3596
|
hid.setLightbar(23, 23, 23).catch(() => {
|
|
2617
3597
|
});
|
|
2618
|
-
if (ownsHid)
|
|
2619
|
-
if (options.autoHotplug !== false) hid.detachHidHotplug();
|
|
2620
|
-
if (options.attachKeyboardFallback) hid.detachKeyboardFallback();
|
|
2621
|
-
}
|
|
3598
|
+
if (ownsHid && options.attachKeyboardFallback) hid.detachKeyboardFallback();
|
|
2622
3599
|
}
|
|
2623
3600
|
};
|
|
2624
3601
|
}
|
|
@@ -2673,8 +3650,31 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
|
|
|
2673
3650
|
this.dsChGains[1].gain.setTargetAtTime(spk, this.dsCtx.currentTime, 0.015);
|
|
2674
3651
|
}
|
|
2675
3652
|
}
|
|
2676
|
-
// Track active continuous handles
|
|
3653
|
+
// Track active continuous handles & graph lifecycle subscribers
|
|
2677
3654
|
activeContinuous = /* @__PURE__ */ new Set();
|
|
3655
|
+
audioGraphListeners = /* @__PURE__ */ new Set();
|
|
3656
|
+
onAudioGraphChange(listener) {
|
|
3657
|
+
this.audioGraphListeners.add(listener);
|
|
3658
|
+
return () => {
|
|
3659
|
+
this.audioGraphListeners.delete(listener);
|
|
3660
|
+
};
|
|
3661
|
+
}
|
|
3662
|
+
getAudioRouting() {
|
|
3663
|
+
return {
|
|
3664
|
+
pcCtx: this.pcCtx,
|
|
3665
|
+
pcMasterGain: this.pcMasterGain,
|
|
3666
|
+
dsCtx: this.dsCtx,
|
|
3667
|
+
dsChGains: this.dsChGains
|
|
3668
|
+
};
|
|
3669
|
+
}
|
|
3670
|
+
emitAudioGraph(event) {
|
|
3671
|
+
for (const fn of this.audioGraphListeners) {
|
|
3672
|
+
try {
|
|
3673
|
+
fn(event);
|
|
3674
|
+
} catch {
|
|
3675
|
+
}
|
|
3676
|
+
}
|
|
3677
|
+
}
|
|
2678
3678
|
// Companion WebSocket lifecycle & auto-reconnect
|
|
2679
3679
|
companionToken = "";
|
|
2680
3680
|
intentionalWsClose = false;
|
|
@@ -2873,6 +3873,7 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
|
|
|
2873
3873
|
splitter.connect(anR, 1);
|
|
2874
3874
|
this.pcAnalysers = [anL, anR];
|
|
2875
3875
|
this.pcNoiseBuffer = this.createNoiseBuffer(ctx);
|
|
3876
|
+
this.emitAudioGraph("pc_ready");
|
|
2876
3877
|
}
|
|
2877
3878
|
// =========================================================================
|
|
2878
3879
|
// OUTPUT B: DUALSENSE 4CH (MODE 1: GAMEPADLY LINK COMPANION WASAPI)
|
|
@@ -3079,6 +4080,7 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
|
|
|
3079
4080
|
this.dsMerger.connect(ctx.destination);
|
|
3080
4081
|
}
|
|
3081
4082
|
this.dsNoiseBuffer = this.createNoiseBuffer(ctx);
|
|
4083
|
+
this.emitAudioGraph("ds_ready");
|
|
3082
4084
|
}
|
|
3083
4085
|
async teardownDsOutput() {
|
|
3084
4086
|
this.intentionalWsClose = true;
|
|
@@ -3087,6 +4089,7 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
|
|
|
3087
4089
|
this.reconnectTimer = null;
|
|
3088
4090
|
}
|
|
3089
4091
|
this.stopAllContinuous();
|
|
4092
|
+
this.emitAudioGraph("ds_teardown");
|
|
3090
4093
|
if (this.dsWorklet) {
|
|
3091
4094
|
try {
|
|
3092
4095
|
this.dsWorklet.port.onmessage = null;
|
|
@@ -3578,9 +4581,1552 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
|
|
|
3578
4581
|
}
|
|
3579
4582
|
};
|
|
3580
4583
|
|
|
3581
|
-
// src/link/
|
|
3582
|
-
|
|
3583
|
-
|
|
4584
|
+
// src/link/connect.ts
|
|
4585
|
+
var LINK_PROTOCOL_START_URI = "gamepadly-link://start";
|
|
4586
|
+
function shouldAutoLaunchLink() {
|
|
4587
|
+
if (typeof navigator === "undefined") return false;
|
|
4588
|
+
return /Windows/i.test(navigator.userAgent) && !/Firefox\//i.test(navigator.userAgent);
|
|
4589
|
+
}
|
|
4590
|
+
function launchLinkViaProtocol(uri = LINK_PROTOCOL_START_URI) {
|
|
4591
|
+
if (typeof document === "undefined" || !document.body) return;
|
|
4592
|
+
const anchor = document.createElement("a");
|
|
4593
|
+
anchor.href = uri;
|
|
4594
|
+
anchor.style.display = "none";
|
|
4595
|
+
document.body.appendChild(anchor);
|
|
4596
|
+
anchor.click();
|
|
4597
|
+
document.body.removeChild(anchor);
|
|
4598
|
+
}
|
|
4599
|
+
function errorMessage(err) {
|
|
4600
|
+
return err instanceof Error ? err.message : String(err);
|
|
4601
|
+
}
|
|
4602
|
+
async function launchAndWaitForCompanion(audio, uri, force) {
|
|
4603
|
+
let sawBlur = false;
|
|
4604
|
+
let wake = null;
|
|
4605
|
+
const onBlur = () => {
|
|
4606
|
+
sawBlur = true;
|
|
4607
|
+
};
|
|
4608
|
+
const onFocus = () => {
|
|
4609
|
+
const fn = wake;
|
|
4610
|
+
wake = null;
|
|
4611
|
+
fn?.();
|
|
4612
|
+
};
|
|
4613
|
+
const hasWindow = typeof window !== "undefined";
|
|
4614
|
+
if (hasWindow) {
|
|
4615
|
+
window.addEventListener("blur", onBlur);
|
|
4616
|
+
window.addEventListener("focus", onFocus);
|
|
4617
|
+
}
|
|
4618
|
+
let health = { online: false };
|
|
4619
|
+
try {
|
|
4620
|
+
launchLinkViaProtocol(uri);
|
|
4621
|
+
const startMs = Date.now();
|
|
4622
|
+
while (true) {
|
|
4623
|
+
await new Promise((resolve) => {
|
|
4624
|
+
const timer = setTimeout(() => {
|
|
4625
|
+
wake = null;
|
|
4626
|
+
resolve();
|
|
4627
|
+
}, 450);
|
|
4628
|
+
wake = () => {
|
|
4629
|
+
clearTimeout(timer);
|
|
4630
|
+
resolve();
|
|
4631
|
+
};
|
|
4632
|
+
});
|
|
4633
|
+
health = await audio.probeCompanion(700);
|
|
4634
|
+
if (health.online) break;
|
|
4635
|
+
const budgetMs = sawBlur || force ? 12e3 : 3600;
|
|
4636
|
+
if (Date.now() - startMs >= budgetMs) break;
|
|
4637
|
+
}
|
|
4638
|
+
} finally {
|
|
4639
|
+
if (hasWindow) {
|
|
4640
|
+
window.removeEventListener("blur", onBlur);
|
|
4641
|
+
window.removeEventListener("focus", onFocus);
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
return health;
|
|
4645
|
+
}
|
|
4646
|
+
async function connectDualSenseViaCompanion(audio, options = {}) {
|
|
4647
|
+
let health = { online: false };
|
|
4648
|
+
let devices = [];
|
|
4649
|
+
try {
|
|
4650
|
+
await audio.initPcOutput().catch(() => {
|
|
4651
|
+
});
|
|
4652
|
+
health = await audio.probeCompanion(900);
|
|
4653
|
+
const autoLaunch = options.autoLaunch ?? shouldAutoLaunchLink();
|
|
4654
|
+
if (!health.online && (options.forceLaunch || autoLaunch)) {
|
|
4655
|
+
options.onLaunchingChange?.(true);
|
|
4656
|
+
try {
|
|
4657
|
+
health = await launchAndWaitForCompanion(
|
|
4658
|
+
audio,
|
|
4659
|
+
options.launchUri ?? LINK_PROTOCOL_START_URI,
|
|
4660
|
+
Boolean(options.forceLaunch)
|
|
4661
|
+
);
|
|
4662
|
+
} finally {
|
|
4663
|
+
options.onLaunchingChange?.(false);
|
|
4664
|
+
}
|
|
4665
|
+
}
|
|
4666
|
+
if (!health.online) return { ok: false, error: "link_not_running", health, devices };
|
|
4667
|
+
devices = await audio.listCompanionDevices().catch(() => []);
|
|
4668
|
+
const target = (options.deviceId ? devices.find((d) => d.id === options.deviceId) : void 0) ?? devices.find((d) => d.isDualSense && d.channels >= 4) ?? devices.find((d) => d.isDualSense);
|
|
4669
|
+
const bind = await audio.connectDualSenseCompanion(
|
|
4670
|
+
target?.id || options.deviceId || "",
|
|
4671
|
+
target?.name || "DualSense WASAPI"
|
|
4672
|
+
);
|
|
4673
|
+
return { ok: true, bind, health, devices };
|
|
4674
|
+
} catch (err) {
|
|
4675
|
+
return { ok: false, error: "failed", message: errorMessage(err), health, devices };
|
|
4676
|
+
}
|
|
4677
|
+
}
|
|
4678
|
+
async function connectDualSenseViaBrowser(audio, options = {}) {
|
|
4679
|
+
try {
|
|
4680
|
+
if (!ThreeLayerAudioEngine.checkBrowserCapabilities().hasSetSinkId) {
|
|
4681
|
+
return { ok: false, error: "no_set_sink_id" };
|
|
4682
|
+
}
|
|
4683
|
+
await audio.initPcOutput().catch(() => {
|
|
4684
|
+
});
|
|
4685
|
+
await audio.unlockBrowserDeviceLabels();
|
|
4686
|
+
const outputs = await audio.listBrowserOutputDevices();
|
|
4687
|
+
const target = (options.deviceId ? outputs.find((o) => o.deviceId === options.deviceId) : void 0) ?? outputs.find(
|
|
4688
|
+
(o) => o.isLikelyDualSense && o.deviceId !== "default" && o.deviceId !== "communications"
|
|
4689
|
+
) ?? outputs.find((o) => o.isLikelyDualSense);
|
|
4690
|
+
if (!target) return { ok: false, error: "dualsense_audio_not_found" };
|
|
4691
|
+
const bind = await audio.connectDualSenseBrowserSink(target.deviceId, target.label);
|
|
4692
|
+
return { ok: true, bind };
|
|
4693
|
+
} catch (err) {
|
|
4694
|
+
return { ok: false, error: "failed", message: errorMessage(err) };
|
|
4695
|
+
}
|
|
4696
|
+
}
|
|
4697
|
+
|
|
4698
|
+
// src/audio/sampleBank.ts
|
|
4699
|
+
function createSampleBank(provider) {
|
|
4700
|
+
const sampleStore = /* @__PURE__ */ new Map();
|
|
4701
|
+
const activeSamples = /* @__PURE__ */ new Set();
|
|
4702
|
+
let disposed = false;
|
|
4703
|
+
const routing = () => provider.getAudioRouting();
|
|
4704
|
+
function buildAudioBufferFromPcm(ctx, pcm) {
|
|
4705
|
+
const chCount = Math.max(1, Math.min(4, pcm.channels.length));
|
|
4706
|
+
const frameCount = Math.max(1, pcm.channels[0]?.length ?? 1);
|
|
4707
|
+
const buf = ctx.createBuffer(chCount, frameCount, Math.max(8e3, Math.round(pcm.sampleRate)));
|
|
4708
|
+
for (let c = 0; c < chCount; c++) {
|
|
4709
|
+
const dst = buf.getChannelData(c);
|
|
4710
|
+
const src = pcm.channels[c] ?? pcm.channels[0];
|
|
4711
|
+
if (src) {
|
|
4712
|
+
dst.set(src.length === frameCount ? src : src.subarray(0, frameCount));
|
|
4713
|
+
}
|
|
4714
|
+
}
|
|
4715
|
+
return buf;
|
|
4716
|
+
}
|
|
4717
|
+
function decodeSampleForContext(id, target) {
|
|
4718
|
+
if (disposed) return Promise.resolve(null);
|
|
4719
|
+
const entry = sampleStore.get(id);
|
|
4720
|
+
const snap = routing();
|
|
4721
|
+
const ctx = target === "pc" ? snap.pcCtx : snap.dsCtx;
|
|
4722
|
+
if (!entry || !ctx) return Promise.resolve(null);
|
|
4723
|
+
if (target === "pc" && entry.pcCtxRef === ctx && entry.pcBuffer) {
|
|
4724
|
+
return Promise.resolve(entry.pcBuffer);
|
|
4725
|
+
}
|
|
4726
|
+
if (target === "ds" && entry.dsCtxRef === ctx && entry.dsBuffer) {
|
|
4727
|
+
return Promise.resolve(entry.dsBuffer);
|
|
4728
|
+
}
|
|
4729
|
+
if (entry.rawPcm) {
|
|
4730
|
+
const buf = buildAudioBufferFromPcm(ctx, entry.rawPcm);
|
|
4731
|
+
if (target === "pc") {
|
|
4732
|
+
entry.pcCtxRef = ctx;
|
|
4733
|
+
entry.pcBuffer = buf;
|
|
4734
|
+
} else {
|
|
4735
|
+
entry.dsCtxRef = ctx;
|
|
4736
|
+
entry.dsBuffer = buf;
|
|
4737
|
+
}
|
|
4738
|
+
return Promise.resolve(buf);
|
|
4739
|
+
}
|
|
4740
|
+
if (!entry.rawEncoded) return Promise.resolve(null);
|
|
4741
|
+
if (target === "pc" && entry.pcDecoding || target === "ds" && entry.dsDecoding) {
|
|
4742
|
+
return Promise.resolve(null);
|
|
4743
|
+
}
|
|
4744
|
+
if (target === "pc") entry.pcDecoding = true;
|
|
4745
|
+
else entry.dsDecoding = true;
|
|
4746
|
+
const copy = entry.rawEncoded.slice(0);
|
|
4747
|
+
return ctx.decodeAudioData(copy).then((decoded) => {
|
|
4748
|
+
if (disposed || sampleStore.get(id) !== entry) return null;
|
|
4749
|
+
const latest = routing();
|
|
4750
|
+
if (target === "pc" && latest.pcCtx === ctx) {
|
|
4751
|
+
entry.pcCtxRef = ctx;
|
|
4752
|
+
entry.pcBuffer = decoded;
|
|
4753
|
+
} else if (target === "ds" && latest.dsCtx === ctx) {
|
|
4754
|
+
entry.dsCtxRef = ctx;
|
|
4755
|
+
entry.dsBuffer = decoded;
|
|
4756
|
+
}
|
|
4757
|
+
return decoded;
|
|
4758
|
+
}).catch(() => null).finally(() => {
|
|
4759
|
+
if (target === "pc") entry.pcDecoding = false;
|
|
4760
|
+
else entry.dsDecoding = false;
|
|
4761
|
+
});
|
|
4762
|
+
}
|
|
4763
|
+
function warmSamplesForContext(target) {
|
|
4764
|
+
for (const id of sampleStore.keys()) {
|
|
4765
|
+
void decodeSampleForContext(id, target);
|
|
4766
|
+
}
|
|
4767
|
+
}
|
|
4768
|
+
function getSampleBufferSync(id, target) {
|
|
4769
|
+
const entry = sampleStore.get(id);
|
|
4770
|
+
const snap = routing();
|
|
4771
|
+
const ctx = target === "pc" ? snap.pcCtx : snap.dsCtx;
|
|
4772
|
+
if (!entry || !ctx) return null;
|
|
4773
|
+
if (target === "pc") {
|
|
4774
|
+
if (entry.pcCtxRef === ctx && entry.pcBuffer) return entry.pcBuffer;
|
|
4775
|
+
} else {
|
|
4776
|
+
if (entry.dsCtxRef === ctx && entry.dsBuffer) return entry.dsBuffer;
|
|
4777
|
+
}
|
|
4778
|
+
if (entry.rawPcm) {
|
|
4779
|
+
const buf = buildAudioBufferFromPcm(ctx, entry.rawPcm);
|
|
4780
|
+
if (target === "pc") {
|
|
4781
|
+
entry.pcCtxRef = ctx;
|
|
4782
|
+
entry.pcBuffer = buf;
|
|
4783
|
+
} else {
|
|
4784
|
+
entry.dsCtxRef = ctx;
|
|
4785
|
+
entry.dsBuffer = buf;
|
|
4786
|
+
}
|
|
4787
|
+
return buf;
|
|
4788
|
+
}
|
|
4789
|
+
void decodeSampleForContext(id, target);
|
|
4790
|
+
return null;
|
|
4791
|
+
}
|
|
4792
|
+
function stopAll(fadeOutMs = 0) {
|
|
4793
|
+
for (const h of Array.from(activeSamples)) {
|
|
4794
|
+
try {
|
|
4795
|
+
h.stop(fadeOutMs);
|
|
4796
|
+
} catch {
|
|
4797
|
+
}
|
|
4798
|
+
}
|
|
4799
|
+
activeSamples.clear();
|
|
4800
|
+
}
|
|
4801
|
+
const unsubGraph = typeof provider.onAudioGraphChange === "function" ? provider.onAudioGraphChange((ev) => {
|
|
4802
|
+
if (disposed) return;
|
|
4803
|
+
if (ev === "pc_ready") {
|
|
4804
|
+
warmSamplesForContext("pc");
|
|
4805
|
+
} else if (ev === "ds_ready") {
|
|
4806
|
+
warmSamplesForContext("ds");
|
|
4807
|
+
} else if (ev === "ds_teardown") {
|
|
4808
|
+
stopAll(0);
|
|
4809
|
+
for (const entry of sampleStore.values()) {
|
|
4810
|
+
entry.dsCtxRef = null;
|
|
4811
|
+
entry.dsBuffer = null;
|
|
4812
|
+
entry.dsDecoding = false;
|
|
4813
|
+
}
|
|
4814
|
+
}
|
|
4815
|
+
}) : () => {
|
|
4816
|
+
};
|
|
4817
|
+
return {
|
|
4818
|
+
async loadSample(id, source) {
|
|
4819
|
+
if (disposed || !id) return false;
|
|
4820
|
+
try {
|
|
4821
|
+
if (typeof source === "string") {
|
|
4822
|
+
const res = await fetch(source);
|
|
4823
|
+
if (!res.ok) return false;
|
|
4824
|
+
const raw = await res.arrayBuffer();
|
|
4825
|
+
sampleStore.set(id, { rawEncoded: raw });
|
|
4826
|
+
} else if (source instanceof ArrayBuffer) {
|
|
4827
|
+
sampleStore.set(id, { rawEncoded: source.slice(0) });
|
|
4828
|
+
} else if (source && Array.isArray(source.channels) && source.channels.length > 0) {
|
|
4829
|
+
sampleStore.set(id, {
|
|
4830
|
+
rawPcm: {
|
|
4831
|
+
sampleRate: source.sampleRate,
|
|
4832
|
+
channels: source.channels.map((ch) => new Float32Array(ch))
|
|
4833
|
+
}
|
|
4834
|
+
});
|
|
4835
|
+
} else {
|
|
4836
|
+
return false;
|
|
4837
|
+
}
|
|
4838
|
+
const snap = routing();
|
|
4839
|
+
const tasks = [];
|
|
4840
|
+
if (snap.pcCtx) tasks.push(decodeSampleForContext(id, "pc"));
|
|
4841
|
+
if (snap.dsCtx) tasks.push(decodeSampleForContext(id, "ds"));
|
|
4842
|
+
if (tasks.length > 0) await Promise.all(tasks);
|
|
4843
|
+
return true;
|
|
4844
|
+
} catch {
|
|
4845
|
+
return false;
|
|
4846
|
+
}
|
|
4847
|
+
},
|
|
4848
|
+
hasSample(id) {
|
|
4849
|
+
return sampleStore.has(id);
|
|
4850
|
+
},
|
|
4851
|
+
unloadSample(id) {
|
|
4852
|
+
sampleStore.delete(id);
|
|
4853
|
+
},
|
|
4854
|
+
playSample(id, options = {}) {
|
|
4855
|
+
if (disposed) return NOOP_SAMPLE_HANDLE;
|
|
4856
|
+
const route = options.route ?? "pc";
|
|
4857
|
+
const initPan = Math.max(-1, Math.min(1, options.pan ?? 0));
|
|
4858
|
+
const initGain = Math.max(1e-3, Math.min(1.5, options.gain ?? 0.85));
|
|
4859
|
+
const initRate = Math.max(0.25, Math.min(4, options.playbackRate ?? 1));
|
|
4860
|
+
const loop = Boolean(options.loop);
|
|
4861
|
+
const delaySec = Math.max(0, (options.delayMs ?? 0) / 1e3);
|
|
4862
|
+
const snap = routing();
|
|
4863
|
+
const dsReady4Ch = Boolean(snap.dsCtx && snap.dsChGains.length >= 4);
|
|
4864
|
+
const dsReady2Ch = Boolean(snap.dsCtx && snap.dsChGains.length >= 2);
|
|
4865
|
+
let target = "pc";
|
|
4866
|
+
let effectiveRoute = route;
|
|
4867
|
+
let gainScale = 1;
|
|
4868
|
+
if (route === "vcm") {
|
|
4869
|
+
if (!dsReady4Ch) return NOOP_SAMPLE_HANDLE;
|
|
4870
|
+
target = "ds";
|
|
4871
|
+
} else if (route === "speaker") {
|
|
4872
|
+
if (dsReady2Ch) {
|
|
4873
|
+
target = "ds";
|
|
4874
|
+
} else if (snap.pcCtx && snap.pcMasterGain) {
|
|
4875
|
+
target = "pc";
|
|
4876
|
+
effectiveRoute = "pc";
|
|
4877
|
+
gainScale = 0.45;
|
|
4878
|
+
} else {
|
|
4879
|
+
return NOOP_SAMPLE_HANDLE;
|
|
4880
|
+
}
|
|
4881
|
+
} else if (route === "quad") {
|
|
4882
|
+
if (dsReady4Ch) {
|
|
4883
|
+
target = "ds";
|
|
4884
|
+
} else if (snap.pcCtx && snap.pcMasterGain) {
|
|
4885
|
+
target = "pc";
|
|
4886
|
+
effectiveRoute = "pc";
|
|
4887
|
+
gainScale = 0.5;
|
|
4888
|
+
} else {
|
|
4889
|
+
return NOOP_SAMPLE_HANDLE;
|
|
4890
|
+
}
|
|
4891
|
+
} else {
|
|
4892
|
+
if (!snap.pcCtx || !snap.pcMasterGain) return NOOP_SAMPLE_HANDLE;
|
|
4893
|
+
target = "pc";
|
|
4894
|
+
}
|
|
4895
|
+
const ctx = target === "pc" ? snap.pcCtx : snap.dsCtx;
|
|
4896
|
+
const buffer = getSampleBufferSync(id, target);
|
|
4897
|
+
if (!buffer) return NOOP_SAMPLE_HANDLE;
|
|
4898
|
+
const src = ctx.createBufferSource();
|
|
4899
|
+
src.buffer = buffer;
|
|
4900
|
+
src.loop = loop;
|
|
4901
|
+
src.playbackRate.value = initRate;
|
|
4902
|
+
const masterGain = ctx.createGain();
|
|
4903
|
+
masterGain.gain.value = initGain * gainScale;
|
|
4904
|
+
let pcPanner = null;
|
|
4905
|
+
let vcmGainL = null;
|
|
4906
|
+
let vcmGainR = null;
|
|
4907
|
+
const cleanupNodes = [src, masterGain];
|
|
4908
|
+
if (effectiveRoute === "pc") {
|
|
4909
|
+
pcPanner = ctx.createStereoPanner();
|
|
4910
|
+
pcPanner.pan.value = initPan;
|
|
4911
|
+
src.connect(masterGain);
|
|
4912
|
+
masterGain.connect(pcPanner);
|
|
4913
|
+
pcPanner.connect(snap.pcMasterGain);
|
|
4914
|
+
cleanupNodes.push(pcPanner);
|
|
4915
|
+
} else if (effectiveRoute === "speaker") {
|
|
4916
|
+
src.connect(masterGain);
|
|
4917
|
+
masterGain.connect(snap.dsChGains[0]);
|
|
4918
|
+
masterGain.connect(snap.dsChGains[1]);
|
|
4919
|
+
} else if (effectiveRoute === "vcm") {
|
|
4920
|
+
vcmGainL = ctx.createGain();
|
|
4921
|
+
vcmGainR = ctx.createGain();
|
|
4922
|
+
vcmGainL.gain.value = Math.cos((initPan + 1) * Math.PI / 4);
|
|
4923
|
+
vcmGainR.gain.value = Math.sin((initPan + 1) * Math.PI / 4);
|
|
4924
|
+
src.connect(masterGain);
|
|
4925
|
+
masterGain.connect(vcmGainL);
|
|
4926
|
+
masterGain.connect(vcmGainR);
|
|
4927
|
+
vcmGainL.connect(snap.dsChGains[2]);
|
|
4928
|
+
vcmGainR.connect(snap.dsChGains[3]);
|
|
4929
|
+
cleanupNodes.push(vcmGainL, vcmGainR);
|
|
4930
|
+
} else {
|
|
4931
|
+
if (buffer.numberOfChannels >= 4) {
|
|
4932
|
+
const splitter = ctx.createChannelSplitter(4);
|
|
4933
|
+
const spkMono = ctx.createGain();
|
|
4934
|
+
spkMono.gain.value = 0.5;
|
|
4935
|
+
vcmGainL = ctx.createGain();
|
|
4936
|
+
vcmGainR = ctx.createGain();
|
|
4937
|
+
vcmGainL.gain.value = Math.cos((initPan + 1) * Math.PI / 4) * Math.SQRT2;
|
|
4938
|
+
vcmGainR.gain.value = Math.sin((initPan + 1) * Math.PI / 4) * Math.SQRT2;
|
|
4939
|
+
src.connect(masterGain);
|
|
4940
|
+
masterGain.connect(splitter);
|
|
4941
|
+
splitter.connect(spkMono, 0);
|
|
4942
|
+
splitter.connect(spkMono, 1);
|
|
4943
|
+
spkMono.connect(snap.dsChGains[0]);
|
|
4944
|
+
spkMono.connect(snap.dsChGains[1]);
|
|
4945
|
+
splitter.connect(vcmGainL, 2);
|
|
4946
|
+
splitter.connect(vcmGainR, 3);
|
|
4947
|
+
vcmGainL.connect(snap.dsChGains[2]);
|
|
4948
|
+
vcmGainR.connect(snap.dsChGains[3]);
|
|
4949
|
+
cleanupNodes.push(splitter, spkMono, vcmGainL, vcmGainR);
|
|
4950
|
+
} else {
|
|
4951
|
+
const spkAtt = ctx.createGain();
|
|
4952
|
+
spkAtt.gain.value = 0.35;
|
|
4953
|
+
vcmGainL = ctx.createGain();
|
|
4954
|
+
vcmGainR = ctx.createGain();
|
|
4955
|
+
vcmGainL.gain.value = Math.cos((initPan + 1) * Math.PI / 4);
|
|
4956
|
+
vcmGainR.gain.value = Math.sin((initPan + 1) * Math.PI / 4);
|
|
4957
|
+
src.connect(masterGain);
|
|
4958
|
+
masterGain.connect(spkAtt);
|
|
4959
|
+
spkAtt.connect(snap.dsChGains[0]);
|
|
4960
|
+
spkAtt.connect(snap.dsChGains[1]);
|
|
4961
|
+
masterGain.connect(vcmGainL);
|
|
4962
|
+
masterGain.connect(vcmGainR);
|
|
4963
|
+
vcmGainL.connect(snap.dsChGains[2]);
|
|
4964
|
+
vcmGainR.connect(snap.dsChGains[3]);
|
|
4965
|
+
cleanupNodes.push(spkAtt, vcmGainL, vcmGainR);
|
|
4966
|
+
}
|
|
4967
|
+
}
|
|
4968
|
+
let isActive = true;
|
|
4969
|
+
const disposeNodes = () => {
|
|
4970
|
+
if (!isActive) return;
|
|
4971
|
+
isActive = false;
|
|
4972
|
+
activeSamples.delete(handle);
|
|
4973
|
+
for (const n of cleanupNodes) {
|
|
4974
|
+
try {
|
|
4975
|
+
n.disconnect();
|
|
4976
|
+
} catch {
|
|
4977
|
+
}
|
|
4978
|
+
}
|
|
4979
|
+
};
|
|
4980
|
+
const handle = {
|
|
4981
|
+
get active() {
|
|
4982
|
+
return isActive;
|
|
4983
|
+
},
|
|
4984
|
+
update: ({ pan, gain, playbackRate } = {}) => {
|
|
4985
|
+
if (!isActive) return;
|
|
4986
|
+
const now = ctx.currentTime;
|
|
4987
|
+
if (gain !== void 0) {
|
|
4988
|
+
const g = Math.max(1e-4, Math.min(1.5, gain)) * gainScale;
|
|
4989
|
+
masterGain.gain.setTargetAtTime(g, now, 0.02);
|
|
4990
|
+
}
|
|
4991
|
+
if (playbackRate !== void 0) {
|
|
4992
|
+
const r = Math.max(0.25, Math.min(4, playbackRate));
|
|
4993
|
+
src.playbackRate.setTargetAtTime(r, now, 0.025);
|
|
4994
|
+
}
|
|
4995
|
+
if (pan !== void 0) {
|
|
4996
|
+
const p = Math.max(-1, Math.min(1, pan));
|
|
4997
|
+
if (pcPanner) {
|
|
4998
|
+
pcPanner.pan.setTargetAtTime(p, now, 0.02);
|
|
4999
|
+
}
|
|
5000
|
+
if (vcmGainL && vcmGainR) {
|
|
5001
|
+
const mult = effectiveRoute === "quad" && buffer.numberOfChannels >= 4 ? Math.SQRT2 : 1;
|
|
5002
|
+
vcmGainL.gain.setTargetAtTime(Math.cos((p + 1) * Math.PI / 4) * mult, now, 0.02);
|
|
5003
|
+
vcmGainR.gain.setTargetAtTime(Math.sin((p + 1) * Math.PI / 4) * mult, now, 0.02);
|
|
5004
|
+
}
|
|
5005
|
+
}
|
|
5006
|
+
},
|
|
5007
|
+
stop: (fadeOutMs = 0) => {
|
|
5008
|
+
if (!isActive) return;
|
|
5009
|
+
const now = ctx.currentTime;
|
|
5010
|
+
if (fadeOutMs > 4) {
|
|
5011
|
+
const fadeSec = Math.min(2, fadeOutMs / 1e3);
|
|
5012
|
+
try {
|
|
5013
|
+
masterGain.gain.cancelScheduledValues(now);
|
|
5014
|
+
masterGain.gain.setValueAtTime(Math.max(1e-4, masterGain.gain.value), now);
|
|
5015
|
+
masterGain.gain.exponentialRampToValueAtTime(1e-4, now + fadeSec);
|
|
5016
|
+
src.stop(now + fadeSec + 0.015);
|
|
5017
|
+
} catch {
|
|
5018
|
+
disposeNodes();
|
|
5019
|
+
}
|
|
5020
|
+
} else {
|
|
5021
|
+
try {
|
|
5022
|
+
src.stop();
|
|
5023
|
+
} catch {
|
|
5024
|
+
}
|
|
5025
|
+
disposeNodes();
|
|
5026
|
+
}
|
|
5027
|
+
}
|
|
5028
|
+
};
|
|
5029
|
+
src.onended = () => {
|
|
5030
|
+
disposeNodes();
|
|
5031
|
+
};
|
|
5032
|
+
activeSamples.add(handle);
|
|
5033
|
+
src.start(ctx.currentTime + delaySec);
|
|
5034
|
+
return handle;
|
|
5035
|
+
},
|
|
5036
|
+
stopAll,
|
|
5037
|
+
dispose() {
|
|
5038
|
+
if (disposed) return;
|
|
5039
|
+
disposed = true;
|
|
5040
|
+
unsubGraph();
|
|
5041
|
+
stopAll(0);
|
|
5042
|
+
sampleStore.clear();
|
|
5043
|
+
}
|
|
5044
|
+
};
|
|
5045
|
+
}
|
|
5046
|
+
|
|
5047
|
+
// src/link/index.ts
|
|
5048
|
+
function createLinkAudio(options) {
|
|
5049
|
+
const engine = new ThreeLayerAudioEngine(options);
|
|
5050
|
+
const bank = createSampleBank(engine);
|
|
5051
|
+
return Object.assign(engine, {
|
|
5052
|
+
loadSample: bank.loadSample,
|
|
5053
|
+
hasSample: bank.hasSample,
|
|
5054
|
+
unloadSample: bank.unloadSample,
|
|
5055
|
+
playSample: bank.playSample,
|
|
5056
|
+
stopAllSamples: bank.stopAll
|
|
5057
|
+
});
|
|
5058
|
+
}
|
|
5059
|
+
|
|
5060
|
+
// src/audio/routing.ts
|
|
5061
|
+
function createPcAudioRouting(ctx, destination = ctx.destination) {
|
|
5062
|
+
const output = ctx.createGain();
|
|
5063
|
+
output.connect(destination);
|
|
5064
|
+
let disposed = false;
|
|
5065
|
+
return {
|
|
5066
|
+
output,
|
|
5067
|
+
getAudioRouting: () => ({
|
|
5068
|
+
pcCtx: disposed ? null : ctx,
|
|
5069
|
+
pcMasterGain: disposed ? null : output,
|
|
5070
|
+
dsCtx: null,
|
|
5071
|
+
dsChGains: []
|
|
5072
|
+
}),
|
|
5073
|
+
dispose() {
|
|
5074
|
+
if (disposed) return;
|
|
5075
|
+
disposed = true;
|
|
5076
|
+
try {
|
|
5077
|
+
output.disconnect();
|
|
5078
|
+
} catch {
|
|
5079
|
+
}
|
|
5080
|
+
}
|
|
5081
|
+
};
|
|
5082
|
+
}
|
|
5083
|
+
|
|
5084
|
+
// src/mic/input.ts
|
|
5085
|
+
var CONTROLLER_MIC_RE = /wireless controller|dualsense|ps5/i;
|
|
5086
|
+
function isMicInputSupported() {
|
|
5087
|
+
return typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia) && typeof window !== "undefined" && Boolean(
|
|
5088
|
+
window.AudioContext || window.webkitAudioContext
|
|
5089
|
+
);
|
|
5090
|
+
}
|
|
5091
|
+
function rawConstraints(deviceId) {
|
|
5092
|
+
return {
|
|
5093
|
+
video: false,
|
|
5094
|
+
audio: {
|
|
5095
|
+
...deviceId ? { deviceId: { exact: deviceId } } : {},
|
|
5096
|
+
echoCancellation: false,
|
|
5097
|
+
noiseSuppression: false,
|
|
5098
|
+
autoGainControl: false
|
|
5099
|
+
}
|
|
5100
|
+
};
|
|
5101
|
+
}
|
|
5102
|
+
function stopStream(s) {
|
|
5103
|
+
if (!s) return;
|
|
5104
|
+
for (const track of s.getTracks()) {
|
|
5105
|
+
try {
|
|
5106
|
+
track.stop();
|
|
5107
|
+
} catch {
|
|
5108
|
+
}
|
|
5109
|
+
}
|
|
5110
|
+
}
|
|
5111
|
+
async function findControllerMic() {
|
|
5112
|
+
if (!navigator.mediaDevices?.enumerateDevices) return void 0;
|
|
5113
|
+
try {
|
|
5114
|
+
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
5115
|
+
return devices.find((d) => d.kind === "audioinput" && CONTROLLER_MIC_RE.test(d.label || ""));
|
|
5116
|
+
} catch {
|
|
5117
|
+
return void 0;
|
|
5118
|
+
}
|
|
5119
|
+
}
|
|
5120
|
+
async function openMicInput(options = {}) {
|
|
5121
|
+
if (!isMicInputSupported()) return "unsupported";
|
|
5122
|
+
const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
|
5123
|
+
const preferPad = !options.deviceId && options.preferControllerMic !== false;
|
|
5124
|
+
let stream = null;
|
|
5125
|
+
try {
|
|
5126
|
+
const known = preferPad ? await findControllerMic() : void 0;
|
|
5127
|
+
try {
|
|
5128
|
+
stream = await navigator.mediaDevices.getUserMedia(rawConstraints(options.deviceId ?? known?.deviceId));
|
|
5129
|
+
} catch (err) {
|
|
5130
|
+
if (!known) throw err;
|
|
5131
|
+
stream = await navigator.mediaDevices.getUserMedia(rawConstraints());
|
|
5132
|
+
}
|
|
5133
|
+
if (preferPad && !CONTROLLER_MIC_RE.test(stream.getAudioTracks()[0]?.label || "")) {
|
|
5134
|
+
const pad = await findControllerMic();
|
|
5135
|
+
const currentId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
|
|
5136
|
+
if (pad?.deviceId && pad.deviceId !== currentId) {
|
|
5137
|
+
try {
|
|
5138
|
+
const padStream = await navigator.mediaDevices.getUserMedia(rawConstraints(pad.deviceId));
|
|
5139
|
+
stopStream(stream);
|
|
5140
|
+
stream = padStream;
|
|
5141
|
+
} catch {
|
|
5142
|
+
}
|
|
5143
|
+
}
|
|
5144
|
+
}
|
|
5145
|
+
const ctx = new AudioCtx();
|
|
5146
|
+
if (ctx.state === "suspended") await ctx.resume();
|
|
5147
|
+
const source = ctx.createMediaStreamSource(stream);
|
|
5148
|
+
const analyser = ctx.createAnalyser();
|
|
5149
|
+
analyser.fftSize = options.fftSize ?? 512;
|
|
5150
|
+
analyser.smoothingTimeConstant = options.smoothing ?? 0.55;
|
|
5151
|
+
source.connect(analyser);
|
|
5152
|
+
const label = stream.getAudioTracks()[0]?.label || "";
|
|
5153
|
+
const activeStream = stream;
|
|
5154
|
+
let closed = false;
|
|
5155
|
+
return {
|
|
5156
|
+
ctx,
|
|
5157
|
+
analyser,
|
|
5158
|
+
stream: activeStream,
|
|
5159
|
+
label,
|
|
5160
|
+
usingControllerMic: CONTROLLER_MIC_RE.test(label),
|
|
5161
|
+
close() {
|
|
5162
|
+
if (closed) return;
|
|
5163
|
+
closed = true;
|
|
5164
|
+
try {
|
|
5165
|
+
source.disconnect();
|
|
5166
|
+
} catch {
|
|
5167
|
+
}
|
|
5168
|
+
stopStream(activeStream);
|
|
5169
|
+
ctx.close().catch(() => {
|
|
5170
|
+
});
|
|
5171
|
+
}
|
|
5172
|
+
};
|
|
5173
|
+
} catch {
|
|
5174
|
+
stopStream(stream);
|
|
5175
|
+
return "denied";
|
|
5176
|
+
}
|
|
5177
|
+
}
|
|
5178
|
+
function timeDomainRms(buf) {
|
|
5179
|
+
if (buf.length === 0) return 0;
|
|
5180
|
+
let sumSq = 0;
|
|
5181
|
+
for (let i = 0; i < buf.length; i++) {
|
|
5182
|
+
const v = (buf[i] - 128) / 128;
|
|
5183
|
+
sumSq += v * v;
|
|
5184
|
+
}
|
|
5185
|
+
return Math.sqrt(sumSq / buf.length);
|
|
5186
|
+
}
|
|
5187
|
+
|
|
5188
|
+
// src/mic/blow.ts
|
|
5189
|
+
function clamp4(v, min, max) {
|
|
5190
|
+
return Math.max(min, Math.min(max, v));
|
|
5191
|
+
}
|
|
5192
|
+
function analyzeBlowSpectrum(freqBins, timeDomain, sampleRate, fftSize, opts = {}) {
|
|
5193
|
+
const rmsThreshold = opts.rmsThreshold ?? 0.035;
|
|
5194
|
+
const flatnessThreshold = opts.flatnessThreshold ?? 0.28;
|
|
5195
|
+
let sumSq = 0;
|
|
5196
|
+
for (let i = 0; i < timeDomain.length; i++) {
|
|
5197
|
+
const s = (timeDomain[i] - 128) / 128;
|
|
5198
|
+
sumSq += s * s;
|
|
5199
|
+
}
|
|
5200
|
+
const rms = timeDomain.length > 0 ? Math.sqrt(sumSq / timeDomain.length) : 0;
|
|
5201
|
+
const binHz = sampleRate / Math.max(1, fftSize);
|
|
5202
|
+
const startBin = Math.max(1, Math.floor(80 / binHz));
|
|
5203
|
+
const endBin = Math.min(freqBins.length - 1, Math.ceil(1600 / binHz));
|
|
5204
|
+
const count = Math.max(1, endBin - startBin + 1);
|
|
5205
|
+
let arithSum = 0;
|
|
5206
|
+
let logSum = 0;
|
|
5207
|
+
let activeBins = 0;
|
|
5208
|
+
for (let i = startBin; i <= endBin; i++) {
|
|
5209
|
+
const mag = Math.max(1e-4, freqBins[i] / 255);
|
|
5210
|
+
arithSum += mag;
|
|
5211
|
+
logSum += Math.log(mag);
|
|
5212
|
+
if (freqBins[i] > 18) activeBins++;
|
|
5213
|
+
}
|
|
5214
|
+
const arithMean = arithSum / count;
|
|
5215
|
+
const geomMean = Math.exp(logSum / count);
|
|
5216
|
+
const flatness = arithMean > 1e-4 ? clamp4(geomMean / arithMean, 0, 1) : 0;
|
|
5217
|
+
const bandFill = activeBins / count;
|
|
5218
|
+
if (rms < rmsThreshold) {
|
|
5219
|
+
return { rms, flatness, rawIntensity: 0 };
|
|
5220
|
+
}
|
|
5221
|
+
const levelNorm = clamp4((rms - rmsThreshold) / Math.max(0.05, 0.28 - rmsThreshold), 0, 1);
|
|
5222
|
+
const flatnessFactor = clamp4(
|
|
5223
|
+
(flatness - flatnessThreshold * 0.65) / Math.max(0.15, 0.78 - flatnessThreshold * 0.65),
|
|
5224
|
+
0,
|
|
5225
|
+
1
|
|
5226
|
+
);
|
|
5227
|
+
const fillFactor = clamp4(bandFill / 0.45, 0, 1);
|
|
5228
|
+
const rawIntensity = clamp4(levelNorm * (0.25 + 0.75 * flatnessFactor * fillFactor), 0, 1);
|
|
5229
|
+
return { rms, flatness, rawIntensity };
|
|
5230
|
+
}
|
|
5231
|
+
function createMicBlowSensor(options = {}) {
|
|
5232
|
+
const rmsThreshold = clamp4(options.rmsThreshold ?? 0.035, 5e-3, 0.5);
|
|
5233
|
+
const flatnessThreshold = clamp4(options.flatnessThreshold ?? 0.28, 0.05, 0.9);
|
|
5234
|
+
const blowingThreshold = clamp4(options.blowingThreshold ?? 0.22, 0.05, 0.95);
|
|
5235
|
+
const smoothing = clamp4(options.smoothing ?? 0.28, 0.05, 1);
|
|
5236
|
+
const fftSize = options.fftSize ?? 512;
|
|
5237
|
+
let input = null;
|
|
5238
|
+
let analyser = null;
|
|
5239
|
+
let freqBuf = null;
|
|
5240
|
+
let timeBuf = null;
|
|
5241
|
+
let blowingSinceMs = 0;
|
|
5242
|
+
let opSeq = 0;
|
|
5243
|
+
const state = {
|
|
5244
|
+
status: "idle",
|
|
5245
|
+
intensity: 0,
|
|
5246
|
+
blowing: false,
|
|
5247
|
+
sustainedMs: 0,
|
|
5248
|
+
peakIntensity: 0,
|
|
5249
|
+
rms: 0,
|
|
5250
|
+
flatness: 0,
|
|
5251
|
+
deviceLabel: "",
|
|
5252
|
+
usingControllerMic: false
|
|
5253
|
+
};
|
|
5254
|
+
function stop() {
|
|
5255
|
+
opSeq++;
|
|
5256
|
+
input?.close();
|
|
5257
|
+
input = null;
|
|
5258
|
+
analyser = null;
|
|
5259
|
+
freqBuf = null;
|
|
5260
|
+
timeBuf = null;
|
|
5261
|
+
blowingSinceMs = 0;
|
|
5262
|
+
state.status = state.status === "denied" || state.status === "unsupported" ? state.status : "idle";
|
|
5263
|
+
state.intensity = 0;
|
|
5264
|
+
state.blowing = false;
|
|
5265
|
+
state.sustainedMs = 0;
|
|
5266
|
+
state.rms = 0;
|
|
5267
|
+
state.flatness = 0;
|
|
5268
|
+
state.deviceLabel = "";
|
|
5269
|
+
state.usingControllerMic = false;
|
|
5270
|
+
}
|
|
5271
|
+
return {
|
|
5272
|
+
async start() {
|
|
5273
|
+
stop();
|
|
5274
|
+
const mySeq = opSeq;
|
|
5275
|
+
state.peakIntensity = 0;
|
|
5276
|
+
const opened = await openMicInput({
|
|
5277
|
+
preferControllerMic: options.preferControllerMic,
|
|
5278
|
+
deviceId: options.deviceId,
|
|
5279
|
+
fftSize,
|
|
5280
|
+
smoothing: 0.55
|
|
5281
|
+
});
|
|
5282
|
+
if (mySeq !== opSeq) {
|
|
5283
|
+
if (typeof opened !== "string") opened.close();
|
|
5284
|
+
return false;
|
|
5285
|
+
}
|
|
5286
|
+
if (typeof opened === "string") {
|
|
5287
|
+
state.status = opened;
|
|
5288
|
+
return false;
|
|
5289
|
+
}
|
|
5290
|
+
input = opened;
|
|
5291
|
+
analyser = opened.analyser;
|
|
5292
|
+
freqBuf = new Uint8Array(new ArrayBuffer(analyser.frequencyBinCount));
|
|
5293
|
+
timeBuf = new Uint8Array(new ArrayBuffer(analyser.fftSize));
|
|
5294
|
+
state.status = "active";
|
|
5295
|
+
state.deviceLabel = opened.label || "Microphone";
|
|
5296
|
+
state.usingControllerMic = opened.usingControllerMic;
|
|
5297
|
+
return true;
|
|
5298
|
+
},
|
|
5299
|
+
stop,
|
|
5300
|
+
sample(nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) {
|
|
5301
|
+
if (state.status !== "active" || !input || !analyser || !freqBuf || !timeBuf) {
|
|
5302
|
+
return state;
|
|
5303
|
+
}
|
|
5304
|
+
analyser.getByteFrequencyData(freqBuf);
|
|
5305
|
+
analyser.getByteTimeDomainData(timeBuf);
|
|
5306
|
+
const metrics = analyzeBlowSpectrum(freqBuf, timeBuf, input.ctx.sampleRate, analyser.fftSize, {
|
|
5307
|
+
rmsThreshold,
|
|
5308
|
+
flatnessThreshold
|
|
5309
|
+
});
|
|
5310
|
+
const target = metrics.rawIntensity;
|
|
5311
|
+
state.intensity = state.intensity + (target - state.intensity) * smoothing;
|
|
5312
|
+
if (state.intensity < 5e-3) state.intensity = 0;
|
|
5313
|
+
if (state.intensity > state.peakIntensity) state.peakIntensity = state.intensity;
|
|
5314
|
+
state.rms = metrics.rms;
|
|
5315
|
+
state.flatness = metrics.flatness;
|
|
5316
|
+
const isBlowing = state.intensity >= blowingThreshold;
|
|
5317
|
+
if (isBlowing) {
|
|
5318
|
+
if (!state.blowing) blowingSinceMs = nowMs;
|
|
5319
|
+
state.sustainedMs = Math.max(0, nowMs - blowingSinceMs);
|
|
5320
|
+
} else {
|
|
5321
|
+
blowingSinceMs = 0;
|
|
5322
|
+
state.sustainedMs = 0;
|
|
5323
|
+
}
|
|
5324
|
+
state.blowing = isBlowing;
|
|
5325
|
+
return state;
|
|
5326
|
+
},
|
|
5327
|
+
getState() {
|
|
5328
|
+
return state;
|
|
5329
|
+
},
|
|
5330
|
+
dispose() {
|
|
5331
|
+
stop();
|
|
5332
|
+
}
|
|
5333
|
+
};
|
|
5334
|
+
}
|
|
5335
|
+
|
|
5336
|
+
// src/mic/level.ts
|
|
5337
|
+
function createMicLevelMeter(options = {}) {
|
|
5338
|
+
const gain = options.gain ?? 2.6;
|
|
5339
|
+
let input = null;
|
|
5340
|
+
let buf = null;
|
|
5341
|
+
let opSeq = 0;
|
|
5342
|
+
const state = {
|
|
5343
|
+
status: "idle",
|
|
5344
|
+
level: 0,
|
|
5345
|
+
peak: 0,
|
|
5346
|
+
rms: 0,
|
|
5347
|
+
deviceLabel: "",
|
|
5348
|
+
usingControllerMic: false
|
|
5349
|
+
};
|
|
5350
|
+
const stop = () => {
|
|
5351
|
+
opSeq++;
|
|
5352
|
+
input?.close();
|
|
5353
|
+
input = null;
|
|
5354
|
+
buf = null;
|
|
5355
|
+
if (state.status === "active") state.status = "idle";
|
|
5356
|
+
state.level = 0;
|
|
5357
|
+
state.rms = 0;
|
|
5358
|
+
};
|
|
5359
|
+
return {
|
|
5360
|
+
async start() {
|
|
5361
|
+
stop();
|
|
5362
|
+
const mySeq = opSeq;
|
|
5363
|
+
const opened = await openMicInput({ fftSize: 256, smoothing: 0.65, ...options });
|
|
5364
|
+
if (mySeq !== opSeq) {
|
|
5365
|
+
if (typeof opened !== "string") opened.close();
|
|
5366
|
+
return false;
|
|
5367
|
+
}
|
|
5368
|
+
if (typeof opened === "string") {
|
|
5369
|
+
state.status = opened;
|
|
5370
|
+
return false;
|
|
5371
|
+
}
|
|
5372
|
+
input = opened;
|
|
5373
|
+
buf = new Uint8Array(new ArrayBuffer(opened.analyser.fftSize));
|
|
5374
|
+
state.status = "active";
|
|
5375
|
+
state.peak = 0;
|
|
5376
|
+
state.deviceLabel = opened.label;
|
|
5377
|
+
state.usingControllerMic = opened.usingControllerMic;
|
|
5378
|
+
return true;
|
|
5379
|
+
},
|
|
5380
|
+
sample() {
|
|
5381
|
+
if (!input || !buf) return state;
|
|
5382
|
+
input.analyser.getByteTimeDomainData(buf);
|
|
5383
|
+
state.rms = timeDomainRms(buf);
|
|
5384
|
+
state.level = Math.min(1, state.rms * gain);
|
|
5385
|
+
if (state.level > state.peak) state.peak = state.level;
|
|
5386
|
+
return state;
|
|
5387
|
+
},
|
|
5388
|
+
getState: () => state,
|
|
5389
|
+
stop,
|
|
5390
|
+
dispose: stop
|
|
5391
|
+
};
|
|
5392
|
+
}
|
|
5393
|
+
|
|
5394
|
+
// src/game/types.ts
|
|
5395
|
+
function defineGame(game) {
|
|
5396
|
+
return game;
|
|
5397
|
+
}
|
|
5398
|
+
|
|
5399
|
+
// src/game/host.ts
|
|
5400
|
+
var NOOP_CONTINUOUS_HANDLE = {
|
|
5401
|
+
update() {
|
|
5402
|
+
},
|
|
5403
|
+
stop() {
|
|
5404
|
+
}
|
|
5405
|
+
};
|
|
5406
|
+
function createLocalBestScoreStorage(key) {
|
|
5407
|
+
return {
|
|
5408
|
+
getBestScore: () => {
|
|
5409
|
+
if (typeof localStorage === "undefined") return 0;
|
|
5410
|
+
try {
|
|
5411
|
+
const raw = localStorage.getItem(key);
|
|
5412
|
+
return raw ? Number(raw) || 0 : 0;
|
|
5413
|
+
} catch {
|
|
5414
|
+
return 0;
|
|
5415
|
+
}
|
|
5416
|
+
},
|
|
5417
|
+
saveBestScore: (score) => {
|
|
5418
|
+
if (typeof localStorage === "undefined") return;
|
|
5419
|
+
try {
|
|
5420
|
+
const prev = Number(localStorage.getItem(key) || 0);
|
|
5421
|
+
if (score > prev) localStorage.setItem(key, String(Math.round(score)));
|
|
5422
|
+
} catch {
|
|
5423
|
+
}
|
|
5424
|
+
}
|
|
5425
|
+
};
|
|
5426
|
+
}
|
|
5427
|
+
function createGameHost(opts) {
|
|
5428
|
+
const { gameId, locale, getPlayerSeats } = opts;
|
|
5429
|
+
const hub = createGamepadly(opts.hub);
|
|
5430
|
+
const active = hub.active;
|
|
5431
|
+
const idleKeyboardState = createEmptyInput();
|
|
5432
|
+
idleKeyboardState.source = "keyboard_mouse";
|
|
5433
|
+
idleKeyboardState.deviceName = "Keyboard & Mouse";
|
|
5434
|
+
idleKeyboardState.identity = {
|
|
5435
|
+
brand: "none",
|
|
5436
|
+
model: "none",
|
|
5437
|
+
displayName: "Keyboard & Mouse",
|
|
5438
|
+
rawId: "",
|
|
5439
|
+
transport: "disconnected",
|
|
5440
|
+
source: "keyboard_mouse"
|
|
5441
|
+
};
|
|
5442
|
+
const idleDisconnectedState = createEmptyInput();
|
|
5443
|
+
const sanitizeInput = opts.isolateKeyboardFallback === false ? (st) => st : (st) => st.source === "keyboard_mouse" ? idleKeyboardState : st;
|
|
5444
|
+
const slotHandleCache = /* @__PURE__ */ new Map();
|
|
5445
|
+
const getCachedSlotHandle = (slotId) => {
|
|
5446
|
+
let h = slotHandleCache.get(slotId);
|
|
5447
|
+
if (!h) {
|
|
5448
|
+
h = hub.player(slotId);
|
|
5449
|
+
slotHandleCache.set(slotId, h);
|
|
5450
|
+
}
|
|
5451
|
+
return h;
|
|
5452
|
+
};
|
|
5453
|
+
const unassignedHandle = hub.player("__unassigned_seat__");
|
|
5454
|
+
const createDynamicSeatHandle = (seatIndex) => {
|
|
5455
|
+
const resolveHandle = () => {
|
|
5456
|
+
const seats = getPlayerSeats?.();
|
|
5457
|
+
if (!seats) return hub.player(seatIndex);
|
|
5458
|
+
const slotId = seats[seatIndex] ?? null;
|
|
5459
|
+
return slotId ? getCachedSlotHandle(slotId) : null;
|
|
5460
|
+
};
|
|
5461
|
+
return {
|
|
5462
|
+
getSlotId: () => resolveHandle()?.getSlotId() ?? null,
|
|
5463
|
+
getCapabilities: () => {
|
|
5464
|
+
const h = resolveHandle();
|
|
5465
|
+
if (h) return h.getCapabilities();
|
|
5466
|
+
return { ...unassignedHandle.getCapabilities(), slotId: null };
|
|
5467
|
+
},
|
|
5468
|
+
input: {
|
|
5469
|
+
getState: () => {
|
|
5470
|
+
const h = resolveHandle();
|
|
5471
|
+
return h ? sanitizeInput(h.input.getState()) : idleDisconnectedState;
|
|
5472
|
+
},
|
|
5473
|
+
applyDeadzone
|
|
5474
|
+
},
|
|
5475
|
+
triggers: {
|
|
5476
|
+
reset: () => resolveHandle()?.triggers.reset(),
|
|
5477
|
+
setLeft: (effect) => resolveHandle()?.triggers.setLeft(effect),
|
|
5478
|
+
setRight: (effect) => resolveHandle()?.triggers.setRight(effect),
|
|
5479
|
+
setBoth: (left, right) => resolveHandle()?.triggers.setBoth(left, right),
|
|
5480
|
+
applyPreset: (presetId, side) => resolveHandle()?.triggers.applyPreset(presetId, side),
|
|
5481
|
+
pulseImpulse: (spec) => resolveHandle()?.triggers.pulseImpulse(spec)
|
|
5482
|
+
},
|
|
5483
|
+
haptics: {
|
|
5484
|
+
pulse: (spec) => resolveHandle()?.haptics.pulse(spec),
|
|
5485
|
+
sweep: (spec) => resolveHandle()?.haptics.sweep(spec),
|
|
5486
|
+
rumble: (o) => resolveHandle()?.haptics.rumble(o),
|
|
5487
|
+
hdRumble: (spec) => resolveHandle()?.haptics.hdRumble(spec),
|
|
5488
|
+
hdSequence: (steps) => resolveHandle()?.haptics.hdSequence(steps),
|
|
5489
|
+
playPreset: (presetId, o) => resolveHandle()?.haptics.playPreset(presetId, o),
|
|
5490
|
+
createContinuous: (preset) => resolveHandle()?.haptics.createContinuous(preset) ?? NOOP_CONTINUOUS_HANDLE,
|
|
5491
|
+
playComboPreset: (presetId, pan) => resolveHandle()?.haptics.playComboPreset(presetId, pan),
|
|
5492
|
+
stop: () => resolveHandle()?.haptics.stop()
|
|
5493
|
+
},
|
|
5494
|
+
audio: {
|
|
5495
|
+
playPcTone: (spec) => resolveHandle()?.audio.playPcTone(spec),
|
|
5496
|
+
playPcNoise: (o) => resolveHandle()?.audio.playPcNoise(o),
|
|
5497
|
+
playControllerSpeakerTone: (spec) => resolveHandle()?.audio.playControllerSpeakerTone(spec),
|
|
5498
|
+
loadSample: (id, source) => active.audio.loadSample(id, source),
|
|
5499
|
+
hasSample: (id) => active.audio.hasSample(id),
|
|
5500
|
+
unloadSample: (id) => active.audio.unloadSample(id),
|
|
5501
|
+
playSample: (id, o) => resolveHandle()?.audio.playSample(id, o) ?? NOOP_SAMPLE_HANDLE
|
|
5502
|
+
},
|
|
5503
|
+
lightbar: {
|
|
5504
|
+
setColor: (r, g, b) => resolveHandle()?.lightbar.setColor(r, g, b),
|
|
5505
|
+
flash: (r, g, b, durationMs) => resolveHandle()?.lightbar.flash(r, g, b, durationMs)
|
|
5506
|
+
},
|
|
5507
|
+
createActions: (spec) => (resolveHandle() ?? active).createActions(spec)
|
|
5508
|
+
};
|
|
5509
|
+
};
|
|
5510
|
+
const capListeners = /* @__PURE__ */ new Set();
|
|
5511
|
+
const micSensors = /* @__PURE__ */ new Set();
|
|
5512
|
+
const sdk = {
|
|
5513
|
+
gameId,
|
|
5514
|
+
locale,
|
|
5515
|
+
showcase: opts.showcase,
|
|
5516
|
+
getCapabilities: () => active.getCapabilities(),
|
|
5517
|
+
onCapabilitiesChange: (listener) => {
|
|
5518
|
+
capListeners.add(listener);
|
|
5519
|
+
const unsubHub = hub.onCapabilitiesChange(listener);
|
|
5520
|
+
return () => {
|
|
5521
|
+
capListeners.delete(listener);
|
|
5522
|
+
unsubHub();
|
|
5523
|
+
};
|
|
5524
|
+
},
|
|
5525
|
+
players: {
|
|
5526
|
+
getSlots: () => hub.getSlots(),
|
|
5527
|
+
get: (indexOrSlotId) => {
|
|
5528
|
+
if (typeof indexOrSlotId === "number" && getPlayerSeats) {
|
|
5529
|
+
return createDynamicSeatHandle(indexOrSlotId);
|
|
5530
|
+
}
|
|
5531
|
+
return typeof indexOrSlotId === "string" ? getCachedSlotHandle(indexOrSlotId) : hub.player(indexOrSlotId);
|
|
5532
|
+
}
|
|
5533
|
+
},
|
|
5534
|
+
input: {
|
|
5535
|
+
getState: () => sanitizeInput(active.input.getState()),
|
|
5536
|
+
applyDeadzone: active.input.applyDeadzone
|
|
5537
|
+
},
|
|
5538
|
+
triggers: active.triggers,
|
|
5539
|
+
haptics: active.haptics,
|
|
5540
|
+
audio: active.audio,
|
|
5541
|
+
lightbar: active.lightbar,
|
|
5542
|
+
createActions: (spec) => active.createActions(spec),
|
|
5543
|
+
createMicBlowSensor: (o) => {
|
|
5544
|
+
const sensor = createMicBlowSensor(o);
|
|
5545
|
+
micSensors.add(sensor);
|
|
5546
|
+
return {
|
|
5547
|
+
start: () => sensor.start(),
|
|
5548
|
+
sample: (nowMs) => sensor.sample(nowMs),
|
|
5549
|
+
getState: () => sensor.getState(),
|
|
5550
|
+
stop: () => sensor.stop(),
|
|
5551
|
+
dispose: () => {
|
|
5552
|
+
micSensors.delete(sensor);
|
|
5553
|
+
sensor.dispose();
|
|
5554
|
+
}
|
|
5555
|
+
};
|
|
5556
|
+
},
|
|
5557
|
+
storage: opts.storage ?? createLocalBestScoreStorage(`${opts.storageKeyPrefix ?? "gamepadly:best:"}${gameId}`)
|
|
5558
|
+
};
|
|
5559
|
+
let disposed = false;
|
|
5560
|
+
return {
|
|
5561
|
+
sdk,
|
|
5562
|
+
hub,
|
|
5563
|
+
notifyPlayerSeatsChanged: () => {
|
|
5564
|
+
if (disposed) return;
|
|
5565
|
+
const event = {
|
|
5566
|
+
slots: hub.getSlots(),
|
|
5567
|
+
active: active.getCapabilities()
|
|
5568
|
+
};
|
|
5569
|
+
for (const fn of capListeners) {
|
|
5570
|
+
try {
|
|
5571
|
+
fn(event);
|
|
5572
|
+
} catch {
|
|
5573
|
+
}
|
|
5574
|
+
}
|
|
5575
|
+
},
|
|
5576
|
+
dispose: () => {
|
|
5577
|
+
if (disposed) return;
|
|
5578
|
+
disposed = true;
|
|
5579
|
+
for (const m of micSensors) {
|
|
5580
|
+
try {
|
|
5581
|
+
m.dispose();
|
|
5582
|
+
} catch {
|
|
5583
|
+
}
|
|
5584
|
+
}
|
|
5585
|
+
micSensors.clear();
|
|
5586
|
+
capListeners.clear();
|
|
5587
|
+
slotHandleCache.clear();
|
|
5588
|
+
hub.dispose();
|
|
5589
|
+
}
|
|
5590
|
+
};
|
|
5591
|
+
}
|
|
5592
|
+
|
|
5593
|
+
// src/game/mock.ts
|
|
5594
|
+
var ALL_CAPABILITIES = [
|
|
5595
|
+
"standard_input",
|
|
5596
|
+
"analog_triggers",
|
|
5597
|
+
"dual_motor_rumble",
|
|
5598
|
+
"impulse_triggers",
|
|
5599
|
+
"hd_rumble",
|
|
5600
|
+
"adaptive_triggers",
|
|
5601
|
+
"audio_haptics",
|
|
5602
|
+
"controller_speaker",
|
|
5603
|
+
"gyro",
|
|
5604
|
+
"accelerometer",
|
|
5605
|
+
"touchpad",
|
|
5606
|
+
"lightbar",
|
|
5607
|
+
"battery"
|
|
5608
|
+
];
|
|
5609
|
+
var BRAND_PROFILES = {
|
|
5610
|
+
sony: {
|
|
5611
|
+
model: "dualsense",
|
|
5612
|
+
displayName: "DualSense Wireless Controller",
|
|
5613
|
+
tier: "dualsense_full_4ch",
|
|
5614
|
+
caps: [
|
|
5615
|
+
"standard_input",
|
|
5616
|
+
"analog_triggers",
|
|
5617
|
+
"dual_motor_rumble",
|
|
5618
|
+
"adaptive_triggers",
|
|
5619
|
+
"audio_haptics",
|
|
5620
|
+
"controller_speaker",
|
|
5621
|
+
"gyro",
|
|
5622
|
+
"accelerometer",
|
|
5623
|
+
"touchpad",
|
|
5624
|
+
"lightbar",
|
|
5625
|
+
"battery"
|
|
5626
|
+
]
|
|
5627
|
+
},
|
|
5628
|
+
nintendo: {
|
|
5629
|
+
model: "switch_pro",
|
|
5630
|
+
displayName: "Switch Pro Controller",
|
|
5631
|
+
tier: "switch_pro_hid",
|
|
5632
|
+
caps: ["standard_input", "hd_rumble", "gyro", "accelerometer", "battery"]
|
|
5633
|
+
},
|
|
5634
|
+
xbox: {
|
|
5635
|
+
model: "xbox_series",
|
|
5636
|
+
displayName: "Xbox Wireless Controller",
|
|
5637
|
+
tier: "xbox_impulse",
|
|
5638
|
+
caps: ["standard_input", "analog_triggers", "dual_motor_rumble", "impulse_triggers"]
|
|
5639
|
+
},
|
|
5640
|
+
generic: {
|
|
5641
|
+
model: "generic",
|
|
5642
|
+
displayName: "Standard Gamepad",
|
|
5643
|
+
tier: "standard_gamepad",
|
|
5644
|
+
caps: ["standard_input", "analog_triggers", "dual_motor_rumble"]
|
|
5645
|
+
},
|
|
5646
|
+
none: {
|
|
5647
|
+
model: "none",
|
|
5648
|
+
displayName: "Keyboard & Mouse",
|
|
5649
|
+
tier: "keyboard_mouse",
|
|
5650
|
+
caps: []
|
|
5651
|
+
}
|
|
5652
|
+
};
|
|
5653
|
+
function buildCapabilities(slotId, state, tier, ready) {
|
|
5654
|
+
const matrix = {};
|
|
5655
|
+
for (const id of ALL_CAPABILITIES) {
|
|
5656
|
+
matrix[id] = { inherent: ready.has(id), availability: ready.has(id) ? "ready" : "unsupported" };
|
|
5657
|
+
}
|
|
5658
|
+
const has = (cap) => ready.has(cap);
|
|
5659
|
+
return {
|
|
5660
|
+
slotId,
|
|
5661
|
+
tier,
|
|
5662
|
+
identity: state.identity,
|
|
5663
|
+
matrix,
|
|
5664
|
+
has,
|
|
5665
|
+
hasAdaptiveTriggers: has("adaptive_triggers"),
|
|
5666
|
+
hasImpulseTriggers: has("impulse_triggers"),
|
|
5667
|
+
hasHdRumble: has("hd_rumble"),
|
|
5668
|
+
hasDualRumble: has("dual_motor_rumble"),
|
|
5669
|
+
has4ChHaptics: has("audio_haptics"),
|
|
5670
|
+
hasControllerSpeaker: has("controller_speaker"),
|
|
5671
|
+
hasGyro: has("gyro"),
|
|
5672
|
+
hasTouchpad: has("touchpad")
|
|
5673
|
+
};
|
|
5674
|
+
}
|
|
5675
|
+
var noop = () => {
|
|
5676
|
+
};
|
|
5677
|
+
function createMockPlayerHandle(options = {}, index = 0) {
|
|
5678
|
+
const brand = options.brand ?? "generic";
|
|
5679
|
+
const profile = BRAND_PROFILES[brand];
|
|
5680
|
+
const slotId = options.slotId ?? `gp-${index}`;
|
|
5681
|
+
const connected = brand !== "none";
|
|
5682
|
+
const state = createEmptyInput();
|
|
5683
|
+
state.connected = connected;
|
|
5684
|
+
state.source = connected ? "gamepad" : "keyboard_mouse";
|
|
5685
|
+
state.deviceName = options.displayName ?? profile.displayName;
|
|
5686
|
+
state.identity = {
|
|
5687
|
+
...state.identity,
|
|
5688
|
+
brand,
|
|
5689
|
+
model: profile.model,
|
|
5690
|
+
displayName: options.displayName ?? profile.displayName,
|
|
5691
|
+
transport: connected ? "usb" : "disconnected",
|
|
5692
|
+
source: connected ? "gamepad" : "keyboard_mouse"
|
|
5693
|
+
};
|
|
5694
|
+
const ready = new Set(profile.caps);
|
|
5695
|
+
return {
|
|
5696
|
+
state,
|
|
5697
|
+
getSlotId: () => connected ? slotId : null,
|
|
5698
|
+
getCapabilities: () => buildCapabilities(connected ? slotId : null, state, profile.tier, ready),
|
|
5699
|
+
input: {
|
|
5700
|
+
getState: () => state,
|
|
5701
|
+
applyDeadzone
|
|
5702
|
+
},
|
|
5703
|
+
triggers: {
|
|
5704
|
+
reset: noop,
|
|
5705
|
+
setLeft: noop,
|
|
5706
|
+
setRight: noop,
|
|
5707
|
+
setBoth: noop,
|
|
5708
|
+
applyPreset: noop,
|
|
5709
|
+
pulseImpulse: noop
|
|
5710
|
+
},
|
|
5711
|
+
haptics: {
|
|
5712
|
+
pulse: noop,
|
|
5713
|
+
sweep: noop,
|
|
5714
|
+
rumble: noop,
|
|
5715
|
+
hdRumble: noop,
|
|
5716
|
+
hdSequence: noop,
|
|
5717
|
+
playPreset: noop,
|
|
5718
|
+
createContinuous: () => ({ update: noop, stop: noop }),
|
|
5719
|
+
playComboPreset: noop,
|
|
5720
|
+
stop: noop
|
|
5721
|
+
},
|
|
5722
|
+
audio: {
|
|
5723
|
+
playPcTone: noop,
|
|
5724
|
+
playPcNoise: noop,
|
|
5725
|
+
playControllerSpeakerTone: noop,
|
|
5726
|
+
loadSample: async () => false,
|
|
5727
|
+
hasSample: () => false,
|
|
5728
|
+
unloadSample: noop,
|
|
5729
|
+
playSample: () => NOOP_SAMPLE_HANDLE
|
|
5730
|
+
},
|
|
5731
|
+
lightbar: {
|
|
5732
|
+
setColor: noop,
|
|
5733
|
+
flash: noop
|
|
5734
|
+
},
|
|
5735
|
+
createActions: (spec) => createActionTracker(spec)
|
|
5736
|
+
};
|
|
5737
|
+
}
|
|
5738
|
+
var IDLE_MIC_STATE = {
|
|
5739
|
+
status: "idle",
|
|
5740
|
+
intensity: 0,
|
|
5741
|
+
blowing: false,
|
|
5742
|
+
sustainedMs: 0,
|
|
5743
|
+
peakIntensity: 0,
|
|
5744
|
+
rms: 0,
|
|
5745
|
+
flatness: 0,
|
|
5746
|
+
deviceLabel: "",
|
|
5747
|
+
usingControllerMic: false
|
|
5748
|
+
};
|
|
5749
|
+
function createIdleMicSensor() {
|
|
5750
|
+
return {
|
|
5751
|
+
start: async () => false,
|
|
5752
|
+
stop: noop,
|
|
5753
|
+
sample: () => ({ ...IDLE_MIC_STATE }),
|
|
5754
|
+
getState: () => ({ ...IDLE_MIC_STATE }),
|
|
5755
|
+
dispose: noop
|
|
5756
|
+
};
|
|
5757
|
+
}
|
|
5758
|
+
function createMockGameSDK(options) {
|
|
5759
|
+
const playerOptions = options.players ?? [{}];
|
|
5760
|
+
const mockPlayers = playerOptions.map((p, i) => createMockPlayerHandle(p, i));
|
|
5761
|
+
const keyboard = createMockPlayerHandle({ brand: "none", slotId: "__keyboard__" });
|
|
5762
|
+
const p1 = mockPlayers[0] ?? keyboard;
|
|
5763
|
+
const slots = mockPlayers.filter((p) => p.state.connected).map((p, i) => ({
|
|
5764
|
+
id: p.getSlotId() ?? `gp-${i}`,
|
|
5765
|
+
playerNumber: i + 1,
|
|
5766
|
+
source: "gamepad",
|
|
5767
|
+
identity: p.state.identity,
|
|
5768
|
+
battery: { percent: 100, charging: false, full: false, known: false },
|
|
5769
|
+
observedReportHz: null,
|
|
5770
|
+
lastActivityAt: 0
|
|
5771
|
+
}));
|
|
5772
|
+
let best = options.bestScore ?? 0;
|
|
5773
|
+
const storage = {
|
|
5774
|
+
getBestScore: () => best,
|
|
5775
|
+
saveBestScore: (score) => {
|
|
5776
|
+
if (score > best) best = Math.round(score);
|
|
5777
|
+
}
|
|
5778
|
+
};
|
|
5779
|
+
return {
|
|
5780
|
+
gameId: options.gameId,
|
|
5781
|
+
locale: options.locale,
|
|
5782
|
+
showcase: options.showcase,
|
|
5783
|
+
mockPlayers,
|
|
5784
|
+
getCapabilities: () => p1.getCapabilities(),
|
|
5785
|
+
onCapabilitiesChange: () => () => {
|
|
5786
|
+
},
|
|
5787
|
+
players: {
|
|
5788
|
+
getSlots: () => slots.map((s) => ({ ...s })),
|
|
5789
|
+
get: (indexOrSlotId) => {
|
|
5790
|
+
if (typeof indexOrSlotId === "number") return mockPlayers[indexOrSlotId] ?? keyboard;
|
|
5791
|
+
return mockPlayers.find((p) => p.getSlotId() === indexOrSlotId) ?? keyboard;
|
|
5792
|
+
}
|
|
5793
|
+
},
|
|
5794
|
+
input: p1.input,
|
|
5795
|
+
triggers: p1.triggers,
|
|
5796
|
+
haptics: p1.haptics,
|
|
5797
|
+
audio: p1.audio,
|
|
5798
|
+
lightbar: p1.lightbar,
|
|
5799
|
+
createActions: (spec) => createActionTracker(spec),
|
|
5800
|
+
createMicBlowSensor: () => createIdleMicSensor(),
|
|
5801
|
+
storage
|
|
5802
|
+
};
|
|
5803
|
+
}
|
|
5804
|
+
|
|
5805
|
+
// src/game/seats.ts
|
|
5806
|
+
function createInitialSeats(slots, maxPlayers) {
|
|
5807
|
+
const count = Math.max(1, maxPlayers);
|
|
5808
|
+
return Array.from({ length: count }, (_, idx) => slots[idx]?.id ?? null);
|
|
5809
|
+
}
|
|
5810
|
+
function reconcileSeats(prevSeats, prevSlots, nextSlots, maxPlayers) {
|
|
5811
|
+
const count = Math.max(1, maxPlayers);
|
|
5812
|
+
if (prevSlots.length === 0) {
|
|
5813
|
+
return createInitialSeats(nextSlots, count);
|
|
5814
|
+
}
|
|
5815
|
+
const nextById = new Map(nextSlots.map((s) => [s.id, s]));
|
|
5816
|
+
const prevById = new Map(prevSlots.map((s) => [s.id, s]));
|
|
5817
|
+
const prevIds = new Set(prevSlots.map((s) => s.id));
|
|
5818
|
+
const seats = Array.from({ length: count }, (_, idx) => prevSeats[idx] ?? null);
|
|
5819
|
+
const usedIds = /* @__PURE__ */ new Set();
|
|
5820
|
+
const vanishedIndices = [];
|
|
5821
|
+
for (let i = 0; i < count; i++) {
|
|
5822
|
+
const id = seats[i];
|
|
5823
|
+
if (!id) continue;
|
|
5824
|
+
if (nextById.has(id) && !usedIds.has(id)) {
|
|
5825
|
+
usedIds.add(id);
|
|
5826
|
+
} else {
|
|
5827
|
+
vanishedIndices.push(i);
|
|
5828
|
+
}
|
|
5829
|
+
}
|
|
5830
|
+
const newCandidates = nextSlots.filter((s) => !prevIds.has(s.id) && !usedIds.has(s.id));
|
|
5831
|
+
for (const seatIdx of vanishedIndices) {
|
|
5832
|
+
const oldId = seats[seatIdx];
|
|
5833
|
+
const oldBrand = oldId ? prevById.get(oldId)?.brand : void 0;
|
|
5834
|
+
const matchIdx = oldBrand ? newCandidates.findIndex((c) => c.brand === oldBrand && !usedIds.has(c.id)) : -1;
|
|
5835
|
+
if (matchIdx >= 0) {
|
|
5836
|
+
const migrated = newCandidates.splice(matchIdx, 1)[0];
|
|
5837
|
+
seats[seatIdx] = migrated.id;
|
|
5838
|
+
usedIds.add(migrated.id);
|
|
5839
|
+
} else {
|
|
5840
|
+
seats[seatIdx] = null;
|
|
5841
|
+
}
|
|
5842
|
+
}
|
|
5843
|
+
for (const candidate of newCandidates) {
|
|
5844
|
+
const emptyIdx = seats.indexOf(null);
|
|
5845
|
+
if (emptyIdx === -1) break;
|
|
5846
|
+
seats[emptyIdx] = candidate.id;
|
|
5847
|
+
usedIds.add(candidate.id);
|
|
5848
|
+
}
|
|
5849
|
+
return seats;
|
|
5850
|
+
}
|
|
5851
|
+
function toggleSeatAssignment(prevSeats, slotId, maxPlayers) {
|
|
5852
|
+
const count = Math.max(1, maxPlayers);
|
|
5853
|
+
const seats = Array.from({ length: count }, (_, idx) => prevSeats[idx] ?? null);
|
|
5854
|
+
const existingIdx = seats.indexOf(slotId);
|
|
5855
|
+
if (existingIdx >= 0) {
|
|
5856
|
+
seats[existingIdx] = null;
|
|
5857
|
+
return seats;
|
|
5858
|
+
}
|
|
5859
|
+
const emptyIdx = seats.indexOf(null);
|
|
5860
|
+
if (emptyIdx >= 0) {
|
|
5861
|
+
seats[emptyIdx] = slotId;
|
|
5862
|
+
return seats;
|
|
5863
|
+
}
|
|
5864
|
+
return [...seats.slice(1), slotId];
|
|
5865
|
+
}
|
|
5866
|
+
|
|
5867
|
+
// src/diagnostics/circularity.ts
|
|
5868
|
+
var CIRCULARITY_SECTORS = 72;
|
|
5869
|
+
var SECTORS = CIRCULARITY_SECTORS;
|
|
5870
|
+
var CIRCULARITY_MIN_RIM_MAGNITUDE = 0.72;
|
|
5871
|
+
var CIRCULARITY_MIN_SECTORS = 12;
|
|
5872
|
+
function createCircularity() {
|
|
5873
|
+
return {
|
|
5874
|
+
sectors: new Float32Array(SECTORS),
|
|
5875
|
+
coveragePct: 0,
|
|
5876
|
+
avgErrorPct: null,
|
|
5877
|
+
maxMag: 0
|
|
5878
|
+
};
|
|
5879
|
+
}
|
|
5880
|
+
function updateCircularity(c, x, y) {
|
|
5881
|
+
const mag = Math.hypot(x, y);
|
|
5882
|
+
if (mag > c.maxMag) c.maxMag = mag;
|
|
5883
|
+
if (mag < CIRCULARITY_MIN_RIM_MAGNITUDE) return;
|
|
5884
|
+
let ang = Math.atan2(y, x);
|
|
5885
|
+
if (ang < 0) ang += Math.PI * 2;
|
|
5886
|
+
const idx = Math.min(SECTORS - 1, Math.floor(ang / (Math.PI * 2) * SECTORS));
|
|
5887
|
+
if (mag > c.sectors[idx]) {
|
|
5888
|
+
c.sectors[idx] = mag;
|
|
5889
|
+
let filled = 0;
|
|
5890
|
+
let errSum = 0;
|
|
5891
|
+
for (let i = 0; i < SECTORS; i++) {
|
|
5892
|
+
if (c.sectors[i] > 0) {
|
|
5893
|
+
filled++;
|
|
5894
|
+
errSum += Math.abs(c.sectors[i] - 1);
|
|
5895
|
+
}
|
|
5896
|
+
}
|
|
5897
|
+
c.coveragePct = Math.round(filled / SECTORS * 100);
|
|
5898
|
+
c.avgErrorPct = filled >= CIRCULARITY_MIN_SECTORS ? Number((errSum / filled * 100).toFixed(1)) : null;
|
|
5899
|
+
}
|
|
5900
|
+
}
|
|
5901
|
+
function buildSectorPath(sectors, cx, cy, radius) {
|
|
5902
|
+
const pts = [];
|
|
5903
|
+
for (let i = 0; i < SECTORS; i++) {
|
|
5904
|
+
const r = sectors[i];
|
|
5905
|
+
if (r <= 0) continue;
|
|
5906
|
+
const ang = (i + 0.5) / SECTORS * Math.PI * 2;
|
|
5907
|
+
const clampedR = Math.min(1.22, r);
|
|
5908
|
+
const px = cx + Math.cos(ang) * radius * clampedR;
|
|
5909
|
+
const py = cy + Math.sin(ang) * radius * clampedR;
|
|
5910
|
+
pts.push(`${pts.length === 0 ? "M" : "L"}${px.toFixed(1)},${py.toFixed(1)}`);
|
|
5911
|
+
}
|
|
5912
|
+
if (pts.length >= 24) pts.push("Z");
|
|
5913
|
+
return pts.join(" ");
|
|
5914
|
+
}
|
|
5915
|
+
|
|
5916
|
+
// src/diagnostics/stick.ts
|
|
5917
|
+
var DEFAULT_DRIFT_THRESHOLDS = Object.freeze({
|
|
5918
|
+
mildOffset: 0.03,
|
|
5919
|
+
driftOffset: 0.08,
|
|
5920
|
+
mildJitter: 0.015,
|
|
5921
|
+
driftJitter: 0.03
|
|
5922
|
+
});
|
|
5923
|
+
function createRestState() {
|
|
5924
|
+
return {
|
|
5925
|
+
inRestSince: null,
|
|
5926
|
+
sessionActive: false,
|
|
5927
|
+
sessionMinX: 0,
|
|
5928
|
+
sessionMaxX: 0,
|
|
5929
|
+
sessionMinY: 0,
|
|
5930
|
+
sessionMaxY: 0,
|
|
5931
|
+
settled: false,
|
|
5932
|
+
peakOffset: 0,
|
|
5933
|
+
peakJitter: 0
|
|
5934
|
+
};
|
|
5935
|
+
}
|
|
5936
|
+
function classifyRestVerdict(settled, peakOffset, peakJitter, thresholds = DEFAULT_DRIFT_THRESHOLDS) {
|
|
5937
|
+
if (!settled) return "waiting";
|
|
5938
|
+
if (peakOffset >= thresholds.driftOffset || peakJitter >= thresholds.driftJitter) return "drift";
|
|
5939
|
+
if (peakOffset >= thresholds.mildOffset || peakJitter >= thresholds.mildJitter) return "mild";
|
|
5940
|
+
return "normal";
|
|
5941
|
+
}
|
|
5942
|
+
var StickDriftTracker = class {
|
|
5943
|
+
left = createRestState();
|
|
5944
|
+
right = createRestState();
|
|
5945
|
+
restMaxMag;
|
|
5946
|
+
settleMs;
|
|
5947
|
+
thresholds;
|
|
5948
|
+
constructor(options = {}) {
|
|
5949
|
+
this.restMaxMag = options.restMaxMagnitude ?? 0.22;
|
|
5950
|
+
this.settleMs = options.settleMs ?? 350;
|
|
5951
|
+
this.thresholds = { ...DEFAULT_DRIFT_THRESHOLDS, ...options.thresholds };
|
|
5952
|
+
}
|
|
5953
|
+
updateAxis(state, x, y, now) {
|
|
5954
|
+
const mag = Math.hypot(x, y);
|
|
5955
|
+
if (mag >= this.restMaxMag) {
|
|
5956
|
+
state.inRestSince = null;
|
|
5957
|
+
state.sessionActive = false;
|
|
5958
|
+
return;
|
|
5959
|
+
}
|
|
5960
|
+
if (state.inRestSince === null) {
|
|
5961
|
+
state.inRestSince = now;
|
|
5962
|
+
state.sessionActive = false;
|
|
5963
|
+
return;
|
|
5964
|
+
}
|
|
5965
|
+
if (now - state.inRestSince < this.settleMs) return;
|
|
5966
|
+
if (!state.sessionActive) {
|
|
5967
|
+
state.sessionActive = true;
|
|
5968
|
+
state.sessionMinX = x;
|
|
5969
|
+
state.sessionMaxX = x;
|
|
5970
|
+
state.sessionMinY = y;
|
|
5971
|
+
state.sessionMaxY = y;
|
|
5972
|
+
} else {
|
|
5973
|
+
if (x < state.sessionMinX) state.sessionMinX = x;
|
|
5974
|
+
if (x > state.sessionMaxX) state.sessionMaxX = x;
|
|
5975
|
+
if (y < state.sessionMinY) state.sessionMinY = y;
|
|
5976
|
+
if (y > state.sessionMaxY) state.sessionMaxY = y;
|
|
5977
|
+
}
|
|
5978
|
+
state.settled = true;
|
|
5979
|
+
if (mag > state.peakOffset) state.peakOffset = mag;
|
|
5980
|
+
const jitter = Math.max(state.sessionMaxX - state.sessionMinX, state.sessionMaxY - state.sessionMinY);
|
|
5981
|
+
if (jitter > state.peakJitter) state.peakJitter = jitter;
|
|
5982
|
+
}
|
|
5983
|
+
update(lx, ly, rx, ry, now) {
|
|
5984
|
+
this.updateAxis(this.left, lx, ly, now);
|
|
5985
|
+
this.updateAxis(this.right, rx, ry, now);
|
|
5986
|
+
}
|
|
5987
|
+
snapshotAxis(state) {
|
|
5988
|
+
const peakOffset = Number(state.peakOffset.toFixed(4));
|
|
5989
|
+
const peakJitter = Number(state.peakJitter.toFixed(4));
|
|
5990
|
+
return {
|
|
5991
|
+
settled: state.settled,
|
|
5992
|
+
peakOffset,
|
|
5993
|
+
peakJitter,
|
|
5994
|
+
verdict: classifyRestVerdict(state.settled, peakOffset, peakJitter, this.thresholds)
|
|
5995
|
+
};
|
|
5996
|
+
}
|
|
5997
|
+
getSnapshot() {
|
|
5998
|
+
return {
|
|
5999
|
+
left: this.snapshotAxis(this.left),
|
|
6000
|
+
right: this.snapshotAxis(this.right)
|
|
6001
|
+
};
|
|
6002
|
+
}
|
|
6003
|
+
reset() {
|
|
6004
|
+
this.left = createRestState();
|
|
6005
|
+
this.right = createRestState();
|
|
6006
|
+
}
|
|
6007
|
+
};
|
|
6008
|
+
var ButtonBounceTracker = class {
|
|
6009
|
+
states = /* @__PURE__ */ new Map();
|
|
6010
|
+
counts = /* @__PURE__ */ new Map();
|
|
6011
|
+
releaseMaxMs;
|
|
6012
|
+
pressIntervalMaxMs;
|
|
6013
|
+
constructor(options = {}) {
|
|
6014
|
+
this.releaseMaxMs = options.releaseMaxMs ?? 55;
|
|
6015
|
+
this.pressIntervalMaxMs = options.pressIntervalMaxMs ?? 90;
|
|
6016
|
+
}
|
|
6017
|
+
update(buttons, now) {
|
|
6018
|
+
for (const [key, pressed] of Object.entries(buttons)) {
|
|
6019
|
+
let timing = this.states.get(key);
|
|
6020
|
+
if (!timing) {
|
|
6021
|
+
timing = { pressed, lastPressAt: pressed ? now : 0, lastReleaseAt: 0 };
|
|
6022
|
+
this.states.set(key, timing);
|
|
6023
|
+
continue;
|
|
6024
|
+
}
|
|
6025
|
+
if (pressed && !timing.pressed) {
|
|
6026
|
+
if (timing.lastReleaseAt > 0 && timing.lastPressAt > 0 && now - timing.lastReleaseAt <= this.releaseMaxMs && now - timing.lastPressAt <= this.pressIntervalMaxMs) {
|
|
6027
|
+
this.counts.set(key, (this.counts.get(key) ?? 0) + 1);
|
|
6028
|
+
}
|
|
6029
|
+
timing.lastPressAt = now;
|
|
6030
|
+
} else if (!pressed && timing.pressed) {
|
|
6031
|
+
timing.lastReleaseAt = now;
|
|
6032
|
+
}
|
|
6033
|
+
timing.pressed = pressed;
|
|
6034
|
+
}
|
|
6035
|
+
}
|
|
6036
|
+
getBouncedButtons() {
|
|
6037
|
+
return Array.from(this.counts.keys());
|
|
6038
|
+
}
|
|
6039
|
+
reset() {
|
|
6040
|
+
this.states.clear();
|
|
6041
|
+
this.counts.clear();
|
|
6042
|
+
}
|
|
6043
|
+
};
|
|
6044
|
+
|
|
6045
|
+
// src/diagnostics/telemetry.ts
|
|
6046
|
+
function createControllerTelemetry(options) {
|
|
6047
|
+
const { source, brandFilter } = options;
|
|
6048
|
+
const setActive = options.setActiveSlot ?? ((id) => void source.setActiveSlot(id));
|
|
6049
|
+
const switcher = new SlotAutoSwitcher();
|
|
6050
|
+
const memory = /* @__PURE__ */ new Map();
|
|
6051
|
+
let latestSamples = [];
|
|
6052
|
+
let activeKey = brandFilter ? `__none_${brandFilter}__` : "__none__";
|
|
6053
|
+
const createDiagnostics = () => ({
|
|
6054
|
+
circularity: { left: createCircularity(), right: createCircularity() },
|
|
6055
|
+
drift: new StickDriftTracker(options.drift),
|
|
6056
|
+
bounce: new ButtonBounceTracker(options.bounce),
|
|
6057
|
+
tested: /* @__PURE__ */ new Set()
|
|
6058
|
+
});
|
|
6059
|
+
const getDiagnostics = (key) => {
|
|
6060
|
+
let d = memory.get(key);
|
|
6061
|
+
if (!d) {
|
|
6062
|
+
d = createDiagnostics();
|
|
6063
|
+
memory.set(key, d);
|
|
6064
|
+
}
|
|
6065
|
+
return d;
|
|
6066
|
+
};
|
|
6067
|
+
return {
|
|
6068
|
+
update(now) {
|
|
6069
|
+
const allSlots = source.getConnectedControllers();
|
|
6070
|
+
const slots = brandFilter ? allSlots.filter((s) => s.identity.brand === brandFilter) : allSlots;
|
|
6071
|
+
const otherSlots = brandFilter ? allSlots.filter((s) => s.identity.brand !== brandFilter) : [];
|
|
6072
|
+
const globalActiveId = source.getActiveSlotId();
|
|
6073
|
+
let activeSlotId = globalActiveId;
|
|
6074
|
+
if (brandFilter) {
|
|
6075
|
+
if (slots.length === 0) {
|
|
6076
|
+
activeSlotId = null;
|
|
6077
|
+
} else if (!globalActiveId || !slots.some((s) => s.id === globalActiveId)) {
|
|
6078
|
+
activeSlotId = slots[0].id;
|
|
6079
|
+
setActive(activeSlotId);
|
|
6080
|
+
}
|
|
6081
|
+
}
|
|
6082
|
+
let triggered = false;
|
|
6083
|
+
if (slots.length > 0) {
|
|
6084
|
+
latestSamples = slots.map((slot) => {
|
|
6085
|
+
const s = source.getInputState(slot.id);
|
|
6086
|
+
return {
|
|
6087
|
+
id: slot.id,
|
|
6088
|
+
lastActivityAt: slot.lastActivityAt,
|
|
6089
|
+
lx: s.lx,
|
|
6090
|
+
ly: s.ly,
|
|
6091
|
+
rx: s.rx,
|
|
6092
|
+
ry: s.ry,
|
|
6093
|
+
l2: s.l2,
|
|
6094
|
+
r2: s.r2
|
|
6095
|
+
};
|
|
6096
|
+
});
|
|
6097
|
+
const { switchTo, triggeredSlotId } = switcher.evaluate(latestSamples, activeSlotId, now);
|
|
6098
|
+
if (switchTo && switchTo !== activeSlotId) {
|
|
6099
|
+
activeSlotId = switchTo;
|
|
6100
|
+
setActive(switchTo);
|
|
6101
|
+
}
|
|
6102
|
+
triggered = triggeredSlotId !== null;
|
|
6103
|
+
} else {
|
|
6104
|
+
latestSamples = [];
|
|
6105
|
+
}
|
|
6106
|
+
const slotKey = activeSlotId ?? (brandFilter ? `__none_${brandFilter}__` : "__none__");
|
|
6107
|
+
activeKey = slotKey;
|
|
6108
|
+
const diagnostics = getDiagnostics(slotKey);
|
|
6109
|
+
const input = activeSlotId ? source.getInputState(activeSlotId) : brandFilter ? createEmptyInput() : source.getInputState();
|
|
6110
|
+
if (input.connected) {
|
|
6111
|
+
updateCircularity(diagnostics.circularity.left, input.lx, input.ly);
|
|
6112
|
+
updateCircularity(diagnostics.circularity.right, input.rx, input.ry);
|
|
6113
|
+
diagnostics.drift.update(input.lx, input.ly, input.rx, input.ry, now);
|
|
6114
|
+
diagnostics.bounce.update(input.buttons, now);
|
|
6115
|
+
for (const [btn, pressed] of Object.entries(input.buttons)) {
|
|
6116
|
+
if (pressed) diagnostics.tested.add(btn);
|
|
6117
|
+
}
|
|
6118
|
+
}
|
|
6119
|
+
return { now, slots, otherSlots, activeSlotId, slotKey, input, triggered, diagnostics };
|
|
6120
|
+
},
|
|
6121
|
+
selectSlot(slotId, now) {
|
|
6122
|
+
switcher.notifyManualSelect(latestSamples, now);
|
|
6123
|
+
setActive(slotId);
|
|
6124
|
+
},
|
|
6125
|
+
resetActive() {
|
|
6126
|
+
memory.set(activeKey, createDiagnostics());
|
|
6127
|
+
},
|
|
6128
|
+
getDiagnostics
|
|
6129
|
+
};
|
|
3584
6130
|
}
|
|
3585
6131
|
|
|
3586
6132
|
// src/bridge/profiles.ts
|
|
@@ -4206,29 +6752,69 @@ function createGameLoop(options) {
|
|
|
4206
6752
|
}
|
|
4207
6753
|
export {
|
|
4208
6754
|
BUILTIN_BRIDGE_PROFILES,
|
|
6755
|
+
ButtonBounceTracker,
|
|
6756
|
+
CIRCULARITY_MIN_RIM_MAGNITUDE,
|
|
6757
|
+
CIRCULARITY_MIN_SECTORS,
|
|
6758
|
+
CIRCULARITY_SECTORS,
|
|
4209
6759
|
COMPANION_HTTP_BASE,
|
|
4210
6760
|
COMPANION_WS_BASE,
|
|
6761
|
+
CONTROLLER_MIC_RE,
|
|
4211
6762
|
DualSenseControllerManager as ControllerManager,
|
|
6763
|
+
DEFAULT_DRIFT_THRESHOLDS,
|
|
4212
6764
|
DualSenseControllerManager,
|
|
6765
|
+
LINK_PROTOCOL_START_URI,
|
|
6766
|
+
NOOP_SAMPLE_HANDLE,
|
|
6767
|
+
SlotAutoSwitcher,
|
|
6768
|
+
StickDriftTracker,
|
|
4213
6769
|
TACTILE_PRESETS,
|
|
4214
6770
|
TRIGGER_PRESETS,
|
|
4215
6771
|
ThreeLayerAudioEngine,
|
|
6772
|
+
TriggerFeedbackController,
|
|
6773
|
+
analyzeBlowSpectrum,
|
|
4216
6774
|
applyDeadzone,
|
|
6775
|
+
attachControllerLifecycle,
|
|
6776
|
+
buildSectorPath,
|
|
4217
6777
|
buildSwitchHdFromPulse,
|
|
6778
|
+
classifyRestVerdict,
|
|
6779
|
+
connectDualSenseViaBrowser,
|
|
6780
|
+
connectDualSenseViaCompanion,
|
|
4218
6781
|
crc32WithSeed,
|
|
4219
6782
|
createActionTracker,
|
|
4220
6783
|
createCanvasStage,
|
|
6784
|
+
createCircularity,
|
|
6785
|
+
createControllerTelemetry,
|
|
4221
6786
|
createDisposables,
|
|
4222
6787
|
createEmptyInput,
|
|
6788
|
+
createGameHost,
|
|
4223
6789
|
createGameLoop,
|
|
4224
6790
|
createGamepadly,
|
|
6791
|
+
createInitialSeats,
|
|
4225
6792
|
createKeyMouseBridge,
|
|
4226
6793
|
createLinkAudio,
|
|
6794
|
+
createLocalBestScoreStorage,
|
|
6795
|
+
createMicBlowSensor,
|
|
6796
|
+
createMicLevelMeter,
|
|
6797
|
+
createMockGameSDK,
|
|
6798
|
+
createMockPlayerHandle,
|
|
6799
|
+
createMotionTracker,
|
|
6800
|
+
createPcAudioRouting,
|
|
6801
|
+
createSampleBank,
|
|
6802
|
+
createTactileBuffer,
|
|
6803
|
+
createTouchpadGestures,
|
|
6804
|
+
defineGame,
|
|
4227
6805
|
encodeSwitchHdRumbleSide,
|
|
4228
6806
|
encodeTriggerEffect,
|
|
4229
6807
|
identifyGamepadFromId,
|
|
6808
|
+
isMicInputSupported,
|
|
6809
|
+
launchLinkViaProtocol,
|
|
6810
|
+
openMicInput,
|
|
6811
|
+
reconcileSeats,
|
|
4230
6812
|
routeHapticPulse,
|
|
4231
6813
|
routeHapticSweep,
|
|
4232
|
-
routeTactilePreset
|
|
6814
|
+
routeTactilePreset,
|
|
6815
|
+
shouldAutoLaunchLink,
|
|
6816
|
+
timeDomainRms,
|
|
6817
|
+
toggleSeatAssignment,
|
|
6818
|
+
updateCircularity
|
|
4233
6819
|
};
|
|
4234
6820
|
//# sourceMappingURL=browser.js.map
|