"""Take measurements and textures straight from the recording, using the camera the inputs imply. Run from the repository root; BUILD is your build folder (it holds recording.mp4, input.jsonl and controller.json): uv run python -m scripts.probe BUILD pose T the camera at T seconds: position, yaw and pitch (three.js axes, metres, origin on the floor under the first frame's camera, which looks along -z; yaw positive = turned right) uv run python -m scripts.probe BUILD floor T X,Y [X,Y ...] where on the floor (y = 0) each pixel of the frame at T lies: use it on the foot of a wall, a desk leg, a doorway's corners. Exact when the pixel really is on the floor. uv run python -m scripts.probe BUILD up T X,Y XB,YB the height of the point at pixel X,Y that stands straight above the floor point at pixel XB,YB (a table top above its leg's foot, a window sill above the wall's foot) uv run python -m scripts.probe BUILD frame T OUT.jpg the recording's frame at T, full size uv run python -m scripts.probe BUILD texture T X1,Y1 X2,Y2 X3,Y3 X4,Y4 OUT.png [WIDTH HEIGHT] the quadrilateral with those corners (top-left, top-right, bottom-right, bottom-left, as the surface should read) pulled straight into an image: a wall, a board, a poster, a patch of floor, as a texture that already carries the scene's own light controller.json holds the numbers the poses come from (edit it when the mirror shows a speed is off): {"hfov_deg":..,"eye_m":..,"turn_deg_s":..,"pitch_deg_s":..,"walk_m_s":..,"sprint_m_s":..,"response_per_s":.., "look_response_per_s":..,"lead_frames":..,"velocity_turns":..,"stick_dead":..,"stick_power":..,"stick_signs":[lx,ly,rx,ry], "keys":{"forward":..,"back":..,"left":..,"right":..,"turn_left":..,"turn_right":..,"look_up":..,"look_down":..,"sprint":..}} (keys default to W/S/A/D, the arrows and ShiftLeft). A "drive" block makes it a vehicle (poses() says how). "inferred": true marks a recording that came without inputs: its gamepad.jsonl is then the camera's own motion written as sticks (write_trace), not what a player pressed. The pose has no collisions: where the recording's player is stopped by something, poses after that point are wrong.""" import json, math, subprocess, sys from pathlib import Path import numpy as np W, H = 1280, 720 # the recording's frame; set from the recording itself by frame_size() def frame_size(build: Path) -> None: """Take the frame size from BUILD's recording: pixels mean nothing without it.""" global W, H found = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", str(build / "recording.mp4")], capture_output=True, text=True).stdout.strip().split(",") if len(found) == 2: W, H = int(found[0]), int(found[1]) def arm(c: dict, yaw, pitch): """Third person (``view``: "third" in the controller): from the ground under the character to the camera, which swings round a pivot ``pivot_m`` over the character's feet, ``orbit_m`` behind it and ``shoulder_m`` to its right along the camera's own axes (yaw positive to the right, pitch positive looking up; arrays do too).""" orbit, shoulder = c.get("orbit_m", 0.0), c.get("shoulder_m", 0.0) return (shoulder * np.cos(yaw) - orbit * np.sin(yaw) * np.cos(pitch), c.get("pivot_m", c["eye_m"]) - orbit * np.sin(pitch), shoulder * np.sin(yaw) + orbit * np.cos(yaw) * np.cos(pitch)) def mouse(build: Path): """The mouse's moves in BUILD's trace: (seconds, counts right and down), one row per mouse_move. A move holds dx and dy, or only where the pointer is (canvas_x, canvas_y): then it is how far that is from the move before.""" when, counts, was = [], [], None for line in (build / "input.jsonl").read_text().splitlines(): e = json.loads(line) if line.strip() else {} if e.get("event") == "mouse_move": here = (e["canvas_x"], e["canvas_y"]) if "canvas_x" in e and "canvas_y" in e else None if "dx" in e and "dy" in e: when.append(e["time_ns"] / 1e9); counts.append((float(e["dx"]), float(e["dy"]))) elif here and was: when.append(e["time_ns"] / 1e9); counts.append((here[0] - was[0], here[1] - was[1])) was = here order = np.argsort(when, kind="stable") return np.array(when, float)[order], np.array(counts, float).reshape(-1, 2)[order] def poses(build: Path, seconds: float, controller: dict | None = None): """The camera at 30 Hz as the recording's inputs drive it: (controller, rows of t, x, y, z, yaw, pitch). ``lead_frames`` in the controller is how far the picture runs ahead of the keys (negative: behind). In third person the inputs move the character, relative to where the camera faces, and the rows are still the camera's: the character stands at row x, z less arm()'s. Where the controller names a ``heading_track`` (a file beside it: t, yaw, pitch as the pictures saw the camera face; scripts/splat/cameras.py writes it where the look inputs do not explain the turning, a view locked onto something) the camera faces as it says. A mouse turns the camera by ``mouse_yaw_deg`` a count to the right and ``mouse_pitch_deg`` a count down (signed: not inverted, looking down is negative), at once and beside whatever the keys and sticks do. A vehicle (``drive`` in the controller, with ``view`` "third"): the forward and back keys (or the left stick) are the pedals and the turning keys (or the left and right ones, or the stick) the wheel. Its speed along its own heading goes toward ``top_m_s`` under the forward pedal and toward ``reverse_m_s`` backwards under the other, each time by a part of what is missing: ``accel_per_s`` of it a second while it speeds up, ``brake_per_s`` while a pedal works against the way it rolls, ``coast_per_s`` toward standing with no pedal. The wheel follows its keys at ``steer_per_s`` and turns the vehicle on a circle of ``turn_radius_m`` at full lock, no faster than ``turn_deg_s`` where the block has one (reversing, the other way round). The camera's arm is the third-person one; it faces where the vehicle heads, following at ``follow_per_s``, and looks down by ``pitch_deg`` (negative) all the time. With a heading track the camera faces as the track says and the vehicle heads where that camera was following to. ``cuts`` (scripts/splat/cuts.py: a recording whose picture jumps) are moments, each with where the state is then (x, z, yaw, pitch): the state is put there for the frame of that moment, and what speed it had turns with it.""" c = controller or json.loads((build / "controller.json").read_text()) third = c.get("view") == "third" track = json.loads((build / c["heading_track"]).read_text()) if c.get("heading_track") else None events = sorted((json.loads(line) for line in (build / "input.jsonl").read_text().splitlines() if line.strip()), key=lambda e: e["time_ns"]) keys, i, rows, past, lead = set(), 0, [], [], float(c.get("lead_frames") or 0) role = {"forward": "KeyW", "back": "KeyS", "left": "KeyA", "right": "KeyD", "turn_left": "ArrowLeft", "turn_right": "ArrowRight", "look_up": "ArrowUp", "look_down": "ArrowDown", "sprint": "ShiftLeft", **(c.get("keys") or {})} held = lambda a, b: (role[a] in keys) - (role[b] in keys) # A gamepad's sticks, where the recording has them (gamepad.jsonl: one row per frame, Gamepad-API axes, y # down). A stick past its dead zone overrides that stick's keys, and gives a part of the full rate. pad = build / "gamepad.jsonl" sticks = [json.loads(line) for line in pad.read_text().splitlines() if line.strip()] if pad.is_file() else [] dead, power, signs = c.get("stick_dead", 0.1), c.get("stick_power", 1.0), c.get("stick_signs") or [1, 1, 1, 1] curve = lambda v: 0.0 if abs(v) <= dead else math.copysign(((abs(v) - dead) / (1 - dead)) ** power, v) axes, row = [0.0] * 4, 0 # What stands in the walker's way, where the build has a map of it (walls.json, scripts/splat/walls.py). walls = json.loads((build / "walls.json").read_text()) if (build / "walls.json").is_file() else {"solid": []} solid, cell, wide = {(i, j) for i, j in walls["solid"]}, walls.get("cell", 1.0), walls.get("radius", 0.0) by_mouse = (math.radians(c.get("mouse_yaw_deg") or 0.0), math.radians(c.get("mouse_pitch_deg") or 0.0)) moved_at, moved = mouse(build) if any(by_mouse) else (np.zeros(0), np.zeros((0, 2))) drive = c.get("drive") def pushed(q): # out of the solid cells within reach (twice, so corners settle) for _ in range(2 if solid else 0): for i in range(math.floor((q[0] - wide) / cell), math.floor((q[0] + wide) / cell) + 1): for j in range(math.floor((q[1] - wide) / cell), math.floor((q[1] + wide) / cell) + 1): nx, nz = min(max(q[0], i * cell), (i + 1) * cell), min(max(q[1], j * cell), (j + 1) * cell) gap = math.hypot(q[0] - nx, q[1] - nz) if (i, j) in solid and 1e-9 < gap < wide: q[0], q[1] = nx + (q[0] - nx) / gap * wide, nz + (q[1] - nz) / gap * wide def step(q, dt=1 / 30, faces=None, counts=(0.0, 0.0)): # q: x, z, yaw, pitch, vx, vz, yaw rate, pitch rate lx, ly, rx, ry = (curve(v * g) for v, g in zip(axes, signs)) if drive: # a vehicle. q: x, z, the camera's yaw and pitch, speed along its heading, its heading, the wheel (-1..1) pedal, wheel = (-ly or held("forward", "back")), (lx or held("turn_right", "turn_left") or held("right", "left")) toward, rate = (drive["top_m_s"] * pedal, drive["accel_per_s"] if q[4] >= 0 else drive["brake_per_s"]) if pedal > 0 else \ (drive["reverse_m_s"] * pedal, drive["brake_per_s"] if q[4] > 0 else drive["accel_per_s"]) if pedal < 0 else (0.0, drive["coast_per_s"]) q[4] += (toward - q[4]) * min(1.0, rate * dt) q[6] += (wheel - q[6]) * min(1.0, (drive.get("steer_per_s") or 30) * dt) k = min(1.0, (drive.get("follow_per_s") or 30) * dt) if faces is None: q[5] += q[6] * math.copysign(min(abs(q[4]) / drive["turn_radius_m"], math.radians(drive.get("turn_deg_s") or 1e9)), q[4]) * dt q[2] += (q[5] - q[2]) * k; q[3] = math.radians(drive.get("pitch_deg") or 0.0) else: # (the heading that camera was following to) q[5] = q[2] + (faces[0] - q[2]) / k; q[2], q[3] = faces q[0] += math.sin(q[5]) * q[4] * dt; q[1] -= math.cos(q[5]) * q[4] * dt; pushed(q) return k = min(1.0, (c.get("look_response_per_s") or 30) * dt) # how quickly turning reaches its rate (30: at once) q[6] += ((rx or held("turn_right", "turn_left")) * math.radians(c["turn_deg_s"]) - q[6]) * k q[7] += ((-ry or held("look_up", "look_down")) * math.radians(c["pitch_deg_s"]) - q[7]) * k turned, tilted = q[6] * dt + counts[0] * by_mouse[0], q[7] * dt + counts[1] * by_mouse[1] if faces is not None: # the heading is the track's, whatever the look inputs say q[6], q[7] = (faces[0] - q[2]) / dt, (faces[1] - q[3]) / dt; turned, tilted = q[6] * dt, q[7] * dt q[2] += turned q[3] = max(-1.4, min(1.4, q[3] + tilted)) f, s = (-ly or held("forward", "back")), (lx or held("right", "left")) speed = c.get("sprint_m_s", c["walk_m_s"]) if role["sprint"] in keys and f > 0 else c["walk_m_s"] k = min(1.0, (c.get("response_per_s") or 30) * dt) if c.get("velocity_turns"): # the speed built up so far turns with the camera (kept as forward and sideways speed) q[4], q[5] = q[4] * math.cos(turned) - q[5] * math.sin(turned), q[5] * math.cos(turned) + q[4] * math.sin(turned) q[4] += ((math.sin(q[2]) * f + math.cos(q[2]) * s) * speed - q[4]) * k q[5] += ((-math.cos(q[2]) * f + math.sin(q[2]) * s) * speed - q[5]) * k q[0] += q[4] * dt; q[1] += q[5] * dt; pushed(q) state = [0.0] * 8 cuts, cut, take_of = sorted(c.get("cuts") or [], key=lambda to: to["t"]), 0, [] count = int(seconds * 30) + 2 if track: # (the frame at t shows step t + lead: that step faces as the frame did) shows = (np.arange(count + max(0, math.ceil(lead))) - lead) / 30 track = np.stack([np.interp(shows, track["t"], track[k]) for k in ("yaw", "pitch")], 1).tolist() # (the mouse's counts of each step: all the moves up to its moment, since the step before) step_of = np.clip(np.ceil((moved_at - 1e-6) * 30).astype(int), 0, None); counted = np.zeros((count + max(0, math.ceil(lead)) + 1, 2)) np.add.at(counted, np.minimum(step_of, len(counted) - 1), moved) for n in range(count + max(0, math.ceil(lead))): # far enough for the last frame's lead t = n / 30 # (a trace written per frame rounds its times to the nanosecond: without the margin half of them land a step late) while i < len(events) and events[i]["time_ns"] / 1e9 <= t + 1e-6: e = events[i]; i += 1 if e["event"] in ("key_press", "key_release"): (keys.add if e["event"] == "key_press" else keys.discard)(e["code"]) while row < len(sticks) and sticks[row]["time_ns"] / 1e9 <= t + 1e-6: axes = [*sticks[row]["left_stick"], *sticks[row]["right_stick"]]; row += 1 while cut < len(cuts) and t >= cuts[cut]["t"] + lead / 30 - 1e-6: to = cuts[cut]; cut += 1; turn = to["yaw"] - state[2] state[0], state[1], state[2], state[3] = to["x"], to["z"], to["yaw"], to.get("pitch", state[3]) if drive: state[5] += turn else: state[4], state[5] = state[4] * math.cos(turn) - state[5] * math.sin(turn), state[5] * math.cos(turn) + state[4] * math.sin(turn) step(state, faces=track[n] if track else None, counts=counted[n]); past.append(list(state)); take_of.append(cut) # The picture's lead over the keys is a shift in time: the frame at t shows the camera of t + lead frames # (a page can only guess ahead with the keys as they are; here the whole trace is known). last = len(past) - 1 for n in range(count): at = min(max(n + lead, 0.0), float(last)); a, b = past[int(at)], past[min(last, int(at) + 1)] shown = [u + (v - u) * (at % 1) for u, v in zip(a, b)] if take_of[int(at)] == take_of[min(last, int(at) + 1)] else list(b if at % 1 >= 0.5 else a) if third: dx, y, dz = arm(c, shown[2], shown[3]) rows.append((n / 30, shown[0] + float(dx), float(y), shown[1] + float(dz), shown[2], shown[3])) continue rows.append((n / 30, shown[0], c["eye_m"], shown[1], shown[2], shown[3])) return c, rows def write_trace(build: Path, facing, tilt, forward, right) -> tuple[float, float, float]: """An inferred trace (a recording that came without inputs): BUILD/gamepad.jsonl for a camera that faces ``facing`` and tilts ``tilt`` (radians) at every thirtieth of a second (one more of them than rows) and travels ``forward`` and ``right`` in between. Each stick is the motion over the largest there is, which are returned (turn and pitch in radians a second, travel in the unit given). Row n holds what happens between n/30 and (n + 1)/30 seconds: replayed with ``lead_frames`` -1 and no smoothing, poses() gives the camera back.""" forward, right = np.asarray(forward, float), np.asarray(right, float) turning, tilting = np.diff(facing) * 30, np.diff(tilt) * 30 most = lambda v: max(float(np.abs(v).max()), math.radians(1)) # (travel over all but its fastest two hundredth: one camera placed a hand's width off makes a step several # times the walking speed, and the walking speed would be that step's) turn_rate, pitch_rate, speed = most(turning), most(tilting), max(float(np.percentile(np.hypot(forward, right), 99.5)), 0.05) fast = np.maximum(1.0, np.hypot(forward, right) / speed); forward, right = forward / fast, right / fast (build / "gamepad.jsonl").write_text("".join(json.dumps({ "frame": k, "time_ns": int(round(k * 1e9 / 30)), "buttons": [], "left_stick": [round(float(right[k] / speed), 5), round(float(-forward[k] / speed), 5)], "right_stick": [round(float(turning[k] / turn_rate), 5), round(float(-tilting[k] / pitch_rate), 5)]}) + "\n" for k in range(len(turning)))) return turn_rate, pitch_rate, speed def trace_from_cameras(build: Path, at, c2w, hfov_deg: float, eye_m: float) -> dict: """The inferred trace and controller numbers from cameras found for the frames at times ``at`` (seconds; each a 4x4 world-from-camera with axes right, down, ahead, in roughly metres). Up is what the cameras' right-hand axes all lie across (a player's camera does not roll); the first camera is taken to look level along -z.""" at, c2w = np.asarray(at, float), np.asarray(c2w, float) across = c2w[:, :3, 0]; _values, vectors = np.linalg.eigh(across.T @ across); up = vectors[:, 0] if np.ptp(across, axis=0).max() < 0.2: # it hardly turned: the first camera's own up up = -c2w[0, :3, 1] up = up if up @ -c2w[:, :3, 1].mean(0) > 0 else -up ahead0 = c2w[0, :3, 2] - (c2w[0, :3, 2] @ up) * up; ahead0 /= np.linalg.norm(ahead0); right0 = np.cross(ahead0, up) # (x right, y down, z ahead: ahead x up = right) looks = c2w[:, :3, 2]; facing = np.unwrap(np.arctan2(looks @ right0, looks @ ahead0)); tilt = np.arcsin(np.clip(looks @ up, -1, 1)) place = c2w[:, :3, 3] - c2w[0, :3, 3]; x, z = place @ right0, -(place @ ahead0) grid = np.arange(int(at[-1] * 30) + 1) / 30 facing, tilt, x, z = (np.interp(grid, at, v) - v[0] for v in (facing, tilt, x, z)) vx, vz = np.diff(x) * 30, np.diff(z) * 30 turn_rate, pitch_rate, speed = write_trace(build, facing, tilt, vx * np.sin(facing[1:]) - vz * np.cos(facing[1:]), vx * np.cos(facing[1:]) + vz * np.sin(facing[1:])) return {"hfov_deg": round(float(hfov_deg), 3), "eye_m": eye_m, "turn_deg_s": round(math.degrees(turn_rate), 3), "pitch_deg_s": round(math.degrees(pitch_rate), 3), "walk_m_s": round(speed, 3), "response_per_s": 30, "look_response_per_s": 30, "lead_frames": -1.0, "keys": {}, "stick_dead": 0.0, "stick_power": 1.0, "stick_signs": [1, 1, 1, 1], "inferred": True} def ray(c, pose, px, py): """World direction through pixel (px, py) for a three.js camera with rotation (pitch, -yaw, 0, 'YXZ').""" f = (W / 2) / math.tan(math.radians(c["hfov_deg"]) / 2) d = np.array([px - W / 2, -(py - H / 2), -f], float) _t, _x, _y, _z, yaw, pitch = pose cp, sp, cy, sy = math.cos(pitch), math.sin(pitch), math.cos(-yaw), math.sin(-yaw) d = np.array([d[0], d[1] * cp - d[2] * sp, d[1] * sp + d[2] * cp]) # about x by pitch return np.array([d[0] * cy + d[2] * sy, d[1], -d[0] * sy + d[2] * cy]) # about y by -yaw def at(rows, t): return rows[min(len(rows) - 1, max(0, int(round(t * 30))))] def floor_point(c, pose, px, py): d = ray(c, pose, px, py) if d[1] >= -1e-6: return None k = -pose[2] / d[1] return pose[1] + k * d[0], pose[3] + k * d[2] def grab(build: Path, t: float, out: Path): subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-ss", f"{t:.3f}", "-i", str(build / "recording.mp4"), "-frames:v", "1", "-q:v", "2", str(out)], check=True) def main(): if len(sys.argv) < 4: print(__doc__); return build, command, t = Path(sys.argv[1]).resolve(), sys.argv[2], float(sys.argv[3]) frame_size(build) pair = lambda text: tuple(float(v) for v in text.split(",")) if command == "frame": grab(build, t, Path(sys.argv[4])); print(sys.argv[4]); return if command == "texture": from PIL import Image corners = [pair(a) for a in sys.argv[4:8]] out = Path(sys.argv[8]) edge = lambda a, b: math.dist(corners[a], corners[b]) size = (int(sys.argv[9]), int(sys.argv[10])) if len(sys.argv) > 10 else ( max(8, int(round(max(edge(0, 1), edge(3, 2))))), max(8, int(round(max(edge(0, 3), edge(1, 2)))))) tmp = out.with_suffix(".frame.jpg"); grab(build, t, tmp) quad = [v for corner in (corners[0], corners[3], corners[2], corners[1]) for v in corner] # PIL: TL, BL, BR, TR Image.open(tmp).transform(size, Image.Transform.QUAD, quad, Image.Resampling.BICUBIC).save(out); tmp.unlink() print(f"{out} {size[0]}x{size[1]}"); return c, rows = poses(build, t) pose = at(rows, t) if command == "pose": print(json.dumps({"t": round(pose[0], 3), "position": [round(pose[1], 3), round(pose[2], 3), round(pose[3], 3)], "yaw_deg": round(math.degrees(pose[4]), 2), "pitch_deg": round(math.degrees(pose[5]), 2)})) elif command == "floor": for text in sys.argv[4:]: p = floor_point(c, pose, *pair(text)) print(text, "->", "not on the floor (the ray points at or above the horizon)" if p is None else f"x {p[0]:.2f}, z {p[1]:.2f}") elif command == "up": top, base = pair(sys.argv[4]), pair(sys.argv[5]) p = floor_point(c, pose, *base) if p is None: print("the base pixel is not on the floor"); return d = ray(c, pose, *top) reach = math.hypot(p[0] - pose[1], p[1] - pose[3]) / max(1e-9, math.hypot(d[0], d[2])) print(f"base x {p[0]:.2f}, z {p[1]:.2f}; height {pose[2] + reach * d[1]:.2f} m") else: print(__doc__) if __name__ == "__main__": main()