From c08bc922b6f3bbc478fd4aae59fd7c037e181606 Mon Sep 17 00:00:00 2001 From: kinect-bot Date: Mon, 30 Nov 2026 12:53:45 -0500 Subject: [PATCH] feat(tracker): add Linux cursor calibration, matching the Windows flow exactly "the cursor scaling is still wrong, make it like the windows one" - the Linux tracker had no way to calibrate at all. The in-game cursor's arm-reach gains (default 3.2/2.6) were tuned specifically for the native Windows tracker's camera/pose characteristics via its "Calibrate cursor" button (core/calibration.h's derive_arm_gains); Linux users were stuck on that default regardless of their own camera/body, with no equivalent tool. tracker/calibration.py is a byte-for-byte port of core/calibration.h's arm-gain derivation (mean(|reach|) -> target/mean, clamped [1,6]) and the calibration.cfg text format load_config()/save_config() share, so a config written by either side is read identically by the shim - not a reimplementation that happens to produce similar numbers, the same formula and the same wire format, verified against tests/test_calibration.cpp's own cases (averaging, diagonal-gesture success, horizontal-only rejection, clamp-to-min, save/reload round-trip) ported 1:1 into tests/test_calibration_py.py - 6/6 passing, plus the existing tracker suite still 11/11. tracker.py gets a --calibrate mode (calibrate_cursor()): mirrors each frame for pose inference exactly like the main loop, computes Kinect joints with mirror=False, and reads HAND_LEFT (index 7) minus SHOULDER_LEFT (index 4) - the slots the player's actual right arm lands in post-mirror, pre-shim-swap, matching exactly where win_main.cpp's CalibrateCursor() reads skeleton.joints[7]/[4] (verified by reading that function directly). Usage: nix run .#tracker -- --calibrate --source 0. docs/calibration.md and docs/linux-wine.md document the Linux flow, the Linux default config path (no %LOCALAPPDATA% equivalent - XDG config dir), and that KINECT_SHIM_CONFIG must be set explicitly in both the calibration tool's environment and the game's launch options (Wine or Proton) so they agree on one file - the same pattern already established for KINECT_SHIM_SHM_FILE. Co-authored-by: sisyphus-dev-ai --- docs/calibration.md | 44 +++++-- docs/linux-wine.md | 26 ++++- tests/test_calibration_py.py | 92 +++++++++++++++ tracker/calibration.py | 218 +++++++++++++++++++++++++++++++++++ tracker/tracker.py | 79 +++++++++++++ 5 files changed, 443 insertions(+), 16 deletions(-) create mode 100644 tests/test_calibration_py.py create mode 100644 tracker/calibration.py diff --git a/docs/calibration.md b/docs/calibration.md index e8e6a43..22a49b5 100644 --- a/docs/calibration.md +++ b/docs/calibration.md @@ -6,11 +6,12 @@ your camera's field of view and where you stand. The guided cursor calibration m arm reach and writes per-camera gains, so the cursor covers the whole screen on your setup instead of only the author's. -The calibration logic lives in `core/calibration/` (`calibration.h` / `calibration.cpp`). The -native tracker runs it from the **Calibrate cursor** button and the `Kinect10.dll` shim reads the -result, so you calibrate once in the tracker and the game picks it up. +The calibration logic lives in `core/calibration/` (`calibration.h` / `calibration.cpp`), shared by +the Windows tracker/shim; `tracker/calibration.py` is a byte-for-byte port of the same arm-gain +derivation and `calibration.cfg` text format for the Linux/Wine path, so a config written by either +side is read identically by the other. -## Run it +### Windows (native tracker) 1. Start capture in the tracker (pick your camera and a 4:3 resolution, click **Start**). 2. Stand at your normal playing distance with your whole body in frame. @@ -18,17 +19,40 @@ result, so you calibrate once in the tracker and the game picks it up. screen** - hand clearly above your shoulder and out to the side - for about two seconds, as the status line prompts. -The tracker averages the raised-arm hold, derives the arm-reach gains (`derive_arm_gains`), and -saves them. The status line reports the gains it wrote, or a clear error if it didn't see a -detected, fully-extended arm, so you can retry. +### Linux (DEA under Wine/Proton, docs/linux-wine.md path) + +With the Linux tracker's dependencies set up (`docs/setup-linux.md`), run the calibrate mode +instead of the normal publish loop: + +```sh +nix run .#tracker -- --calibrate --source 0 +# or without Nix: tracker/.venv/bin/python -m tracker.tracker --calibrate --source 0 +``` + +Stand at your playing distance, whole body in frame, and raise your right arm up and out toward the +top corner of the screen - hand clearly above your shoulder and out to the side - when the terminal +prompts you; the hold lasts about two seconds. This does not run the normal tracker loop or publish +to shared memory - it exits after writing the config. + +Both paths average the raised-arm hold, derive the arm-reach gains (`derive_arm_gains`), and save +them. Each reports the gains it wrote, or a clear error if it didn't see a detected, fully-extended +arm, so you can retry. ## Where it's saved and who reads it Both programs share one config path so they always agree: -- Default: `%LOCALAPPDATA%\VirtualKinect\calibration.cfg`. -- Override: set `KINECT_SHIM_CONFIG` to a file path, in both the tracker and the shim's - environment, to use a different location. +- Windows default: `%LOCALAPPDATA%\VirtualKinect\calibration.cfg`. +- Linux default (no `%LOCALAPPDATA%` equivalent): `$XDG_CONFIG_HOME/VirtualKinect/calibration.cfg` + (usually `~/.config/VirtualKinect/calibration.cfg`). This is a plain Linux path, not reachable + from the shim running under Wine/Proton without an override - see below. +- Override: set `KINECT_SHIM_CONFIG` to a file path, in **both** the calibration tool's and the + shim's environment, to use a different (or shared) location. On the Linux/Wine path this is + **required**, not optional: set it in your shell when running `--calibrate`, and set it again + (as the Wine-visible path through the default `Z:` drive, e.g. + `KINECT_SHIM_CONFIG='Z:\home\you\.config\VirtualKinect\calibration.cfg'`) in the game's Steam + Launch Options alongside `KINECT_SHIM_SHM_FILE` (see `docs/linux-wine.md`), so the tool and the + shim agree on the same underlying file. The shim resolves the arm gains with this precedence: diff --git a/docs/linux-wine.md b/docs/linux-wine.md index b2c464c..9ce522a 100644 --- a/docs/linux-wine.md +++ b/docs/linux-wine.md @@ -85,21 +85,35 @@ exact same tmpfs file. No Wine camera support needed at all. ``` This creates `/dev/shm/virtual_kinect_frames` and keeps publishing live frames into it. -5. **Launch DEA under Wine with `KINECT_SHIM_SHM_FILE` set**, pointing at that same file - through the `Z:` drive: +5. **Launch DEA with `KINECT_SHIM_SHM_FILE` set**, pointing at that same file through the + `Z:` drive. Plain Wine: ```sh WINEPREFIX=/path/to/your/prefix \ KINECT_SHIM_SHM_FILE='Z:\dev\shm\virtual_kinect_frames' \ wine spice2x.exe # (or however you normally launch it) ``` + Steam Proton (add spice2x/DEA as a non-Steam game, force a Proton version in + Properties -> Compatibility): put the same assignment in **Properties -> General -> + Launch Options**, prefixed before `%command%`: + ``` + KINECT_SHIM_SHM_FILE='Z:\dev\shm\virtual_kinect_frames' %command% + ``` The shim reads `KINECT_SHIM_SHM_FILE` once at `NuiInitialize` and, when set, opens that path as a file-backed mapping instead of looking for the named Wine section. Check `kinect_shim.log` for a `shm-file='...' open=1` line to confirm it attached. -6. Calibration (`docs/calibration.md`) and everything downstream works the same as the - Windows path - the shim doesn't care whether the bytes came from a Windows tracker or - this Linux one, only that the contract layout matches (it's `#pragma pack(1)` and - already cross-checked against the Python struct by the core test suite). +6. **Calibrate the cursor** - required on Linux, there is no built-in default that fits + every camera. With the tracker set up, run: + ```sh + nix run .#tracker -- --calibrate --source 0 + ``` + and raise your right arm as prompted. Then set `KINECT_SHIM_CONFIG` the same way as + `KINECT_SHIM_SHM_FILE` above (same `Z:`-drive path translation) in the launch options, so + the shim reads the gains this just wrote. See `docs/calibration.md` for the full guide + and the exact env var to set. Everything downstream works the same as the Windows path - + the shim doesn't care whether the bytes came from a Windows tracker or this Linux one, + only that the contract layout matches (it's `#pragma pack(1)` and already cross-checked + against the Python struct by the core test suite). ## If it still doesn't attach diff --git a/tests/test_calibration_py.py b/tests/test_calibration_py.py new file mode 100644 index 0000000..f4e2873 --- /dev/null +++ b/tests/test_calibration_py.py @@ -0,0 +1,92 @@ +"""Parity tests for tracker/calibration.py against core/calibration.h's +behavior, mirroring tests/test_calibration.cpp's derive_arm_gains and +save_config/load_config cases so the two implementations are provably the +same function, not just similarly-named ones.""" + +import os +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from tracker.calibration import ( # noqa: E402 + ARM_GAIN_MAX, + ARM_GAIN_MIN, + TARGET_ARM_REACH_X, + TARGET_ARM_REACH_Y, + CalibrationConfig, + calibration_config_path, + derive_arm_gains, + load_config, + save_config, +) + + +def test_derive_arm_gains_averages_hold_and_scales_to_target_reach(): + hold = [(0.5, 0.3)] * 16 + gains, error = derive_arm_gains(hold) + assert error == "" + assert gains.x == pytest.approx(TARGET_ARM_REACH_X / 0.5, abs=1e-5) + assert gains.y == pytest.approx(TARGET_ARM_REACH_Y / 0.3, abs=1e-5) + + +def test_derive_arm_gains_succeeds_on_diagonal_up_and_out_gesture(): + diagonal_hold = [(0.5, 0.3)] * 16 + gains, error = derive_arm_gains(diagonal_hold) + assert error == "" + assert ARM_GAIN_MIN < gains.x < ARM_GAIN_MAX + assert ARM_GAIN_MIN < gains.y < ARM_GAIN_MAX + + horizontal_hold = [(0.5, 0.0)] * 16 + gains2, error2 = derive_arm_gains(horizontal_hold) + assert gains2 is None + assert "too small" in error2 + + +def test_derive_arm_gains_clamps_to_range_and_rejects_bad_holds(): + gains, error = derive_arm_gains([]) + assert gains is None + assert error != "" + + gains2, error2 = derive_arm_gains([(0.0, 0.0)]) + assert gains2 is None + + gains3, error3 = derive_arm_gains([(2.0, 2.0)]) + assert gains3.x == pytest.approx(ARM_GAIN_MIN) + assert gains3.y == pytest.approx(ARM_GAIN_MIN) + + +def test_saved_config_reloads_with_identical_values(): + original = CalibrationConfig( + depth_width=640, + depth_height=480, + z0_meters=2.6, + depth_gain=1.0, + mirror=True, + player_scale=1.23, + smoothing=(0.6, 0.4, 0.4, 0.04, 0.07), + floor_plane=(0.0, 1.0, 0.0, -0.9), + arm_gain_x=3.7, + arm_gain_y=3.0, + ) + path = "/tmp/kinect_calibration_py_test.cfg" + try: + save_config(original, path) + loaded = load_config(path) + assert loaded == original + finally: + if os.path.exists(path): + os.remove(path) + + +def test_load_config_missing_file_returns_none(): + assert load_config("/tmp/kinect_calibration_py_test_missing.cfg") is None + + +def test_calibration_config_path_honors_env_override(): + assert calibration_config_path("/custom/path.cfg") == "/custom/path.cfg" + assert calibration_config_path(None).endswith( + os.path.join("VirtualKinect", "calibration.cfg") + ) diff --git a/tracker/calibration.py b/tracker/calibration.py new file mode 100644 index 0000000..b163d7d --- /dev/null +++ b/tracker/calibration.py @@ -0,0 +1,218 @@ +"""Camera-agnostic cursor arm-reach calibration, ported from core/calibration.h. + +This is a byte-for-byte port of the arm-gain derivation and the shared +calibration.cfg text format the shim's load_config()/save_config() (C++, +core/calibration.h) read and write, so a config written here is read +identically by the shim regardless of which side wrote it. Only the arm-gain +calibration flow is ported (the "Calibrate cursor" button on the native +tracker); the T-pose scale/floor-plane calibration is not, since the shim +works fine on the CalibrationConfig{} defaults for those fields - only the +arm-reach gains need a per-camera value. + +Formula and defaults are copied exactly from core/calibration.h (not +reimplemented independently): see kTargetArmReachX/Y, kArmGainMin/Max, and +derive_arm_gains's mean-of-abs-reach clamp-and-divide. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from typing import Optional + +# --- core/calibration.h constants (copied exactly) ------------------------- + +DEFAULT_ARM_GAIN_X = 3.2 +DEFAULT_ARM_GAIN_Y = 2.6 +ARM_GAIN_MIN = 1.0 +ARM_GAIN_MAX = 6.0 +TARGET_ARM_REACH_X = 0.86 +TARGET_ARM_REACH_Y = 0.5 +MIN_MEASURED_REACH = 1e-3 + +# --- core/mapping.h MappingConfig{} / SmoothingParameters{} defaults ------- +# (the CalibrationConfig{} fields this module does not calibrate; written +# verbatim so a config written here, loaded by the shim, behaves exactly like +# one the native tracker would produce before ever running T-pose calibration) + +DEFAULT_DEPTH_WIDTH = 640 +DEFAULT_DEPTH_HEIGHT = 480 +DEFAULT_Z0_METERS = 2.5 +DEFAULT_DEPTH_GAIN = 0.0 +DEFAULT_MIRROR = True +DEFAULT_PLAYER_SCALE = 1.0 +DEFAULT_SMOOTHING = (0.6, 0.4, 0.4, 0.04, 0.07) +DEFAULT_FLOOR_PLANE = (0.0, 1.0, 0.0, 0.0) + + +@dataclass +class ArmGains: + x: float = DEFAULT_ARM_GAIN_X + y: float = DEFAULT_ARM_GAIN_Y + + +@dataclass +class CalibrationConfig: + depth_width: int = DEFAULT_DEPTH_WIDTH + depth_height: int = DEFAULT_DEPTH_HEIGHT + z0_meters: float = DEFAULT_Z0_METERS + depth_gain: float = DEFAULT_DEPTH_GAIN + mirror: bool = DEFAULT_MIRROR + player_scale: float = DEFAULT_PLAYER_SCALE + smoothing: tuple[float, float, float, float, float] = field( + default_factory=lambda: DEFAULT_SMOOTHING + ) + floor_plane: tuple[float, float, float, float] = field( + default_factory=lambda: DEFAULT_FLOOR_PLANE + ) + arm_gain_x: float = DEFAULT_ARM_GAIN_X + arm_gain_y: float = DEFAULT_ARM_GAIN_Y + + +def derive_arm_gains( + samples: list[tuple[float, float]], +) -> tuple[Optional[ArmGains], str]: + """Exactly core/calibration.h's derive_arm_gains: gain = target_reach / + mean(|measured_reach|), clamped to [1.0, 6.0]. `samples` are + (measured_reach_x, measured_reach_y) pairs already filtered to + person-detected frames. Returns (None, error) on failure, matching the + C++ function's (false, error) contract.""" + if not samples: + return None, "arm-gain calibration requires a detected raised-arm hold" + mean_x = sum(abs(x) for x, _ in samples) / len(samples) + mean_y = sum(abs(y) for _, y in samples) / len(samples) + if mean_x < MIN_MEASURED_REACH or mean_y < MIN_MEASURED_REACH: + return None, "arm-gain calibration reach too small - extend the arm fully" + gains = ArmGains( + x=min(max(TARGET_ARM_REACH_X / mean_x, ARM_GAIN_MIN), ARM_GAIN_MAX), + y=min(max(TARGET_ARM_REACH_Y / mean_y, ARM_GAIN_MIN), ARM_GAIN_MAX), + ) + return gains, "" + + +def calibration_config_path(env_override: Optional[str] = None) -> str: + """Linux equivalent of core/calibration.h's calibration_config_path: the + KINECT_SHIM_CONFIG override (shared with the shim - set it to the same + path, reachable from Wine via its Z: drive, in the game's launch options) + when set, else a Linux XDG-style default. There is no %LOCALAPPDATA% on + Linux, so this does not reuse the Windows-side default path string - set + KINECT_SHIM_CONFIG explicitly to share one file with the shim.""" + override = env_override if env_override is not None else os.environ.get("KINECT_SHIM_CONFIG") + if override: + return override + xdg_config = os.environ.get("XDG_CONFIG_HOME") or os.path.join( + os.path.expanduser("~"), ".config" + ) + return os.path.join(xdg_config, "VirtualKinect", "calibration.cfg") + + +def save_config(config: CalibrationConfig, path: str) -> None: + """Writes the exact whitespace-delimited token format core/calibration.h's + save_config()/load_config() share - key, then its value(s), one line per + key. The shim's loader reads tokens via operator>>, so exact whitespace + layout does not matter, but the key names, order, and count of tokens + per key do.""" + parent = os.path.dirname(path) + if parent: + os.makedirs(parent, exist_ok=True) + with open(path, "w") as f: + f.write(f"depth_width {config.depth_width}\n") + f.write(f"depth_height {config.depth_height}\n") + f.write(f"z0_meters {config.z0_meters!r}\n") + f.write(f"depth_gain {config.depth_gain!r}\n") + f.write(f"mirror {1 if config.mirror else 0}\n") + f.write(f"player_scale {config.player_scale!r}\n") + f.write("smoothing " + " ".join(repr(v) for v in config.smoothing) + "\n") + f.write("floor_plane " + " ".join(repr(v) for v in config.floor_plane) + "\n") + f.write(f"arm_gain_x {config.arm_gain_x!r}\n") + f.write(f"arm_gain_y {config.arm_gain_y!r}\n") + + +def load_config(path: str) -> Optional[CalibrationConfig]: + """Mirrors core/calibration.h's load_config: strict token-by-token parse + of the required depth_width..floor_plane fields (None on any failure, so + a missing/corrupt file falls back to CalibrationConfig() defaults exactly + like the C++ side), then scans optional trailing arm_gain_x/arm_gain_y + tokens.""" + try: + with open(path) as f: + tokens = f.read().split() + except OSError: + return None + + def take(expected_key: str, count: int, pos: int): + if pos >= len(tokens) or tokens[pos] != expected_key: + return None, pos + pos += 1 + if pos + count > len(tokens): + return None, pos + values = tokens[pos : pos + count] + return values, pos + count + + pos = 0 + values, pos = take("depth_width", 1, pos) + if values is None: + return None + depth_width = int(values[0]) + values, pos = take("depth_height", 1, pos) + if values is None: + return None + depth_height = int(values[0]) + values, pos = take("z0_meters", 1, pos) + if values is None: + return None + z0_meters = float(values[0]) + values, pos = take("depth_gain", 1, pos) + if values is None: + return None + depth_gain = float(values[0]) + values, pos = take("mirror", 1, pos) + if values is None: + return None + mirror = values[0] not in ("0", "0.0") + values, pos = take("player_scale", 1, pos) + if values is None: + return None + player_scale = float(values[0]) + values, pos = take("smoothing", 5, pos) + if values is None: + return None + smoothing = tuple(float(v) for v in values) + values, pos = take("floor_plane", 4, pos) + if values is None: + return None + floor_plane = tuple(float(v) for v in values) + + config = CalibrationConfig( + depth_width=depth_width, + depth_height=depth_height, + z0_meters=z0_meters, + depth_gain=depth_gain, + mirror=mirror, + player_scale=player_scale, + smoothing=smoothing, + floor_plane=floor_plane, + ) + + # Optional trailing arm_gain_x/arm_gain_y pair, in any order, mirroring + # the C++ loader's "while (file >> extra)" scan. + i = pos + while i < len(tokens): + key = tokens[i] + if key not in ("arm_gain_x", "arm_gain_y"): + i += 1 + continue + if i + 1 >= len(tokens): + break + try: + value = float(tokens[i + 1]) + except ValueError: + i += 2 + continue + if key == "arm_gain_x": + config.arm_gain_x = value + else: + config.arm_gain_y = value + i += 2 + + return config diff --git a/tracker/tracker.py b/tracker/tracker.py index c473bf3..37d04a0 100644 --- a/tracker/tracker.py +++ b/tracker/tracker.py @@ -249,6 +249,69 @@ def _parse_size(text: str) -> tuple[int, int]: return int(w), int(h) +def calibrate_cursor( + source: FrameSource, + provider: PoseProvider, + depth_size: tuple[int, int], + hold_seconds: float = 1.8, +) -> int: + """Port of tracker-native's win_main.cpp CalibrateCursor(): mirror each + frame for pose inference (same as the main loop), compute Kinect joints + with mirror=False (the physical flip already did that job), and read + HAND_LEFT (index 7) minus SHOULDER_LEFT (index 4) - the slots the + player's actual right arm lands in post-mirror, pre-shim-swap, exactly + where win_main.cpp reads skeleton.joints[7]/[4]. Prints the same + "Calibrated cursor gains X=... Y=... (saved)" / "Calibration failed: ..." + status text the native tracker's status line shows.""" + import cv2 + + from . import calibration as cal + from .joint_mapping import map_pose_to_kinect_joints + + print( + "Calibrating cursor: raise your right arm up and out toward the top " + "corner of the screen - hand clearly above your shoulder and out to " + "the side...", + flush=True, + ) + samples: list[tuple[float, float]] = [] + deadline = time.monotonic() + hold_seconds + while time.monotonic() < deadline: + frame = source.read() + if frame is None: + break + mirrored = cv2.flip(frame, 1) + pose = provider.process(mirrored, timestamp_ms=None) + if pose is None: + continue + joints = map_pose_to_kinect_joints(pose, depth_size, mirror=False) + hand = joints[7] + shoulder = joints[4] + samples.append((hand[0] - shoulder[0], hand[1] - shoulder[1])) + + gains, error = cal.derive_arm_gains(samples) + if gains is None: + print(f"Calibration failed: {error}", flush=True) + return 1 + + path = cal.calibration_config_path() + config = cal.load_config(path) or cal.CalibrationConfig() + config.arm_gain_x = gains.x + config.arm_gain_y = gains.y + cal.save_config(config, path) + print( + f"Calibrated cursor gains X={gains.x:.6f} Y={gains.y:.6f} " + f"(saved to {path})", + flush=True, + ) + print( + "Set KINECT_SHIM_CONFIG to this same path (reachable from Wine via its " + "Z: drive) in the game's launch options so the shim reads it.", + flush=True, + ) + return 0 + + def main(argv: Optional[list[str]] = None) -> int: parser = argparse.ArgumentParser(description="Webcam -> MediaPipe pose -> Kinect IPC contract publisher") parser.add_argument("--source", default="0", help="webcam index (e.g. 0) or video file path") @@ -262,10 +325,26 @@ def main(argv: Optional[list[str]] = None) -> int: parser.add_argument("--max-frames", type=int, default=None) parser.add_argument("--max-seconds", type=float, default=None) parser.add_argument("--measure-fps", action="store_true", help="benchmark lite/full/heavy and exit") + parser.add_argument( + "--calibrate", + action="store_true", + help="run the guided cursor arm-reach calibration and exit (writes the " + "shim's shared calibration.cfg; stand at your playing distance and " + "raise your right arm up and out when prompted)", + ) args = parser.parse_args(argv) from .pose import MediaPipePoseProvider + if args.calibrate: + source = CvFrameSource(args.source) + provider = MediaPipePoseProvider(model=args.model, models_dir=args.models_dir) + try: + return calibrate_cursor(source, provider, args.depth_size) + finally: + source.release() + provider.close() + if args.measure_fps: source = CvFrameSource(args.source) frame = source.read()