Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions native/common/hook_protocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
namespace inputsplit::proto {

constexpr uint32_t kMagic = 0x4C505349; // "ISPL" in little-endian
constexpr uint16_t kProtocolVersion = 4; // 2: DirectInput / Raw Input counters, 3: frame stats,
// 4: tuning (dead zones, button remapping)
constexpr uint16_t kProtocolVersion = 5; // 2: DirectInput / Raw Input counters, 3: frame stats,
// 4: tuning (dead zones, button remapping),
// 5: player order in tuning

// Pipe name prefix; the game PID (decimal) is appended.
constexpr wchar_t kPipePrefix[] = L"\\\\.\\pipe\\InputSplit.Hook.";
Expand Down Expand Up @@ -115,7 +116,10 @@ struct TuningMessage {
// For each XInput button bit i (XINPUT_GAMEPAD_* == 1 << i): the bit the game sees
// instead, or kButtonOff to hide the button.
uint8_t buttonMap[16];
uint32_t reserved2[2];
// Without slot lock (the game reads every controller): the physical slot behind the
// game's player 1..4. Identity (0, 1, 2, 3) = Windows' own order.
uint8_t playerSlots[4];
uint32_t reserved2;
};
constexpr uint8_t kButtonOff = 0xFF;

Expand Down
7 changes: 7 additions & 0 deletions native/helper/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,13 @@ Json Handle(const std::string& method, const Json& params) {
tuning.buttonMap[i] = i < static_cast<int>(map.size()) ? map[i].get<uint8_t>()
: static_cast<uint8_t>(i);
}
for (int i = 0; i < 4; ++i) tuning.playerSlots[i] = static_cast<uint8_t>(i);
if (params.contains("playerSlots")) {
const Json& slots = params["playerSlots"];
for (int i = 0; i < 4 && i < static_cast<int>(slots.size()); ++i) {
tuning.playerSlots[i] = slots[i].get<uint8_t>();
}
}
if (!SessionManager::Instance().SetTuning(params.at("sessionId").get<int>(), tuning)) {
throw HelperError{"sessionNotFound", "No such session."};
}
Expand Down
2 changes: 2 additions & 0 deletions native/hook/modules.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ void FillFrameStats(proto::StatusMessage& status);
void SetTuning(const proto::TuningMessage& tuning);
void ClearTuning();
void ApplyTuning(XINPUT_STATE* state); // no-op unless a tuning is set
// The physical slot for the game's user index when a player order is set; false otherwise.
bool PlayerOrderSlot(DWORD userIndex, DWORD& physical);

// detection.cpp
uint32_t DetectApis(); // proto::DetectedApi bits
Expand Down
25 changes: 24 additions & 1 deletion native/hook/tuning.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ std::atomic<int> g_leftDeadzone{0};
std::atomic<int> g_rightDeadzone{0};
std::atomic<int> g_triggerDeadzone{0};
std::atomic<uint8_t> g_buttonMap[16];
std::atomic<bool> g_orderEnabled{false};
std::atomic<uint8_t> g_playerSlots[4];

constexpr double kStickMax = 32767.0;

Expand Down Expand Up @@ -69,11 +71,32 @@ void SetTuning(const proto::TuningMessage& tuning) {
g_triggerDeadzone.store(trigger, std::memory_order_relaxed);
const bool enabled = !identity || left > 0 || right > 0 || trigger > 0;
g_enabled.store(enabled, std::memory_order_release);
bool order = false;
for (int i = 0; i < 4; ++i) {
uint8_t slot = tuning.playerSlots[i];
if (slot > 3) slot = static_cast<uint8_t>(i);
g_playerSlots[i].store(slot, std::memory_order_relaxed);
order = order || slot != i;
}
g_orderEnabled.store(order, std::memory_order_release);
if (order) {
Log(LogLevel::Info, "Player order: slots %u %u %u %u", tuning.playerSlots[0] + 1u,
tuning.playerSlots[1] + 1u, tuning.playerSlots[2] + 1u, tuning.playerSlots[3] + 1u);
}
Log(LogLevel::Info, "Tuning %s: dead zones L=%d R=%d triggers=%d, buttons %s",
enabled ? "on" : "off", left, right, trigger, identity ? "unchanged" : "remapped");
}

void ClearTuning() { g_enabled.store(false, std::memory_order_release); }
void ClearTuning() {
g_enabled.store(false, std::memory_order_release);
g_orderEnabled.store(false, std::memory_order_release);
}

bool PlayerOrderSlot(DWORD userIndex, DWORD& physical) {
if (userIndex > 3 || !g_orderEnabled.load(std::memory_order_acquire)) return false;
physical = g_playerSlots[userIndex].load(std::memory_order_relaxed);
return true;
}

void ApplyTuning(XINPUT_STATE* state) {
if (state == nullptr || !g_enabled.load(std::memory_order_acquire)) return;
Expand Down
4 changes: 2 additions & 2 deletions native/hook/xinput_bridge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ std::atomic<bool> g_gameWantsEnabled{true}; // last value the game passed to XI
// "no controller" for this index.
bool MapUserIndex(DWORD userIndex, DWORD& physical) {
if (!IsActive(proto::kFeatureXInputSlotLock)) {
physical = userIndex;
if (!PlayerOrderSlot(userIndex, physical)) physical = userIndex;
return true;
}
DWORD slot = g_xinputSlot.load(std::memory_order_relaxed);
Expand Down Expand Up @@ -117,7 +117,7 @@ DWORD WINAPI DetourGetKeystroke(DWORD userIndex, DWORD reserved, XINPUT_KEYSTROK
DWORD result = g_real.getKeystroke(physical, reserved, keystroke);
// Report the index the game asked for, not the physical slot.
if (result == ERROR_SUCCESS && keystroke != nullptr && userIndex != kUserIndexAny &&
IsActive(proto::kFeatureXInputSlotLock)) {
physical != userIndex) {
keystroke->UserIndex = static_cast<BYTE>(userIndex);
}
return result;
Expand Down
1 change: 1 addition & 0 deletions src/main/native/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export const helperMethods = {
rightDeadzone: z.number().int(),
triggerDeadzone: z.number().int(),
buttonMap: z.array(z.number().int()),
playerSlots: z.array(z.number().int()).optional(),
}),
result: empty,
},
Expand Down
34 changes: 32 additions & 2 deletions src/renderer/src/components/ControllerTuningCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { GAMEPAD_BUTTONS, type GamepadButton } from '@shared/defaults'
import type { GamepadTuning } from '@shared/domain'
import { isDefaultTuning, stickPercent } from '@shared/tuning'
import { isDefaultTuning, stickPercent, withPlayerSlot } from '@shared/tuning'
import { useDevicesStore } from '../stores/devices'
import { useSettingsStore } from '../stores/settings'
import UiButton from './ui/UiButton.vue'
Expand Down Expand Up @@ -82,8 +82,21 @@ function swapAB(): void {
save({ remap })
}

const slotOptions = computed(() =>
[0, 1, 2, 3].map((slot) => ({ value: slot, label: t('common.slot', { n: slot + 1 }) })),
)
function setPlayerSlot(player: number, slot: number): void {
save({ playerOrder: withPlayerSlot(tuning.value.playerOrder, player, slot) })
}

function reset(): void {
save({ leftDeadzone: 0, rightDeadzone: 0, triggerDeadzone: 0, remap: {} })
save({
leftDeadzone: 0,
rightDeadzone: 0,
triggerDeadzone: 0,
remap: {},
playerOrder: [0, 1, 2, 3],
})
}
</script>

Expand Down Expand Up @@ -141,5 +154,22 @@ function reset(): void {
/>
</div>
</div>

<p class="mt-5 text-[13px] font-medium text-text">{{ $t('controllers.tuning.order') }}</p>
<p class="mt-0.5 text-[12px] text-text-muted">{{ $t('controllers.tuning.orderHint') }}</p>
<div class="mt-2 grid grid-cols-2 gap-x-4 gap-y-2 md:grid-cols-4">
<div v-for="player in [0, 1, 2, 3]" :key="player" class="flex flex-col gap-1">
<span class="text-[12px] text-text-muted">{{
$t('controllers.tuning.player', { n: player + 1 })
}}</span>
<UiSelect
:key="`${player}-${tuning.playerOrder.join()}`"
:model-value="tuning.playerOrder[player] ?? player"
:options="slotOptions"
:label="$t('controllers.tuning.player', { n: player + 1 })"
@update:model-value="setPlayerSlot(player, $event)"
/>
</div>
</div>
</UiCard>
</template>
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,10 @@ export const de: Messages = {
swapAB: 'A und B tauschen',
off: 'Aus',
dpad: 'Steuerkreuz',
order: 'Spielerreihenfolge',
orderHint:
'Für Spiele, die alle Controller lesen (kein Controller für das Spiel gewählt): welcher Platz als Spieler 1, 2, 3 und 4 spielt.',
player: 'Spieler {n}',
},
doubled: 'Kann in Spielen doppelt reagieren',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,10 @@ export const en = {
swapAB: 'Swap A and B',
off: 'Off',
dpad: 'D-pad',
order: 'Player order',
orderHint:
'For games that read every controller (no controller chosen for the game): which slot plays as player 1, 2, 3 and 4.',
player: 'Player {n}',
},
doubled: 'May respond twice in games',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,10 @@ export const es: Messages = {
swapAB: 'Intercambiar A y B',
off: 'Desactivado',
dpad: 'Cruceta',
order: 'Orden de jugadores',
orderHint:
'Para juegos que leen todos los mandos (sin mando elegido para el juego): qué ranura juega como jugador 1, 2, 3 y 4.',
player: 'Jugador {n}',
},
doubled: 'Puede responder dos veces en los juegos',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,10 @@ export const fr: Messages = {
swapAB: 'Inverser A et B',
off: 'Désactivé',
dpad: 'Croix directionnelle',
order: 'Ordre des joueurs',
orderHint:
'Pour les jeux qui lisent toutes les manettes (aucune manette choisie pour le jeu) : quel emplacement joue en tant que joueur 1, 2, 3 et 4.',
player: 'Joueur {n}',
},
doubled: 'Peut réagir deux fois dans les jeux',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,10 @@ export const ja: Messages = {
swapAB: 'A と B を入れ替える',
off: 'オフ',
dpad: '十字キー',
order: 'プレイヤーの順番',
orderHint:
'すべてのコントローラーを読むゲーム(ゲーム用のコントローラーを選んでいない場合)で、どのスロットがプレイヤー 1・2・3・4 になるか。',
player: 'プレイヤー {n}',
},
doubled: 'ゲームで二重に反応することがあります',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,10 @@ export const pl: Messages = {
swapAB: 'Zamień A i B',
off: 'Wyłączony',
dpad: 'Krzyżak',
order: 'Kolejność graczy',
orderHint:
'Dla gier, które czytają wszystkie kontrolery (nie wybrano kontrolera dla gry): które gniazdo gra jako gracz 1, 2, 3 i 4.',
player: 'Gracz {n}',
},
doubled: 'Może reagować podwójnie w grach',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,10 @@ export const ptBR: Messages = {
swapAB: 'Trocar A e B',
off: 'Desligado',
dpad: 'Direcional',
order: 'Ordem dos jogadores',
orderHint:
'Para jogos que leem todos os controles (nenhum controle escolhido para o jogo): qual slot joga como jogador 1, 2, 3 e 4.',
player: 'Jogador {n}',
},
doubled: 'Pode responder duas vezes nos jogos',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,10 @@ export const ru: Messages = {
swapAB: 'Поменять A и B',
off: 'Выключена',
dpad: 'Крестовина',
order: 'Порядок игроков',
orderHint:
'Для игр, которые читают все геймпады (геймпад для игры не выбран): какой слот играет за игрока 1, 2, 3 и 4.',
player: 'Игрок {n}',
},
doubled: 'Может срабатывать дважды',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,10 @@ export const tr: Messages = {
swapAB: "A ile B'yi değiştir",
off: 'Kapalı',
dpad: 'Yön tuşları',
order: 'Oyuncu sırası',
orderHint:
'Tüm kumandaları okuyan oyunlar için (oyuna kumanda seçilmemişse): hangi yuvanın 1, 2, 3 ve 4. oyuncu olarak oynayacağı.',
player: 'Oyuncu {n}',
},
doubled: 'Oyunlarda iki kez tepki verebilir',
tools: {
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/uk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,10 @@ export const uk: Messages = {
swapAB: 'Поміняти A і B',
off: 'Вимкнена',
dpad: 'Хрестовина',
order: 'Порядок гравців',
orderHint:
'Для ігор, що читають усі геймпади (геймпад для гри не вибрано): який слот грає за гравця 1, 2, 3 і 4.',
player: 'Гравець {n}',
},
doubled: 'Може спрацьовувати двічі',
tools: {
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,9 @@ export const zhCN: Messages = {
swapAB: '交换 A 和 B',
off: '关闭',
dpad: '方向键',
order: '玩家顺序',
orderHint: '适用于读取所有手柄的游戏(未为游戏选择手柄):哪个插槽作为玩家 1、2、3、4。',
player: '玩家 {n}',
},
doubled: '在游戏中可能触发两次',
tools: {
Expand Down
8 changes: 7 additions & 1 deletion src/shared/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,13 @@ export const DEFAULT_SETTINGS: Settings = {
antiCheatProtection: true,
gameAudioToDisplay: true,
overlayHotkeyEnabled: true,
gamepadTuning: { leftDeadzone: 0, rightDeadzone: 0, triggerDeadzone: 0, remap: {} },
gamepadTuning: {
leftDeadzone: 0,
rightDeadzone: 0,
triggerDeadzone: 0,
remap: {},
playerOrder: [0, 1, 2, 3],
},
blockGameBarButton: true,
}

Expand Down
6 changes: 6 additions & 0 deletions src/shared/domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,11 @@ export const GamepadTuningSchema = z.object({
rightDeadzone: z.number().int().min(0).max(60),
triggerDeadzone: z.number().int().min(0).max(60),
remap: z.partialRecord(GamepadButtonSchema, z.union([GamepadButtonSchema, z.literal('off')])),
/**
* For games that read every controller (no controller chosen): the slot behind player
* 1..4. [0, 1, 2, 3] keeps Windows' order.
*/
playerOrder: z.array(z.number().int().min(0).max(3)).length(4).default([0, 1, 2, 3]),
})
export type GamepadTuning = z.infer<typeof GamepadTuningSchema>

Expand Down Expand Up @@ -461,6 +466,7 @@ export const SettingsSchema = z.object({
rightDeadzone: 0,
triggerDeadzone: 0,
remap: {},
playerOrder: [0, 1, 2, 3],
}),
blockGameBarButton: ADDED_SETTINGS_FIELDS.blockGameBarButton.default(true),
})
Expand Down
20 changes: 18 additions & 2 deletions src/shared/tuning.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { isDefaultTuning, stickPercent, toHelperTuning } from './tuning'
import { isDefaultTuning, stickPercent, toHelperTuning, withPlayerSlot } from './tuning'

describe('toHelperTuning', () => {
it('turns percents into XInput units and buttons into bit indexes', () => {
Expand All @@ -8,7 +8,9 @@ describe('toHelperTuning', () => {
rightDeadzone: 0,
triggerDeadzone: 20,
remap: { a: 'b', b: 'a', back: 'off' },
playerOrder: [1, 0, 2, 3],
})
expect(tuning.playerSlots).toEqual([1, 0, 2, 3])
expect(tuning.leftDeadzone).toBe(3277)
expect(tuning.triggerDeadzone).toBe(51)
expect(tuning.buttonMap[12]).toBe(13) // A (0x1000) acts as B (0x2000)
Expand All @@ -21,11 +23,18 @@ describe('toHelperTuning', () => {

describe('isDefaultTuning', () => {
it('ignores buttons mapped to themselves', () => {
const base = { leftDeadzone: 0, rightDeadzone: 0, triggerDeadzone: 0, remap: {} }
const base = {
leftDeadzone: 0,
rightDeadzone: 0,
triggerDeadzone: 0,
remap: {},
playerOrder: [0, 1, 2, 3],
}
expect(isDefaultTuning(base)).toBe(true)
expect(isDefaultTuning({ ...base, remap: { a: 'a' } })).toBe(true)
expect(isDefaultTuning({ ...base, remap: { a: 'b' } })).toBe(false)
expect(isDefaultTuning({ ...base, rightDeadzone: 5 })).toBe(false)
expect(isDefaultTuning({ ...base, playerOrder: [1, 0, 2, 3] })).toBe(false)
})
})

Expand All @@ -36,3 +45,10 @@ describe('stickPercent', () => {
expect(stickPercent(-32768, -32768)).toBe(100)
})
})

describe('withPlayerSlot', () => {
it('swaps slots between players', () => {
expect(withPlayerSlot([0, 1, 2, 3], 0, 2)).toEqual([2, 1, 0, 3])
expect(withPlayerSlot([2, 1, 0, 3], 0, 2)).toEqual([2, 1, 0, 3])
})
})
Loading
Loading