The free camera steps through move, lock and off: locked, the view stays and Link walks where the left stick points on screen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lebomisandClaude Opus 5.5 committed 2026-11-19 14:28:13 +11:00
1 parent 58930c152c
commit 5fdacca237
6 files changed
+86 -65

No files matched your search

+21 -18
View File
@@ -21,12 +21,14 @@
// the anchor is driven. When no driven component has been updated for LOST_NS (a load replaced them) the next one
// away from the default anchors again; the free camera keeps its own position.
//
// Input (runtime/input.c freecam_gate): TOTK_FREECAM_PAD or TOTK_FREECAM_KEY switches it (both none by default, so the
// player opts in). While it is on the game gets no input; the left stick flies along the view and to the side, ZR and
// ZL straight up and down, the right stick and the mouse turn, and each press of L or R halves or doubles the speed.
// Keys work through their bindings: the keys' sticks, and the keys bound to ZL, ZR, L and R. Every driven component
// steps the flight by the wall-clock time since the last step, so the speed is the same at any frame rate and game
// speed.
// Input (runtime/input.c freecam_gate): TOTK_FREECAM_PAD or TOTK_FREECAM_KEY steps it off, move, lock and off again
// (both none by default, so the player opts in). While it moves the game gets no input; the left stick flies along the
// view and to the side, ZR and ZL straight up and down, the right stick and the mouse turn, and each press of L or R
// halves or doubles the speed. Keys work through their bindings: the keys' sticks, and the keys bound to ZL, ZR, L and
// R. Every driven component steps the flight by the wall-clock time since the last step, so the speed is the same at
// any frame rate and game speed. Locked, the view stays where the flight left it and the game gets its input back.
// The game steers Link by the camera it draws, which takes the overrides, so Link walks where the stick points on
// screen with the stick as it is.
#include <math.h>
#include <stdint.h>
#include <stdio.h>
@@ -56,11 +58,11 @@ static PlatMutex pad_lock = PLAT_MUTEX_INIT;
static FreecamPad pad_now; // the last poll's input (input thread), under pad_lock
static int speed_clicks; // R presses minus L presses not yet applied (input thread adds, the hook takes)
static double mouse_deg[2]; // under pad_lock: mouse turn not yet applied, degrees (right +, down +)
// + 1 at every switch (input thread); odd while the free camera is on. One value, so the hook never sees a switch
// without the state it switched to.
// + 1 at every switch (input thread); modulo 3 the stage (FREECAM_OFF, _MOVE, _LOCK). One value, so the hook never
// sees a switch without the stage it switched to.
static unsigned generation;
int freecam_on(void) { return __atomic_load_n(&generation, __ATOMIC_ACQUIRE) & 1; }
int freecam_state(void) { return __atomic_load_n(&generation, __ATOMIC_ACQUIRE) % 3; }
void freecam_pad(const FreecamPad *p) {
plat_mutex_lock(&pad_lock);
@@ -88,16 +90,17 @@ enum {
int freecam_available(void) { return rt_game_version == 143 && rt_patch_enabled(rt_patch_set("freecam")); }
void freecam_toggle(void) {
void freecam_cycle(void) {
unsigned gen = __atomic_add_fetch(&generation, 1, __ATOMIC_ACQ_REL);
rt_log("freecam: %s", gen & 1 ? "on" : "off");
static const char *const names[] = {"off", "move", "lock"};
rt_log("freecam: %s", names[gen % 3]);
}
// Game thread only (the camera update runs on one thread). A component stays listed from its first drive until its
// up offset is put back (the first update after the switch goes off) or, while off, until it has gone LOST_NS
// without an update (freed by a load).
static struct {
unsigned generation;
unsigned flight; // (generation + 2) / 3: the same from move through lock, new at the next move
int started; // pos, yaw and pitch hold a pose
double pos[3], yaw, pitch, speed; // radians; yaw 0 looks along +Z, pitch > 0 up
uint64_t last_step, anchor_seen;
@@ -220,10 +223,10 @@ static void freecam_hook(Cpu *c) {
uint64_t cam = c->x[19];
memcpy(&c->x[8], (const void *)(uintptr_t)(cam + OFF_LINK), sizeof c->x[8]);
unsigned gen = __atomic_load_n(&generation, __ATOMIC_ACQUIRE);
int active = gen & 1;
if (!active && !fc.n) return; // the common case: one load and two compares
if (gen != fc.generation) { // a switch: a new flight starts at the game camera, at the start speed
fc.generation = gen;
int state = gen % 3, active = state != FREECAM_OFF;
if (!active && !fc.n) return; // the common case: one load, a division and two compares
if ((gen + 2) / 3 != fc.flight) { // a new flight starts at the game camera, at the start speed
fc.flight = (gen + 2) / 3;
fc.started = 0, fc.anchored = 0, fc.speed = SPEED_START;
plat_mutex_lock(&pad_lock); // mouse motion from before the switch does not turn the new flight
mouse_deg[0] = mouse_deg[1] = 0;
@@ -248,7 +251,7 @@ static void freecam_hook(Cpu *c) {
if (i < 0 && (i = pick(cam, eye, target)) < 0) return;
if (!fc.started) start(eye, target, now);
fc.driven[i].seen = fc.anchor_seen = now;
step(now);
if (state == FREECAM_MOVE) step(now); // locked, the view holds its pose
drive(cam);
}
@@ -257,5 +260,5 @@ __attribute__((constructor)) static void freecam_register(void) {
}
#else
int freecam_available(void) { return 0; }
void freecam_toggle(void) {}
void freecam_cycle(void) {}
#endif
+13 -11
View File
@@ -271,7 +271,8 @@ static void rec_apply(uint64_t b, const int32_t sl[2], const int32_t sr[2]) {
void input_direct_mouse_sample(int enabled, int32_t *dx, int32_t *dy) {
plat_mutex_lock(&lock);
enabled = enabled && !g_block && !g_menu && !freecam_on(); // the free camera takes the mouse (freecam_gate)
// the moving free camera takes the mouse (freecam_gate)
enabled = enabled && !g_block && !g_menu && freecam_state() != FREECAM_MOVE;
*dx = script_mouse[0]; *dy = script_mouse[1];
script_mouse[0] = script_mouse[1] = 0;
if (!enabled) { *dx = *dy = 0; }
@@ -854,12 +855,13 @@ static float trigger_unit(int16_t v) { // 0..1 past a 5 % dead zone
}
// The free camera combo, latched like Minus+Plus (input_map.c, chord): once every button of it is down (on the gamepad,
// or pressed by an input script) the free camera switches once, and the buttons stay hidden from the game until all are
// released; the free camera key switches it on its press. While the free camera is on it gets the input and the game
// gets nothing, so Link stands still: the sticks (the keys' sticks merged into sl and sr), the trigger axes or else ZL
// and ZR as buttons, a press of L or R as a speed click, and the mouse's motion, which input_direct_mouse_sample then
// keeps from the game's camera. ZL, ZR, L and R are the merged Switch buttons, so the keys bound to them count. Off for
// other updates and with the freecam patch set off. Under lock.
// or pressed by an input script) the free camera steps once (off, move, lock), and the buttons stay hidden from the
// game until all are released; the free camera key steps it on its press. While the free camera moves it gets the
// input and the game gets nothing, so Link stands still: the sticks (the keys' sticks merged into sl and sr), the
// trigger axes or else ZL and ZR as buttons, a press of L or R as a speed click, and the mouse's motion, which
// input_direct_mouse_sample then keeps from the game's camera. ZL, ZR, L and R are the merged Switch buttons, so the
// keys bound to them count. Locked, the game gets the input as it is (freecam.c: the game steers Link by the camera it
// draws). Off for other updates and with the freecam patch set off. Under lock.
static void freecam_gate(uint64_t *b, int32_t sl[2], int32_t sr[2]) {
static int held, key_held, available = -1, shoulder[2];
if (available < 0) available = freecam_available();
@@ -878,13 +880,13 @@ static void freecam_gate(uint64_t *b, int32_t sl[2], int32_t sr[2]) {
else if (held) held = raw != 0;
else if (raw == mask) {
held = 1;
freecam_toggle();
freecam_cycle();
}
int key = available ? freecam_key() : KEY_NONE;
int key_down = key != KEY_NONE && ikb_foreground() && ikb_down(key);
if (key_down && !key_held) freecam_toggle();
if (key_down && !key_held) freecam_cycle();
key_held = key_down;
if (available && freecam_on()) {
if (available && freecam_state() == FREECAM_MOVE) {
float lt = trigger_unit(trigger_seen[0]), rt = trigger_unit(trigger_seen[1]);
if (*b >> B_ZL & 1) lt = 1;
if (*b >> B_ZR & 1) rt = 1;
@@ -1035,7 +1037,7 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
static int overlay_held; // L3+R3 step the performance overlay (F10)
int overlay = input_overlay_gate(&overlay_held, &b);
sl[0] = st[0], sl[1] = st[1], sr[0] = st[2], sr[1] = st[3];
freecam_gate(&b, sl, sr); // TOTK_FREECAM_PAD switches the free camera, which then takes the pad (freecam.c)
freecam_gate(&b, sl, sr); // TOTK_FREECAM_PAD steps the free camera, which takes the pad while moving (freecam.c)
plat_mutex_unlock(&lock);
if (toggle) menu_toggle();
if (overlay) menu_perf_cycle();
+6 -4
View File
@@ -99,12 +99,14 @@ int input_pad_read(uint64_t *buttons, int32_t *lx, int32_t *ly);
// The gamepad layout in effect (PAD_LAYOUT_*, input_map.h; TOTK_PAD_LAYOUT, live); -1 without a gamepad. Any thread.
int input_pad_layout(void);
// Free camera (freecam.c). input.c switches it with TOTK_FREECAM_PAD and, while it is on, hands it the gamepad and
// gives the game none: sticks -1..1 with up +y after the dead zone, triggers 0..1; each L or R press is one speed click.
// Free camera (freecam.c). input.c steps it with TOTK_FREECAM_PAD and, while it moves, hands it the gamepad and gives
// the game none: sticks -1..1 with up +y after the dead zone, triggers 0..1; each L or R press is one speed click.
// Locked, the view stays and the game gets the input.
typedef struct { float lx, ly, rx, ry, lt, rt; } FreecamPad;
enum { FREECAM_OFF, FREECAM_MOVE, FREECAM_LOCK };
int freecam_available(void); // game 1.4.3 with the freecam patch set on
int freecam_on(void);
void freecam_toggle(void); // logs; input thread
int freecam_state(void); // FREECAM_*
void freecam_cycle(void); // off, move, lock, off; logs; input thread
void freecam_pad(const FreecamPad *p);
void freecam_speed_click(int faster); // R (1) doubles the speed, L (0) halves it
void freecam_mouse(double right_deg, double down_deg); // a turn from the mouse, added at the next step
+29 -22
View File
@@ -359,14 +359,17 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_WALK_SCALE_DESC] = "The tilt the keyboard's sticks get while the walk key is held. Half is a walk, the "
"full tilt a run.",
[UI_MENU_FREECAM_PAD] = "Free camera combo",
[UI_MENU_FREECAM_PAD_DESC] = "Gamepad buttons pressed together that detach the view from Link and bring it back. "
"While it is on the game gets no input: the left stick flies along the view and sideways, the triggers up and "
"down, the right stick turns, and each press of L or R halves or doubles the speed. Game version 1.4.3.",
[UI_MENU_FREECAM_PAD_DESC] = "Gamepad buttons pressed together that step the view through three stages: it leaves "
"Link and flies, it stays where it was left while Link plays on, and it comes back. While it flies the game "
"gets no input: the left stick flies along the view and sideways, the triggers up and down, the right stick "
"turns, and each press of L or R halves or doubles the speed. Locked, Link walks where the left stick points "
"on screen. Game version 1.4.3.",
[UI_MENU_FREECAM_PAD_V143] = "Game version 1.4.3 only",
[UI_MENU_FREECAM_KEY] = "Free camera key",
[UI_MENU_FREECAM_KEY_DESC] = "A key that detaches the view from Link and brings it back. While it is on: W A S D "
"fly along the view and sideways, the keys bound to ZR and ZL (X and Z by default) up and down, the mouse and "
"the arrow keys turn, and the keys bound to L and R (Q and R) halve or double the speed. Game version 1.4.3.",
[UI_MENU_FREECAM_KEY_DESC] = "A key that steps the view through the same stages: it leaves Link and flies, it "
"stays while Link plays on, and it comes back. While it flies: W A S D fly along the view and sideways, the "
"keys bound to ZR and ZL (X and Z by default) up and down, the mouse and the arrow keys turn, and the keys "
"bound to L and R (Q and R) halve or double the speed. Game version 1.4.3.",
[UI_MENU_GROUP_GAMEPLAY_TWEAKS] = "Gameplay tweaks",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED] = "Gameplay tweaks",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED_DESC] = "Mouse wheel controls for Ultrahand rotation and distance, item and weapon switching, and smooth map zoom.",
@@ -979,14 +982,17 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_WALK_SCALE_DESC] = "Отклонение стиков клавиатуры при удержании клавиши шага. Половина — шаг, полное "
"отклонение — бег.",
[UI_MENU_FREECAM_PAD] = "Сочетание свободной камеры",
[UI_MENU_FREECAM_PAD_DESC] = "Кнопки геймпада, нажатые вместе, отделяют камеру от Линка и возвращают её. Пока она "
"включена, игра не получает ввод: левый стик ведёт камеру вдоль взгляда и вбок, курки — вверх и вниз, правый "
"стик поворачивает, а каждое нажатие L или R уменьшает или увеличивает скорость вдвое. Версия игры 1.4.3.",
[UI_MENU_FREECAM_PAD_DESC] = "Кнопки геймпада, нажатые вместе, переключают камеру по трём режимам: она отделяется "
"от Линка и летает, остаётся на месте, пока Линком снова можно управлять, и возвращается. Пока камера летает, "
"игра не получает ввод: левый стик ведёт камеру вдоль взгляда и вбок, курки — вверх и вниз, правый стик "
"поворачивает, а каждое нажатие L или R уменьшает или увеличивает скорость вдвое. Когда камера закреплена, "
"Линк идёт туда, куда левый стик указывает на экране. Версия игры 1.4.3.",
[UI_MENU_FREECAM_PAD_V143] = "Только для версии игры 1.4.3",
[UI_MENU_FREECAM_KEY] = "Клавиша свободной камеры",
[UI_MENU_FREECAM_KEY_DESC] = "Клавиша, которая отделяет камеру от Линка и возвращает её. Пока она включена: W A S "
"D ведут камеру вдоль взгляда и вбок, клавиши ZR и ZL (по умолчанию X и Z) — вверх и вниз, мышь и стрелки "
"поворачивают, а клавиши L и R (Q и R) уменьшают или увеличивают скорость вдвое. Версия игры 1.4.3.",
[UI_MENU_FREECAM_KEY_DESC] = "Клавиша, которая переключает те же режимы: камера отделяется от Линка и летает, "
"остаётся на месте, пока Линком снова можно управлять, и возвращается. Пока она летает: W A S D ведут камеру "
"вдоль взгляда и вбок, клавиши ZR и ZL (по умолчанию X и Z) — вверх и вниз, мышь и стрелки поворачивают, а "
"клавиши L и R (Q и R) уменьшают или увеличивают скорость вдвое. Версия игры 1.4.3.",
[UI_MENU_GROUP_GAMEPLAY_TWEAKS] = "Геймплей",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED] = "Настройки геймплея",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED_DESC] = "Управление колесом мыши: вращение и дистанция предметов в Ультраруке, выбор оружия и предметов, плавный зум карты.",
@@ -1790,16 +1796,17 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_WALK_SCALE_DESC] = "A inclinação dos analógicos do teclado enquanto a tecla de andar está segura. Metade "
"é andar, a inclinação total é correr.",
[UI_MENU_FREECAM_PAD] = "Combinação da câmera livre",
[UI_MENU_FREECAM_PAD_DESC] = "Botões do controle pressionados juntos que soltam a câmera do Link e a trazem de "
"volta. Enquanto ela está ligada o jogo não recebe comandos: o analógico esquerdo voa na direção da visão e "
"para os lados, os gatilhos sobem e descem, o analógico direito gira, e cada toque em L ou R reduz a "
"velocidade à metade ou a dobra. Versão do jogo 1.4.3.",
[UI_MENU_FREECAM_PAD_DESC] = "Botões do controle pressionados juntos que passam a câmera por três etapas: ela se "
"solta do Link e voa, fica parada onde foi deixada enquanto o Link volta a ser controlado, e volta. Enquanto "
"ela voa o jogo não recebe comandos: o analógico esquerdo voa na direção da visão e para os lados, os gatilhos "
"sobem e descem, o analógico direito gira, e cada toque em L ou R reduz a velocidade à metade ou a dobra. Com "
"a câmera parada, o Link anda para onde o analógico esquerdo aponta na tela. Versão do jogo 1.4.3.",
[UI_MENU_FREECAM_PAD_V143] = "Só na versão 1.4.3 do jogo",
[UI_MENU_FREECAM_KEY] = "Tecla da câmera livre",
[UI_MENU_FREECAM_KEY_DESC] = "Uma tecla que solta a câmera do Link e a traz de volta. Enquanto ela está ligada: W "
"A S D voam na direção da visão e para os lados, as teclas de ZR e ZL (X e Z por padrão) sobem e descem, o "
"mouse e as setas giram, e as teclas de L e R (Q e R) reduzem a velocidade à metade ou a dobram. Versão do "
"jogo 1.4.3.",
[UI_MENU_FREECAM_KEY_DESC] = "Uma tecla que passa a câmera pelas mesmas etapas: ela se solta do Link e voa, fica "
"parada enquanto o Link volta a ser controlado, e volta. Enquanto ela voa: W A S D voam na direção da visão e "
"para os lados, as teclas de ZR e ZL (X e Z por padrão) sobem e descem, o mouse e as setas giram, e as teclas "
"de L e R (Q e R) reduzem a velocidade à metade ou a dobram. Versão do jogo 1.4.3.",
[UI_MENU_GROUP_GAMEPLAY_TWEAKS] = "Ajustes de jogabilidade",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED] = "Ajustes de jogabilidade",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED_DESC] = "Controles com a roda do mouse para rotação e distância na Ultramão, seleção de armas e itens, e zoom suave no mapa.",
@@ -2550,10 +2557,10 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_WALK_SCALE] = "步行幅度",
[UI_MENU_WALK_SCALE_DESC] = "按住步行键时键盘摇杆的推动幅度。一半为走路,推满为奔跑。",
[UI_MENU_FREECAM_PAD] = "自由镜头组合键",
[UI_MENU_FREECAM_PAD_DESC] = "同时按下的手柄按键,让镜头脱离林克,再按一次回到林克。开启期间游戏不接收输入:左摇杆沿视线方向和左右移动,扳机键上升和下降,右摇杆转动视角,每按一次 L 或 R 速度减半或加倍。游戏版本 1.4.3。",
[UI_MENU_FREECAM_PAD_DESC] = "同时按下的手柄按键,让镜头依次切换三个阶段:脱离林克自由飞行、停在原处而林克恢复操作、回到林克。飞行期间游戏不接收输入:左摇杆沿视线方向和左右移动,扳机键上升和下降,右摇杆转动视角,每按一次 L 或 R 速度减半或加倍。镜头固定时,林克朝左摇杆在屏幕上指向的方向移动。游戏版本 1.4.3。",
[UI_MENU_FREECAM_PAD_V143] = "仅限游戏版本 1.4.3",
[UI_MENU_FREECAM_KEY] = "自由镜头键",
[UI_MENU_FREECAM_KEY_DESC] = "让镜头脱离林克、再按一次回到林克的按键。开启期间:W A S D 沿视线方向和左右移动,ZR 和 ZL 对应的按键(默认 X 和 Z)上升和下降,鼠标和方向键转动视角,L 和 R 对应的按键(默认 Q 和 R)让速度减半或加倍。游戏版本 1.4.3。",
[UI_MENU_FREECAM_KEY_DESC] = "让镜头依次切换相同阶段的按键:脱离林克自由飞行、停在原处而林克恢复操作、回到林克。飞行期间:W A S D 沿视线方向和左右移动,ZR 和 ZL 对应的按键(默认 X 和 Z)上升和下降,鼠标和方向键转动视角,L 和 R 对应的按键(默认 Q 和 R)让速度减半或加倍。游戏版本 1.4.3。",
[UI_MENU_GROUP_GAMEPLAY_TWEAKS] = "游戏操作微调",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED] = "启用操作微调",
[UI_MENU_GAMEPLAY_TWEAKS_ENABLED_DESC] = "使用鼠标滚轮控制究极手物体旋转与距离、武器与道具切换以及地图平滑缩放。",