File size: 29,483 Bytes
a3e20d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#!/usr/bin/env python3
"""Visualize a synchronized ZED + Homie + OptiTrack/SMPL-X data case in Rerun."""

from __future__ import annotations

import argparse
import csv
import json
import os
import socket
import struct
import subprocess
import time
import xml.etree.ElementTree as ET
from pathlib import Path

import cv2
import numpy as np
import rerun as rr
import rerun.blueprint as rrb
import yaml

HERE = Path(__file__).resolve().parent
DEFAULT_CASE = Path("/mnt/Datasets/2026-06-27-12:26:35")
HOMIE_NAMES = ("front_left", "front_right", "back_left", "back_right")
HOMIE_VIDEO = {
    "front_left": "homie_front_left.mp4",
    "front_right": "homie_front_right.mp4",
    "back_left": "homie_back_left.mp4",
    "back_right": "homie_back_right.mp4",
}
HOMIE_CAMCHAIN = {
    "front_left": "cam0", "front_right": "cam1",
    "back_left": "cam2", "back_right": "cam3",
}


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    p.add_argument("case", nargs="?", type=Path, default=DEFAULT_CASE)
    p.add_argument("--zed-calib", type=Path, default=HERE / "config/zed_poses_0622.json")
    p.add_argument("--homie-calib", type=Path, default=HERE / "config/homie_rig_calib.json")
    p.add_argument("--homie-camchain", type=Path, default=HERE / "config/homie-camchain.yaml")
    p.add_argument("--zed", default="0,1,2,3,4,5,6,7", help="ZED camera indices, or empty")
    p.add_argument("--homie", default="front_left", help="Homie camera names, or empty")
    p.add_argument("--optitrack-calib", type=Path, default=HERE / "config/Calibration-Exported.mcal")
    p.add_argument("--assets-dir", type=Path,
                   default=Path("/home/acerobotics/Datasets/mesh_alignmend/aligned_textured"),
                   help="room OBJ asset directory (flat *.obj or <name>/mesh.obj layout)")
    p.add_argument("--no-room-assets", dest="no_room_assets", action="store_true", default=False,
                   help="do not load room assets")
    p.add_argument("--room-assets", dest="no_room_assets", action="store_false",
                   help="explicitly enable room asset loading")
    p.add_argument("--enable-room-alignment", dest="enable_room_alignment", action="store_true", default=True,
                   help="enable floor/center alignment and CLI room offsets (default)")
    p.add_argument("--no-room-alignment", dest="enable_room_alignment", action="store_false",
                   help="disable floor/center alignment and CLI room offsets")
    p.add_argument("--enable-room-controls", dest="enable_room_controls", action="store_true", default=True,
                   help="launch live room translation/rotation controls (default)")
    p.add_argument("--no-room-controls", dest="enable_room_controls", action="store_false",
                   help="disable live room transform controls")
    p.add_argument("--asset-floor-z", type=float, default=-1.62, help="floor Z in the source Z-up OBJ coordinates")
    p.add_argument("--asset-translation", type=float, nargs=3, default=(0.12, -0.52, 0.79), metavar=("DX", "DY", "DZ"),
                   help="additional room translation in OptiTrack world meters")
    p.add_argument("--asset-rotation-deg", type=float, nargs=3, default=(0.0, 62.0, 0.0), metavar=("RX", "RY", "RZ"),
                   help="additional room rotation about world X/Y/Z in degrees")
    p.add_argument("--no-auto-asset-align", action="store_true", help="disable horizontal room/camera center alignment")
    p.add_argument("--start", type=float, default=0.0, help="start time in OptiTrack seconds")
    p.add_argument("--duration", type=float, default=None)
    p.add_argument("--mesh-fps", type=float, default=15.0,
                   help="(unused; SMPL is logged as a single static pose at --start)")
    p.add_argument("--no-video", action="store_true")
    p.add_argument("--full-video", action="store_true", help="embed complete MP4 assets instead of one RGB frame per camera")
    p.add_argument("--no-smpl", action="store_true")
    p.add_argument("--save", type=Path, help="write an .rrd instead of spawning the viewer")
    p.add_argument("--connect", metavar="URL", help="connect to an existing Rerun server, e.g. rerun+http://127.0.0.1:9876/proxy")
    p.add_argument("--grpc-port", type=int, default=9876, help="Rerun data proxy port (only with --connect)")
    p.add_argument("--web-port", type=int, default=9090, help="headless Web Viewer HTTP port")
    p.add_argument("--control-port", type=int, default=None, help="room-alignment UI port; default web-port + 2")
    p.add_argument("--server-memory", default="8GiB", help="Rerun proxy cache limit")
    return p.parse_args()


def kill_orphaned_viewers() -> None:
    """Terminate leftover rerun servers from previous runs of this script.

    They are detached (start_new_session), so they outlive a crashed or
    Ctrl+C'd parent and then squat on the ports. A process serving our own
    /tmp/multicam_optitrack_smpl_*.rrd is killed unless some ancestor is a
    still-running visualize_case.py (i.e. an active sibling session).
    """
    import signal

    def ppid_of(pid: int) -> int:
        try:
            return int(Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[1])
        except (OSError, IndexError, ValueError):
            return 0

    def has_live_owner(pid: int) -> bool:
        seen = 0
        while pid > 1 and seen < 20:
            try:
                argv = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")
            except OSError:
                return False
            if pid != os.getpid() and any(a.endswith(b"visualize_case.py") for a in argv):
                return True
            pid, seen = ppid_of(pid), seen + 1
        return False

    for pid_dir in Path("/proc").glob("[0-9]*"):
        pid = int(pid_dir.name)
        if pid == os.getpid():
            continue
        try:
            argv = (pid_dir / "cmdline").read_bytes().split(b"\0")
        except OSError:
            continue
        # exact-argument match so shells whose command text merely quotes
        # these strings are never touched
        serves_our_rrd = any(a.startswith(b"/tmp/multicam_optitrack_smpl_")
                             and a.endswith(b".rrd") for a in argv)
        if (serves_our_rrd and b"--serve-web" in argv
                and not has_live_owner(pid)):
            print(f"Stopping orphaned Rerun viewer (pid {pid})")
            try:
                os.kill(pid, signal.SIGTERM)
            except OSError:
                pass
    time.sleep(0.5)


def start_headless_server(recording: Path, web_port: int, server_memory: str) -> subprocess.Popen:
    """Start the web viewer on a completed RRD; no transient gRPC stream involved."""
    executable = Path(__file__).resolve().parent / ".venv/bin/rerun"
    if not executable.is_file():
        raise FileNotFoundError(f"Rerun CLI not found at {executable}; install requirements in .venv")
    with socket.socket() as check:
        if check.connect_ex(("127.0.0.1", web_port)) == 0:
            kill_orphaned_viewers()
    with socket.socket() as check:
        if check.connect_ex(("127.0.0.1", web_port)) == 0:
            raise RuntimeError(f"Port {web_port} is already in use. Re-run with --web-port {web_port + 1}")
    # Rerun's web app still fetches data through this proxy. Keep it predictable for SSH.
    proxy_port = web_port + 1
    with socket.socket() as check:
        if check.connect_ex(("127.0.0.1", proxy_port)) == 0:
            raise RuntimeError(f"Proxy port {proxy_port} is already in use. Choose another --web-port")
    proc = subprocess.Popen(
        [str(executable), str(recording), "--serve-web", "--bind", "127.0.0.1",
         "--port", str(proxy_port), "--web-viewer-port", str(web_port),
         "--server-memory-limit", server_memory],
        start_new_session=True,
    )
    deadline = time.monotonic() + 15.0
    while time.monotonic() < deadline:
        if proc.poll() is not None:
            raise RuntimeError("Rerun Web Viewer exited during startup; run .venv/bin/rerun --serve-web to inspect its error")
        try:
            with socket.create_connection(("127.0.0.1", web_port), timeout=0.2):
                return proc
        except OSError:
            time.sleep(0.1)
    proc.terminate()
    raise TimeoutError(f"Rerun Web Viewer did not open port {web_port}")


def rotation_xyz_deg(rx: float, ry: float, rz: float) -> np.ndarray:
    x, y, z = np.radians([rx, ry, rz])
    cx, sx, cy, sy, cz, sz = np.cos(x), np.sin(x), np.cos(y), np.sin(y), np.cos(z), np.sin(z)
    Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]])
    Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]])
    Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]])
    return Rz @ Ry @ Rx


def launch_alignment_ui(base_translation: np.ndarray, room_R: np.ndarray, proxy_port: int,
                        control_port: int, recording_id: str):
    import gradio as gr
    stream = rr.RecordingStream("multicam_optitrack_smpl", recording_id=recording_id)
    stream.connect_grpc(f"rerun+http://127.0.0.1:{proxy_port}/proxy")

    counter = [0]

    def update(dx: float, dy: float, dz: float, rx: float, ry: float, rz: float) -> str:
        delta = np.array([dx, dy, dz], float)
        total = base_translation + delta
        total_R = rotation_xyz_deg(rx, ry, rz) @ room_R
        rr.log("world/room", rr.Transform3D(translation=total, mat3x3=total_R), static=True, recording=stream)
        stream.flush()
        counter[0] += 1
        return (f"已发送更新 #{counter[0]}\n\n"
                f"总平移: [{total[0]:.3f}, {total[1]:.3f}, {total[2]:.3f}] m  "
                f"附加旋转: [{rx:.1f}, {ry:.1f}, {rz:.1f}]°\n\n"
                f"启动参数: `--asset-translation {dx:.3f} {dy:.3f} {dz:.3f} "
                f"--asset-rotation-deg {rx:.1f} {ry:.1f} {rz:.1f}`")

    with gr.Blocks(title="Room alignment") as demo:
        gr.Markdown("# 房间 Mesh 平移微调\n滑块表示叠加在自动对齐结果上的偏移(米)。松开滑块后更新 Rerun。")
        x = gr.Slider(-5, 5, value=0, step=0.01, label="X 平移 / m")
        y = gr.Slider(-5, 5, value=0, step=0.01, label="Y 平移 / m")
        z = gr.Slider(-5, 5, value=0, step=0.01, label="Z 平移 / m")
        with gr.Row():
            rx = gr.Slider(-180, 180, value=0, step=1, label="绕 X 旋转 / °")
            ry = gr.Slider(-180, 180, value=0, step=1, label="绕 Y 旋转 / °")
            rz = gr.Slider(-180, 180, value=0, step=1, label="绕 Z 旋转 / °")
        controls = [x, y, z, rx, ry, rz]
        status = gr.Markdown(update(0, 0, 0, 0, 0, 0))
        for slider in controls:
            slider.release(update, inputs=controls, outputs=status, show_progress="hidden")
        gr.Button("应用数值", variant="primary").click(update, inputs=controls, outputs=status, show_progress="hidden")
    demo.launch(server_name="127.0.0.1", server_port=control_port, prevent_thread_lock=True, quiet=True)
    return demo, stream


def load_obj(path: Path) -> tuple[np.ndarray, np.ndarray]:
    vertices, faces = [], []
    with path.open() as f:
        for line in f:
            if line.startswith("v "):
                vertices.append([float(x) for x in line.split()[1:4]])
            elif line.startswith("f "):
                idx = [int(x.split("/")[0]) - 1 for x in line.split()[1:]]
                for i in range(1, len(idx) - 1):
                    faces.append([idx[0], idx[i], idx[i + 1]])
    return np.asarray(vertices, np.float32), np.asarray(faces, np.uint32)


def obj_collection_bounds(paths: list[Path]) -> tuple[np.ndarray, np.ndarray]:
    lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
    for path in paths:
        with path.open(errors="ignore") as f:
            for line in f:
                if line.startswith("v "):
                    v = np.fromstring(line[2:], sep=" ", count=3)
                    if len(v) == 3:
                        lo, hi = np.minimum(lo, v), np.maximum(hi, v)
    if not np.isfinite(lo).all():
        raise ValueError("No OBJ vertices found for room alignment")
    return lo, hi


def open_pc2(path: Path) -> tuple[np.memmap, float]:
    with path.open("rb") as f:
        if f.read(12) != b"POINTCACHE2\0":
            raise ValueError(f"Not a POINTCACHE2 file: {path}")
        version, points, start, rate, frames = struct.unpack("<iiffi", f.read(20))
    if version != 1 or path.stat().st_size != 32 + frames * points * 12:
        raise ValueError(f"Invalid PC2 header/size: {path}")
    return np.memmap(path, dtype="<f4", mode="r", offset=32, shape=(frames, points, 3)), rate


def read_homie_poses(path: Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    data = np.genfromtxt(path, delimiter=",", names=True, skip_header=1)
    frames = data["frame"].astype(np.int64)
    pos_m = np.column_stack([data["Homie_px"], data["Homie_py"], data["Homie_pz"]]) / 1000.0
    quat = np.column_stack([data["Homie_qx"], data["Homie_qy"], data["Homie_qz"], data["Homie_qw"]])
    return frames, pos_m, quat


def quat_xyzw_to_mat(q: np.ndarray) -> np.ndarray:
    q = q / np.linalg.norm(q)
    x, y, z, w = q
    return np.array([
        [1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)],
        [2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)],
        [2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)],
    ])


def euler_rotation(pitch: float, yaw: float, roll: float) -> np.ndarray:
    p, y, r = np.radians([pitch, yaw, roll])
    cp, sp, cy, sy, cr, sr = np.cos(p), np.sin(p), np.cos(y), np.sin(y), np.cos(r), np.sin(r)
    return np.array([[cr*cy, cr*sy*sp-sr*cp, cr*sy*cp+sr*sp],
                     [sr*cy, sr*sy*sp+cr*cp, sr*sy*cp-cr*sp],
                     [-sy, cy*sp, cy*cp]])


def homie_rectification(camchain_path: Path) -> tuple[dict[str, np.ndarray], np.ndarray]:
    cc = yaml.safe_load(camchain_path.read_text())
    # Matches the parameters recorded in this case's rectify_report.json.
    out, fov, zoom = 1024, 90.0, 0.78125
    focal = out / (2 * np.tan(np.radians(fov) / 2)) * zoom
    K = np.array([[focal, 0, out/2], [0, focal, out/2], [0, 0, 1.0]])
    view = euler_rotation(-5.0, 0.0, 0.0)
    result = {}
    pairs = (("cam0", "front_left", "cam1", "front_right"),
             ("cam2", "back_left", "cam3", "back_right"))
    for lk, ln, rk, rn in pairs:
        def kd(key: str):
            c = cc[key]; fx, fy, cx, cy = c["intrinsics"]
            return np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1.0]]), np.asarray(c["distortion_coeffs"])
        K0, D0 = kd(lk); K1, D1 = kd(rk)
        T = np.asarray(cc[rk]["T_cn_cnm1"], float)
        size = tuple(map(int, cc[lk]["resolution"]))
        R1, R2, *_ = cv2.fisheye.stereoRectify(K0, D0, K1, D1, size, T[:3, :3], T[:3, 3],
                                                flags=cv2.CALIB_ZERO_DISPARITY, newImageSize=size,
                                                balance=0.0, fov_scale=1.0)
        result[ln], result[rn] = view @ R1, view @ R2
    return result, K


def log_video(path: str, video_path: Path, origin_s: float) -> None:
    asset = rr.AssetVideo(path=video_path)
    rr.log(path, asset, static=True)
    stamps = asset.read_frame_timestamps_nanos()
    rr.send_columns(path,
        indexes=[rr.TimeColumn("time", duration=origin_s + stamps * 1e-9)],
        columns=rr.VideoFrameReference.columns_nanos(stamps))


def log_video_frame(path: str, video_path: Path, origin_s: float, requested_time_s: float,
                    flip_vertical: bool = False) -> None:
    """Log one JPEG frame, avoiding transfer of the complete MP4 asset."""
    sample_time = max(requested_time_s, origin_s)
    cap = cv2.VideoCapture(str(video_path))
    cap.set(cv2.CAP_PROP_POS_MSEC, max(0.0, sample_time - origin_s) * 1000.0)
    ok, frame = cap.read()
    cap.release()
    if not ok:
        raise RuntimeError(f"Could not decode RGB frame from {video_path} at {sample_time - origin_s:.3f}s")
    if flip_vertical:
        frame = cv2.flip(frame, 0)
    ok, encoded = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 90])
    if not ok:
        raise RuntimeError(f"Could not JPEG-encode frame from {video_path}")
    rr.set_time("time", duration=sample_time)
    rr.log(path, rr.EncodedImage(contents=encoded.tobytes(), media_type="image/jpeg"))


def rotation_midpoint(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    """Closest proper rotation to the equal-weight mean of two rotations."""
    u, _, vt = np.linalg.svd(a + b)
    d = np.eye(3); d[-1, -1] = np.linalg.det(u @ vt)
    return u @ d @ vt


def load_optitrack_cameras(path: Path) -> dict[int, dict]:
    root = ET.fromstring(path.read_bytes().decode("utf-16"))
    gl_to_cv = np.diag([1.0, -1.0, -1.0])
    cameras = {}
    for cam in root.findall(".//Camera"):
        props, intr, extr = cam.find("Properties"), cam.find("IntrinsicStandardCameraModel"), cam.find("Extrinsic")
        if props is None or intr is None or extr is None:
            continue
        cid = int(props.attrib["CameraID"])
        fx, fy = float(intr.attrib["HorizontalFocalLength"]), float(intr.attrib["VerticalFocalLength"])
        cx, cy = float(intr.attrib["LensCenterX"]), float(intr.attrib["LensCenterY"])
        R = np.array([float(extr.attrib[f"OrientMatrix{i}"]) for i in range(9)]).reshape(3, 3) @ gl_to_cv
        t = np.array([float(extr.attrib[k]) for k in ("X", "Y", "Z")]) * 1000.0
        T = np.eye(4); T[:3, :3], T[:3, 3] = R, t
        cameras[cid] = {"T_c2w": T, "K": np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1.0]]),
                        "width": 2048, "height": 1088, "serial": cam.attrib.get("Serial", "")}
    return cameras


def log_camera_static(path: str, T_c2w: np.ndarray, K: np.ndarray, width: int, height: int,
                      color: tuple[int, int, int]) -> None:
    rr.log(path, rr.Transform3D(translation=T_c2w[:3, 3] / 1000.0, mat3x3=T_c2w[:3, :3]), static=True)
    rr.log(path, rr.Pinhole(image_from_camera=K, width=width, height=height,
                            camera_xyz=rr.ViewCoordinates.RDF, image_plane_distance=0.32,
                            color=color), static=True)


def blueprint(zed: list[str], homie: list[str]) -> rrb.Blueprint:
    video_views = [rrb.Spatial2DView(name=f"ZED {c}", origin=f"world/cameras/zed/cam{c}") for c in zed]
    video_views += [rrb.Spatial2DView(name=f"Homie {c}", origin=f"world/cameras/homie/{c}") for c in homie]
    videos = rrb.Grid(*video_views, grid_columns=2) if video_views else rrb.TextLogView()
    return rrb.Blueprint(rrb.Horizontal(
        rrb.Spatial3DView(name="All cameras + SMPL", origin="world", contents=["world/**"],
                          background=[41, 43, 38]),  # matches calibration_sz.png backdrop
        videos, column_shares=[2, 1]), collapse_panels=True)


def main() -> None:
    args = parse_args(); case = args.case.resolve()
    server_proc = None
    alignment_ui = alignment_stream = None
    room_base_translation = room_rotation = None
    recording_id = "multicam-optitrack-smpl-room-control"
    web_rrd = None
    zed_ids = [x.strip() for x in args.zed.split(",") if x.strip()]
    homie_ids = [x.strip() for x in args.homie.split(",") if x.strip()]
    unknown = set(homie_ids) - set(HOMIE_NAMES)
    if unknown: raise ValueError(f"Unknown Homie cameras: {sorted(unknown)}")
    if args.save and args.connect:
        raise ValueError("--save and --connect are mutually exclusive")
    rr.init("multicam_optitrack_smpl", recording_id=recording_id, spawn=False)
    if args.save:
        rr.save(args.save)
    elif args.connect:
        rr.connect_grpc(args.connect)
    else:
        web_rrd = Path(f"/tmp/multicam_optitrack_smpl_{os.getpid()}.rrd")
        rr.save(web_rrd)
    rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Y_UP, static=True)
    rr.log("world/origin", rr.TransformAxes3D(axis_length=0.5), static=True)

    zc = json.loads(args.zed_calib.read_text())["cameras"]

    if not args.no_room_assets and args.assets_dir.is_dir():
        # Source meshes are globally placed in a Z-up reconstruction. Convert
        # (x,y,z)_src -> (x,z,-y)_world and lift their source floor to Y=0.
        axis_R = np.array([[1, 0, 0], [0, 0, 1], [0, -1, 0]], dtype=float)
        room_R = axis_R.copy()
        excluded_assets = {"scene.obj", "table_cook.obj"}
        # New layout: aligned_textured/<name>/mesh.glb (textures embedded;
        # Asset3D cannot resolve an OBJ's external .mtl/.png). Fall back to
        # <name>/mesh.obj, then to the legacy flat *.obj layout.
        parts = sorted(args.assets_dir.glob("*/mesh.glb"))
        if not parts:
            parts = sorted(args.assets_dir.glob("*/mesh.obj"))
        if not parts:
            parts = sorted(p for p in args.assets_dir.glob("*.obj") if p.name not in excluded_assets)
        objects = parts
        translation = np.zeros(3)
        if args.enable_room_alignment:
            room_R = rotation_xyz_deg(*args.asset_rotation_deg) @ axis_R
            translation = np.array([0.0, -args.asset_floor_z, 0.0]) + np.asarray(args.asset_translation)
        if args.enable_room_alignment and objects and not args.no_auto_asset_align:
            # bounds parser reads OBJ text; GLB entries use their sibling OBJ
            bounds_paths = [p.with_suffix(".obj") if p.suffix == ".glb" else p for p in objects]
            lo, hi = obj_collection_bounds(bounds_paths)
            room_center_world = room_R @ ((lo + hi) * 0.5)
            camera_positions = np.array([np.asarray(c["T_c2w"], float)[:3, 3] / 1000.0 for c in zc.values()])
            camera_center = (camera_positions.min(axis=0) + camera_positions.max(axis=0)) * 0.5
            translation[[0, 2]] += camera_center[[0, 2]] - room_center_world[[0, 2]]
            print(f"Auto room alignment translation: {translation.round(3).tolist()} m")
        rr.log("world/room", rr.Transform3D(translation=translation, mat3x3=room_R), static=True)
        if args.enable_room_controls:
            room_base_translation, room_rotation = translation.copy(), room_R.copy()
        palette = [(230, 92, 92), (239, 158, 64), (230, 205, 80), (86, 190, 116),
                   (65, 185, 205), (78, 135, 225), (145, 105, 210), (215, 95, 175),
                   (155, 115, 82), (120, 175, 155)]
        for i, obj in enumerate(objects):
            # <name>/mesh.glb|obj carries its own texture: log untinted.
            # Legacy untextured flat OBJs keep the palette tint.
            textured = obj.name in ("mesh.glb", "mesh.obj")
            name = obj.parent.name if textured else obj.stem
            if textured:
                rr.log(f"world/room/objects/{name}", rr.Asset3D(path=obj), static=True)
            else:
                rr.log(f"world/room/objects/{name}",
                       rr.Asset3D(path=obj, albedo_factor=palette[i % len(palette)]), static=True)

    zed_color = (60, 220, 90)
    for cid in zed_ids:
        c = zc[cid]; path = f"world/cameras/zed/cam{cid}"
        log_camera_static(path, np.asarray(c["T_c2w"]), np.asarray(c["K"]), c["width"], c["height"], zed_color)

    for cid, c in load_optitrack_cameras(args.optitrack_calib).items():
        log_camera_static(f"world/cameras/optitrack/cam{cid}", c["T_c2w"], c["K"], c["width"], c["height"], (65, 135, 255))

    rig = json.loads(args.homie_calib.read_text())["T_homie_cam"]
    Rrect, Kh = homie_rectification(args.homie_camchain)
    frames, positions, quats = read_homie_poses(case / "objects/rb_Homie.csv")
    end = np.inf if args.duration is None else args.start + args.duration

    def homie_cam_T(Twh: np.ndarray, cam: str) -> np.ndarray:
        if cam == "front_left":
            Tl = Twh @ np.asarray(rig["front_left"], float)
            Tr = Twh @ np.asarray(rig["front_right"], float)
            Tl[:3, :3] = Tl[:3, :3] @ Rrect["front_left"].T
            Tr[:3, :3] = Tr[:3, :3] @ Rrect["front_right"].T
            T = np.eye(4)
            T[:3, 3] = (Tl[:3, 3] + Tr[:3, 3]) * 0.5
            T[:3, :3] = rotation_midpoint(Tl[:3, :3], Tr[:3, :3])
            return T
        T = Twh @ np.asarray(rig[cam], float)
        T[:3, :3] = T[:3, :3] @ Rrect[cam].T
        return T

    if args.full_video:
        # animated rig: poses follow the timeline alongside the videos
        keep = (frames / 60.0 >= args.start) & (frames / 60.0 <= end)
        for frame, pos, quat in zip(frames[keep], positions[keep], quats[keep]):
            rr.set_time("time", duration=float(frame) / 60.0)
            Rwh = quat_xyzw_to_mat(quat)
            rr.log("world/optitrack/homie_rigid_body", rr.Transform3D(translation=pos, mat3x3=Rwh))
            rr.log("world/optitrack/homie_rigid_body", rr.TransformAxes3D(axis_length=0.25))
            Twh = np.eye(4); Twh[:3, :3], Twh[:3, 3] = Rwh, pos * 1000.0
            for cam in homie_ids:
                T = homie_cam_T(Twh, cam)
                rr.log(f"world/cameras/homie/{cam}", rr.Transform3D(translation=T[:3, 3]/1000.0, mat3x3=T[:3, :3]))
    else:
        # static snapshot at --start, consistent with the static human and the
        # single logged video frames
        i = int(np.argmin(np.abs(frames / 60.0 - args.start)))
        Rwh = quat_xyzw_to_mat(quats[i])
        rr.log("world/optitrack/homie_rigid_body",
               rr.Transform3D(translation=positions[i], mat3x3=Rwh), static=True)
        rr.log("world/optitrack/homie_rigid_body", rr.TransformAxes3D(axis_length=0.25), static=True)
        Twh = np.eye(4); Twh[:3, :3], Twh[:3, 3] = Rwh, positions[i] * 1000.0
        for cam in homie_ids:
            T = homie_cam_T(Twh, cam)
            rr.log(f"world/cameras/homie/{cam}",
                   rr.Transform3D(translation=T[:3, 3]/1000.0, mat3x3=T[:3, :3]), static=True)
    for cam in homie_ids:
        rr.log(f"world/cameras/homie/{cam}", rr.Pinhole(image_from_camera=Kh, width=1024, height=1024,
            camera_xyz=rr.ViewCoordinates.RDF, image_plane_distance=0.24, color=(255, 105, 55)), static=True)

    if not args.no_video:
        export = json.loads((case / "videos/export_info.json").read_text())
        origins = {v["file"]: float(v["start_optitrack_time_s"]) for v in export["videos"]}
        for cid in zed_ids:
            name = f"zed_cam{cid}.mp4"; path = f"world/cameras/zed/cam{cid}/rgb"
            if args.full_video: log_video(path, case/"videos"/name, origins[name])
            else: log_video_frame(path, case/"videos"/name, origins[name], args.start, flip_vertical=True)
        for cam in homie_ids:
            name = HOMIE_VIDEO[cam]; path = f"world/cameras/homie/{cam}/rgb"
            if args.full_video: log_video(path, case/"videos"/name, origins[name])
            else: log_video_frame(path, case/"videos"/name, origins[name], args.start)

    if not args.no_smpl:
        # Static single pose at --start: the Homie rig does not follow the
        # human, so animating the SMPL mesh only inflates the recording.
        _, faces = load_obj(case / "viz/human/poses_template.obj")
        verts, source_fps = open_pc2(case / "viz/human/poses_motion.pc2")
        i = min(len(verts) - 1, max(0, int(round(args.start * source_fps))))
        rr.log("world/human/smplx", rr.Mesh3D(vertex_positions=verts[i], triangle_indices=faces,
                                               vertex_colors=(115, 170, 255, 210)), static=True)
    rr.send_blueprint(blueprint(zed_ids, homie_ids))
    print("Rerun logging complete.")
    if web_rrd is not None:
        rr.disconnect()
        server_proc = start_headless_server(web_rrd, args.web_port, args.server_memory)
        print(f"Headless Web Viewer loaded {web_rrd}.")
        proxy_port = args.web_port + 1
        control_port = args.control_port
        if control_port is None:  # first free port from web_port+2
            for candidate in range(args.web_port + 2, args.web_port + 22):
                with socket.socket() as check:
                    if check.connect_ex(("127.0.0.1", candidate)) != 0:
                        control_port = candidate
                        break
            else:
                raise RuntimeError("No free control port found; pass --control-port")
        if room_base_translation is not None:
            alignment_ui, alignment_stream = launch_alignment_ui(
                room_base_translation, room_rotation, proxy_port, control_port, recording_id)
        print("On your LOCAL machine run:")
        forwards = f"-L {args.web_port}:127.0.0.1:{args.web_port} -L {proxy_port}:127.0.0.1:{proxy_port}"
        if alignment_ui is not None:
            forwards += f" -L {control_port}:127.0.0.1:{control_port}"
        print(f"  ssh -N {forwards} acerobotics@SERVER")
        print("Then open:")
        print(f"  http://127.0.0.1:{args.web_port}?url=rerun%3A%2F%2Flocalhost%3A{proxy_port}%2Fproxy")
        if alignment_ui is not None:
            print(f"Room alignment controls: http://127.0.0.1:{control_port}")
    if server_proc is not None:
        print("Web Viewer is ready. Keep this process running; press Ctrl+C after viewing.")
        try:
            server_proc.wait()
        except KeyboardInterrupt:
            print("\nStopping Web Viewer...")
            if alignment_ui is not None:
                alignment_ui.close()
            server_proc.terminate()
            try:
                server_proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                server_proc.kill()


if __name__ == "__main__":
    main()