Download aim.py from zhanwenchen/personalgui-accel-data: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/datasets/zhanwenchen/personalgui-accel-data/resolve/main/aim.py
- Command line
-
hf download hf://datasets/zhanwenchen/personalgui-accel-data/aim.py
-
curl -L -o aim.py https://huggingface.co/datasets/zhanwenchen/personalgui-accel-data/resolve/main/aim.py
13 kB
| # /// script | |
| # requires-python = '>=3.12' | |
| # dependencies = ['numpy', 'pillow', 'pyserial'] | |
| # /// | |
| '''Relative aiming for Task A: move the gun, not a cursor. | |
| Everything actuated so far has been absolute pointing — park the cursor, then | |
| jump to a screen pixel. That is right for menus and unusable in a battle: there | |
| is no cursor, and the mouse steers the gun by relative movement. So aiming is a | |
| control problem rather than a click, and it needs three things this file | |
| provides. | |
| 1. A way to measure how far the view actually moved, from the captured frames | |
| alone. Phase correlation gives that without any game-side information. | |
| 2. A gain: how many pixels the view turns per unit of mouse movement. This is | |
| a property of the game's sensitivity setting, so it has to be measured on | |
| the rig rather than assumed, and re-measured whenever that setting changes. | |
| 3. A closed loop: move, look, correct. One open-loop jump will not land, | |
| because the gain is only approximate and the turret has inertia. | |
| uv run aim.py --self-test # verify the estimator, no hardware | |
| uv run aim.py --calibrate # measure the gain (needs the game up) | |
| The self-test is the part that can be checked without the rig, and it is worth | |
| running after any change here: an aiming loop built on a shift estimator that | |
| is silently wrong would look like a model that cannot aim. | |
| ''' | |
| from __future__ import annotations | |
| import time | |
| from argparse import ArgumentParser | |
| from dataclasses import dataclass | |
| from io import BytesIO | |
| from typing import Callable | |
| import numpy as np | |
| from PIL import Image | |
| Grab = Callable[[], bytes] # returns JPEG bytes of the current frame | |
| def _luma(jpeg: bytes, downscale: int = 2) -> np.ndarray: | |
| im = Image.open(BytesIO(jpeg)).convert('L') | |
| if downscale > 1: | |
| im = im.resize((im.width // downscale, im.height // downscale)) | |
| return np.asarray(im, dtype=np.float32) | |
| def estimate_shift(a: np.ndarray, b: np.ndarray) -> tuple[float, float]: | |
| '''How far b is displaced from a, in pixels, by phase correlation. | |
| Returns (dx, dy): positive dx means the content moved right. A Hann window | |
| is applied first because the frames are not periodic and the edges would | |
| otherwise dominate the correlation. | |
| ''' | |
| if a.shape != b.shape: | |
| raise ValueError(f'frame size changed: {a.shape} vs {b.shape}') | |
| h, w = a.shape | |
| win = np.outer(np.hanning(h), np.hanning(w)) | |
| fa = np.fft.rfft2((a - a.mean()) * win) | |
| fb = np.fft.rfft2((b - b.mean()) * win) | |
| # conj(a)*b, not a*conj(b): the reversed order returns the exact | |
| # negative of the displacement, which an earlier version of this | |
| # file shipped while its self-test quietly negated the result and | |
| # reported a pass (FINDINGS F44). | |
| cross = np.conj(fa) * fb | |
| mag = np.abs(cross) | |
| mag[mag == 0] = 1e-12 | |
| corr = np.fft.irfft2(cross / mag, s=a.shape) | |
| peak = np.unravel_index(int(np.argmax(corr)), corr.shape) | |
| dy, dx = float(peak[0]), float(peak[1]) | |
| # wrap: a peak past the halfway point is a negative displacement | |
| if dy > h / 2: | |
| dy -= h | |
| if dx > w / 2: | |
| dx -= w | |
| return dx, dy | |
| class Gain: | |
| '''Pixels of view movement per unit of mouse movement, WITH sign. | |
| The sign records which way the view travels for a positive mouse movement. | |
| It is not cosmetic: aim_at is a proportional controller, and one fed a | |
| flipped sign does not converge slowly, it diverges. | |
| ''' | |
| px_per_count_x: float | |
| px_per_count_y: float | |
| downscale: int | |
| samples: int | |
| sign_stable: bool = True | |
| def counts_for(self, dx_px: float, dy_px: float) -> tuple[int, int]: | |
| gx = self.px_per_count_x or 1e-9 | |
| gy = self.px_per_count_y or 1e-9 | |
| return int(round(dx_px / gx)), int(round(dy_px / gy)) | |
| def calibrate_gain(hid, grab: Grab, counts: int = 200, samples: int = 3, | |
| settle_s: float = 0.35, downscale: int = 2) -> Gain: | |
| '''Measure pixels-per-count by moving a known amount and watching the view. | |
| Each sample moves out and back so the aim ends where it started, which | |
| matters because this runs on a live game. The horizontal and vertical gains | |
| are measured separately: they differ whenever the game applies a different | |
| sensitivity per axis. | |
| ''' | |
| xs: list[float] = [] | |
| ys: list[float] = [] | |
| for _ in range(samples): | |
| before = _luma(grab(), downscale) | |
| hid.move_rel(counts, 0) | |
| time.sleep(settle_s) | |
| after = _luma(grab(), downscale) | |
| dx, _ = estimate_shift(before, after) | |
| hid.move_rel(-counts, 0) | |
| time.sleep(settle_s) | |
| xs.append(dx * downscale / counts) # signed, deliberately | |
| before = _luma(grab(), downscale) | |
| hid.move_rel(0, counts) | |
| time.sleep(settle_s) | |
| after = _luma(grab(), downscale) | |
| _, dy = estimate_shift(before, after) | |
| hid.move_rel(0, -counts) | |
| time.sleep(settle_s) | |
| ys.append(dy * downscale / counts) # signed, deliberately | |
| # If the measured direction flips between samples the gain is not | |
| # trustworthy at all: something other than our input is moving the view. | |
| stable = (len({x > 0 for x in xs}) == 1 and len({y > 0 for y in ys}) == 1) | |
| return Gain(float(np.median(xs)), float(np.median(ys)), | |
| downscale, samples, stable) | |
| def aim_at(hid, grab: Grab, offset_fn: Callable[[bytes], tuple[float, float] | None], | |
| gain: Gain, tol_px: float = 12.0, max_steps: int = 6, | |
| settle_s: float = 0.25, damping: float = 0.8) -> dict: | |
| '''Bring the gun onto a target by moving, looking and correcting. | |
| offset_fn is given the current frame and returns how far the target sits | |
| from the aiming point in pixels, or None if it cannot find it. Steps are | |
| damped because overshooting and oscillating is the usual failure of a loop | |
| like this, and each correction is measured rather than assumed. | |
| ''' | |
| trace: list[dict] = [] | |
| for step in range(max_steps): | |
| frame = grab() | |
| off = offset_fn(frame) | |
| if off is None: | |
| trace.append({'step': step, 'status': 'target not found'}) | |
| return {'hit': False, 'reason': 'target not found', 'trace': trace} | |
| dx_px, dy_px = off | |
| err = float(np.hypot(dx_px, dy_px)) | |
| trace.append({'step': step, 'dx_px': dx_px, 'dy_px': dy_px, 'err_px': err}) | |
| if err <= tol_px: | |
| return {'hit': True, 'steps': step, 'err_px': err, 'trace': trace} | |
| cx, cy = gain.counts_for(dx_px * damping, dy_px * damping) | |
| if cx == 0 and cy == 0: # below one count of resolution | |
| return {'hit': False, 'reason': 'below movement resolution', | |
| 'err_px': err, 'trace': trace} | |
| hid.move_rel(cx, cy) | |
| time.sleep(settle_s) | |
| return {'hit': False, 'reason': 'did not converge', 'trace': trace} | |
| def _self_test() -> int: | |
| '''Check the estimator against known shifts, with no hardware involved.''' | |
| rng = np.random.default_rng(0) | |
| base = rng.random((360, 640)).astype(np.float32) | |
| # smooth it so it resembles a scene rather than white noise | |
| for _ in range(3): | |
| base = (base + np.roll(base, 1, 0) + np.roll(base, 1, 1)) / 3.0 | |
| worst = 0.0 | |
| print(f'{"true dx":>8s} {"true dy":>8s} {"est dx":>8s} {"est dy":>8s}') | |
| # The last four exceed half the frame on one or both axes, which is | |
| # what exercises the wrap-around branch below (half-width 320, | |
| # half-height 180 on this 360x640 test image). | |
| for tdx, tdy in ((10, 0), (-14, 0), (0, 9), (0, -21), (17, -13), | |
| (-30, 25), (200, 0), (-260, 0), (0, 150), | |
| (240, -140)): | |
| shifted = np.roll(np.roll(base, tdy, axis=0), tdx, axis=1) | |
| edx, edy = estimate_shift(base, shifted) | |
| print(f'{tdx:8d} {tdy:8d} {edx:8.1f} {edy:8.1f}') | |
| worst = max(worst, abs(edx - tdx), abs(edy - tdy)) | |
| ok = worst <= 1.0 | |
| print(f'\nworst error {worst:.2f} px — {"PASS" if ok else "FAIL"}') | |
| return 0 if ok else 1 | |
| def _direction_test() -> int: | |
| """Run the real calibrate_gain against a mock rig with a known direction. | |
| The estimator's self-test only exercises estimate_shift. This exercises the | |
| whole path — device, capture, gain — and checks the one property nothing | |
| else checks: that a positive mouse movement produces a gain whose SIGN says | |
| which way the view actually went. Two bugs shipped for want of this test | |
| (FINDINGS F44): the estimator returned the negative of its contract, and | |
| the gain discarded the sign with abs() so nothing downstream could notice. | |
| """ | |
| from io import BytesIO as _B | |
| rng = np.random.default_rng(1) | |
| world = rng.random((720, 1280)).astype(np.float32) | |
| for _ in range(3): | |
| world = (world + np.roll(world, 1, 0) + np.roll(world, 1, 1)) / 3.0 | |
| class MockRig: | |
| """A device whose movement really does displace the captured view.""" | |
| def __init__(self, px_per_count_x: float, px_per_count_y: float): | |
| self.gx, self.gy = px_per_count_x, px_per_count_y | |
| self.ox = self.oy = 0.0 | |
| def move_rel(self, dx: int, dy: int) -> None: | |
| self.ox += dx * self.gx | |
| self.oy += dy * self.gy | |
| def grab(self) -> bytes: | |
| view = np.roll(np.roll(world, int(round(self.oy)), 0), | |
| int(round(self.ox)), 1) | |
| buf = _B() | |
| Image.fromarray(view.clip(0, 1).__mul__(255).astype('uint8')).save( | |
| buf, format='JPEG', quality=92) | |
| return buf.getvalue() | |
| ok = True | |
| print(f'{"true gain x":>12s} {"true gain y":>12s} ' | |
| f'{"measured x":>11s} {"measured y":>11s} verdict') | |
| for tgx, tgy in ((0.40, 0.35), (-0.40, 0.35), (0.55, -0.48), (-0.30, -0.30)): | |
| rig = MockRig(tgx, tgy) | |
| g = calibrate_gain(rig, rig.grab, counts=100, samples=2, | |
| settle_s=0.0, downscale=2) | |
| sign_ok = (np.sign(g.px_per_count_x) == np.sign(tgx) | |
| and np.sign(g.px_per_count_y) == np.sign(tgy)) | |
| mag_ok = (abs(abs(g.px_per_count_x) - abs(tgx)) < 0.05 | |
| and abs(abs(g.px_per_count_y) - abs(tgy)) < 0.05) | |
| good = sign_ok and mag_ok and g.sign_stable | |
| ok &= good | |
| print(f'{tgx:12.2f} {tgy:12.2f} {g.px_per_count_x:11.3f} ' | |
| f'{g.px_per_count_y:11.3f} ' | |
| f'{"ok" if good else ("SIGN WRONG" if not sign_ok else "magnitude off")}') | |
| # A controller given a flipped gain must diverge, not merely converge | |
| # slowly. Confirm that, so the sign check above is known to matter. | |
| class Turret: | |
| def __init__(self, dx, gx): self.dx, self.gx = dx, gx | |
| def move_rel(self, cx, cy): self.dx -= cx * self.gx | |
| def offset(self, _): return (self.dx, 0.0) | |
| right = Turret(300.0, 0.40) | |
| aim_at(right, lambda: b'', right.offset, | |
| Gain(0.40, 0.40, 2, 2), tol_px=12, max_steps=6, settle_s=0.0) | |
| flipped = Turret(300.0, 0.40) | |
| aim_at(flipped, lambda: b'', flipped.offset, | |
| Gain(-0.40, -0.40, 2, 2), tol_px=12, max_steps=6, settle_s=0.0) | |
| diverged = abs(flipped.dx) > 300.0 | |
| print(f'\ncorrect sign converges to {abs(right.dx):8.1f} px') | |
| print(f'flipped sign ends at {abs(flipped.dx):8.1f} px ' | |
| f'({"diverges as expected" if diverged else "DID NOT DIVERGE"})') | |
| ok &= diverged | |
| print(f'\n{"PASS" if ok else "FAIL"}') | |
| return 0 if ok else 1 | |
| def main() -> int: | |
| ap = ArgumentParser(description='Relative aiming for Task A.') | |
| ap.add_argument('--self-test', action='store_true') | |
| ap.add_argument('--direction-test', action='store_true', | |
| help='run the real gain measurement against a mock rig') | |
| ap.add_argument('--calibrate', action='store_true') | |
| ap.add_argument('--counts', type=int, default=200) | |
| ap.add_argument('--device', default='/dev/video0') | |
| ap.add_argument('--port', | |
| default='/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0') | |
| args = ap.parse_args() | |
| if args.self_test: | |
| return _self_test() | |
| if args.direction_test: | |
| return _direction_test() | |
| if args.calibrate: | |
| from gua_eval.capture import ElgatoSource # noqa: PLC0415 | |
| from hid_kmbox import KMBox # noqa: PLC0415 | |
| cap = ElgatoSource(args.device) | |
| frames = cap.frames() | |
| def grab() -> bytes: | |
| return next(frames)[0] | |
| with KMBox(args.port) as hid: | |
| hid.open() | |
| hid.set_relative() | |
| gain = calibrate_gain(hid, grab, counts=args.counts) | |
| print(f'horizontal {gain.px_per_count_x:.4f} px/count') | |
| print(f'vertical {gain.px_per_count_y:.4f} px/count') | |
| print(f' a 300 px correction needs ' | |
| f'{gain.counts_for(300, 0)[0]} counts horizontally') | |
| return 0 | |
| ap.print_help() | |
| return 0 | |
| if __name__ == '__main__': | |
| raise SystemExit(main()) | |