File size: 18,141 Bytes
3f4bb1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Run SONIC v1.1 whole-body ONNX on a reconstruction clip (G1 29-DoF).

``G1_MINIMAL_CFG`` is the locomotion USD (wrong joint set). SONIC tracks the
29-DoF G1 (``G1_29DOF_CFG`` / GR00T cylinder G1): waist yaw/roll/pitch and
wrist roll/pitch/yaw, no Inspire mimic joints.

The DexYCB clip is a tabletop hand. Encoder **teleop** mode uses standing
legs + reconstructed right-hand root as the right-wrist target. The coffee
can is spawned on the table from ``isaaclab_replay.npz``.

  cd simulation
  ./replay_sonic.sh --headless \\
      --npz ../reconstruction/runs/20200709_141754_836212060125/obj_tracking_out/isaaclab_replay.npz
"""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path

from isaaclab.app import AppLauncher

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(line_buffering=True)

_PROJECT = Path(__file__).resolve().parents[2]
_DEFAULT_CLIP = (
    _PROJECT
    / "reconstruction"
    / "runs"
    / "20200709_141754_836212060125"
    / "obj_tracking_out"
    / "isaaclab_replay.npz"
)
_DEFAULT_CKPT = _PROJECT / "checkpoints" / "sonic" / "sonic_v1_1"

parser = argparse.ArgumentParser(description="SONIC v1.1 play on a v2d reconstruction clip.")
parser.add_argument("--npz", type=Path, default=_DEFAULT_CLIP)
parser.add_argument("--checkpoint", type=Path, default=_DEFAULT_CKPT)
parser.add_argument("--mode", choices=("teleop", "g1"), default="teleop")
parser.add_argument("--output", type=Path, default=None)
parser.add_argument("--table-z", type=float, default=0.75)
parser.add_argument("--robot-x", type=float, default=0.0, help="pelvis x; 0 matches the manip env")
parser.add_argument("--object-x", type=float, default=0.36, help="object rest x in the pelvis frame")
parser.add_argument("--object-y", type=float, default=-0.20, help="object rest y; right-hand workspace")
parser.add_argument("--max-steps", type=int, default=None)
parser.add_argument(
    "--hands",
    choices=("dex3", "inspire", "wuji"),
    default="dex3",
    help="dex3 = stock 3-finger (14 DoF); inspire = 5-finger (24 DoF), needs fetch_inspire_hand.py",
)
parser.add_argument(
    "--track-hand-orientation",
    action="store_true",
    help="feed the reconstructed MANO hand rotation as the right-wrist orientation target",
)
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()
args_cli.enable_cameras = True

app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app

import numpy as np  # noqa: E402
import torch  # noqa: E402

import isaaclab.sim as sim_utils  # noqa: E402
from isaaclab.assets import Articulation, RigidObject, RigidObjectCfg  # noqa: E402
from isaaclab.sensors.camera import Camera, CameraCfg  # noqa: E402
from isaaclab.sim import SimulationContext  # noqa: E402
from v2d_sim.sonic.robot_cfg import g1_sonic_articulation_cfg  # noqa: E402

from v2d_sim.sonic import (  # noqa: E402
    ACTION_CLIP,
    DEFAULT_ANGLES,
    G1_ACTION_SCALE,
    G1_SONIC_JOINT_NAMES,
    History,
    SonicOnnxAgent,
    load_clip_ref,
    pack_decoder,
    pack_encoder,
    vr3_local_from_bodies,
    vr3_local_targets,
)

_TABLE_SIZE = (0.80, 1.00, 0.05)
_TABLE_CENTER_X = 0.60
_CTRL_DT = 0.02
_SIM_DT = 0.005
_DECIMATION = 4


def _as_numpy(x) -> np.ndarray:
    if hasattr(x, "torch"):
        x = x.torch
    if isinstance(x, torch.Tensor):
        return x.detach().cpu().numpy()
    return np.asarray(x)


def _batch_row(x) -> np.ndarray:
    a = np.asarray(_as_numpy(x), dtype=np.float64)
    if a.ndim == 0:
        raise RuntimeError(f"empty sim tensor {type(x)}")
    if a.ndim >= 2:
        a = a[0]
    return a


def _wxyz_to_xyzw(wxyz: np.ndarray) -> np.ndarray:
    wxyz = np.asarray(wxyz, dtype=np.float64)
    return np.stack([wxyz[..., 1], wxyz[..., 2], wxyz[..., 3], wxyz[..., 0]], axis=-1)


def _xyzw_to_wxyz(xyzw: np.ndarray) -> np.ndarray:
    """Isaac Lab 3 reports ``*_quat_w`` as (x, y, z, w); SONIC math is wxyz.

    Reading these as wxyz turns identity into a 180 deg yaw, which makes the
    policy try to spin around.
    """
    xyzw = np.asarray(xyzw, dtype=np.float64)
    return np.stack([xyzw[..., 3], xyzw[..., 0], xyzw[..., 1], xyzw[..., 2]], axis=-1)


def _rgb_frame(camera: Camera) -> np.ndarray | None:
    try:
        out = camera.data.output
        rgb = out["rgb"] if isinstance(out, dict) or hasattr(out, "__getitem__") else out
        img = _as_numpy(rgb)
    except Exception:
        return None
    if img.size == 0:
        return None
    if img.ndim == 4:
        img = img[0]
    img = img[..., :3]
    if img.dtype != np.uint8:
        finite = img[np.isfinite(img)]
        peak = float(np.nanmax(finite)) if finite.size else 1.0
        scale = 255.0 if peak <= 1.5 else 1.0
        img = np.clip(img * scale, 0, 255).astype(np.uint8)
    h, w = img.shape[:2]
    return img[: h - (h % 2), : w - (w % 2)]


def _write_mp4(path: Path, frames: list[np.ndarray], fps: float) -> None:
    if not frames:
        raise RuntimeError("no frames captured")
    path.parent.mkdir(parents=True, exist_ok=True)
    try:
        import imageio.v2 as imageio

        imageio.mimsave(str(path), frames, fps=float(fps), codec="libx264", pixelformat="yuv420p")
        return
    except Exception as exc:
        print(f"[sonic] imageio h264 failed ({exc}); trying OpenCV", flush=True)
    import cv2

    h, w = frames[0].shape[:2]
    writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h))
    if not writer.isOpened():
        raise RuntimeError(f"could not open VideoWriter for {path}")
    for fr in frames:
        writer.write(cv2.cvtColor(fr, cv2.COLOR_RGB2BGR))
    writer.release()


def _spawn_table(xy: np.ndarray, table_top: float) -> None:
    """Kinematic slab. Legs at this depth collide with the G1 feet."""
    wood = sim_utils.PreviewSurfaceCfg(diffuse_color=(0.48, 0.34, 0.22))
    kin = sim_utils.RigidBodyPropertiesCfg(kinematic_enabled=True, disable_gravity=True)
    col = sim_utils.CollisionPropertiesCfg()
    mat = sim_utils.RigidBodyMaterialCfg(static_friction=0.9, dynamic_friction=0.7, restitution=0.0)
    lx, ly, thick = _TABLE_SIZE
    top = sim_utils.CuboidCfg(
        size=(lx, ly, thick),
        rigid_props=kin,
        mass_props=sim_utils.MassPropertiesCfg(mass=50.0),
        collision_props=col,
        visual_material=wood,
        physics_material=mat,
    )
    top.func(
        "/World/TableTop",
        top,
        translation=(float(xy[0]), float(xy[1]), float(table_top - 0.5 * thick)),
    )


def _object_cfg(urdf: str, prim: str, pos, rot_xyzw) -> RigidObjectCfg:
    return RigidObjectCfg(
        prim_path=prim,
        spawn=sim_utils.UrdfFileCfg(
            asset_path=urdf,
            fix_base=False,
            joint_drive=None,
            force_usd_conversion=True,
            collision_type="Convex Hull",
            mass_props=sim_utils.MassPropertiesCfg(mass=0.35),
            rigid_props=sim_utils.RigidBodyPropertiesCfg(
                disable_gravity=False,
                kinematic_enabled=False,
                linear_damping=0.05,
                angular_damping=0.05,
                max_depenetration_velocity=1.0,
            ),
            collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=True),
            physics_material=sim_utils.RigidBodyMaterialCfg(
                static_friction=1.1, dynamic_friction=0.9, restitution=0.0
            ),
        ),
        init_state=RigidObjectCfg.InitialStateCfg(pos=tuple(pos), rot=tuple(rot_xyzw)),
    )


def _g1_cfg(init_pos: tuple[float, float, float]):
    return g1_sonic_articulation_cfg("/World/Robot", init_pos=init_pos, hands=args_cli.hands)


def _stand_vr3_local(
    robot: Articulation, pelvis_pos: np.ndarray, pelvis_quat: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
    """VR 3-point pose of the current (standing) configuration, in the pelvis frame."""
    body_pos = np.asarray(_as_numpy(robot.data.body_pos_w), dtype=np.float64)
    body_quat = _xyzw_to_wxyz(np.asarray(_as_numpy(robot.data.body_quat_w), dtype=np.float64))
    if body_pos.ndim == 3:
        body_pos, body_quat = body_pos[0], body_quat[0]
    return vr3_local_from_bodies(robot.body_names, body_pos, body_quat, pelvis_pos, pelvis_quat)


def _joint_ids(robot: Articulation) -> np.ndarray:
    names = list(robot.joint_names)
    ids = []
    missing = []
    for n in G1_SONIC_JOINT_NAMES:
        if n not in names:
            missing.append(n)
        else:
            ids.append(names.index(n))
    if missing:
        raise RuntimeError(
            "SONIC joints missing on this USD (need 29-DoF G1, not g1_minimal): " + ", ".join(missing)
        )
    return np.asarray(ids, dtype=np.int64)


def main() -> None:
    npz_path = args_cli.npz.resolve()
    ckpt = args_cli.checkpoint.resolve()
    if not npz_path.is_file():
        raise SystemExit(f"missing {npz_path} — run retarget/export_isaaclab.sh first")
    if not (ckpt / "model_encoder.onnx").is_file():
        raise SystemExit(f"missing SONIC ONNX in {ckpt}")

    out_mp4 = (args_cli.output or (npz_path.parent / "sonic_replay.mp4")).resolve()

    ref = load_clip_ref(
        npz_path,
        table_xy=(_TABLE_CENTER_X, 0.0),
        table_z=float(args_cli.table_z),
        robot_xy=(float(args_cli.robot_x), 0.0),
        object_xy=(float(args_cli.object_x), float(args_cli.object_y)),
        pelvis_z=0.78,
    )
    agent = SonicOnnxAgent(ckpt)
    scale = np.asarray(G1_ACTION_SCALE, dtype=np.float64)
    default = np.asarray(DEFAULT_ANGLES, dtype=np.float64)

    n_steps = ref.joint_pos.shape[0]
    if args_cli.max_steps is not None:
        n_steps = min(n_steps, int(args_cli.max_steps))

    print(f"[sonic] clip {npz_path}", flush=True)
    print(f"[sonic] checkpoint {ckpt}  mode={args_cli.mode}  steps={n_steps} @ 50 Hz", flush=True)
    print(f"[sonic] robot G1_29DOF_CFG (not g1_minimal)  table_z={ref.table_z:.3f}", flush=True)
    lx, ly, thick = _TABLE_SIZE
    table_x0 = float(ref.table_xy[0] - 0.5 * lx)
    table_x1 = float(ref.table_xy[0] + 0.5 * lx)
    rw = ref.hand_pos_w[0]
    print(
        f"[sonic] layout robot_xy=({ref.robot_xy[0]:.2f},{ref.robot_xy[1]:.2f})  "
        f"table_x=[{table_x0:.2f},{table_x1:.2f}]  front_clearance={table_x0 - ref.robot_xy[0]:.2f} m  "
        f"R_wrist0=({rw[0]:.2f},{rw[1]:.2f},{rw[2]:.2f})",
        flush=True,
    )
    print(f"[sonic] mp4 {out_mp4}", flush=True)

    sim = SimulationContext(sim_utils.SimulationCfg(dt=_SIM_DT, device=args_cli.device))
    look = np.array([0.40, 0.0, 0.85], dtype=np.float32)
    eye = np.array([-1.6, -2.2, 1.70], dtype=np.float32)
    sim.set_camera_view(eye=eye.tolist(), target=look.tolist())

    sim_utils.GroundPlaneCfg().func("/World/defaultGroundPlane", sim_utils.GroundPlaneCfg())
    sim_utils.DomeLightCfg(intensity=2500.0, color=(0.8, 0.8, 0.8)).func(
        "/World/Light", sim_utils.DomeLightCfg(intensity=2500.0, color=(0.8, 0.8, 0.8))
    )
    _spawn_table(ref.table_xy, ref.table_z)

    robot_xyz = (float(ref.robot_xy[0]), float(ref.robot_xy[1]), float(ref.pelvis_z))
    robot = Articulation(_g1_cfg(robot_xyz))
    obj = None
    obj_xyzw0 = (0.0, 0.0, 0.0, 1.0)
    if ref.object_urdf and Path(ref.object_urdf).is_file() and ref.object_pos is not None:
        p0 = ref.object_pos[0]
        if ref.object_wxyz is not None:
            obj_xyzw0 = tuple(_wxyz_to_xyzw(ref.object_wxyz[0]).tolist())
        obj = RigidObject(_object_cfg(ref.object_urdf, "/World/Object", p0, obj_xyzw0))
        print(
            f"[sonic] object rest xy=({p0[0]:.3f},{p0[1]:.3f}) z={p0[2]:.3f}  "
            f"({p0[2] - ref.table_z:.3f} m above table)",
            flush=True,
        )

    camera = Camera(
        CameraCfg(
            prim_path="/World/RecordCamera",
            update_period=0.0,
            height=480,
            width=640,
            data_types=["rgb"],
            spawn=sim_utils.PinholeCameraCfg(
                focal_length=24.0,
                focus_distance=400.0,
                horizontal_aperture=20.955,
                clipping_range=(0.1, 1.0e5),
            ),
        )
    )

    sim.reset()
    camera.set_world_poses_from_view(
        torch.tensor(eye, device=sim.device).unsqueeze(0),
        torch.tensor(look, device=sim.device).unsqueeze(0),
    )
    sonic_ids = _joint_ids(robot)
    sonic_ids_list = [int(i) for i in sonic_ids.tolist()]
    print(f"[sonic] articulation joints={len(robot.joint_names)}  sonic mapped={len(sonic_ids)}", flush=True)
    # Whatever SONIC does not drive is a finger joint, available as a separate
    # action channel for grasping.
    extra_ids = [i for i in range(len(robot.joint_names)) if i not in set(sonic_ids_list)]
    if extra_ids:
        print(
            f"[sonic] {len(extra_ids)} non-SONIC joints held at default: "
            f"{[robot.joint_names[i] for i in extra_ids]}",
            flush=True,
        )

    device = sim.device
    n_j = len(robot.joint_names)
    q0 = np.zeros(n_j, dtype=np.float64)
    q0[sonic_ids] = default
    robot.write_root_pose_to_sim_index(
        root_pose=torch.tensor(
            [[robot_xyz[0], robot_xyz[1], robot_xyz[2], 0.0, 0.0, 0.0, 1.0]],
            dtype=torch.float32,
            device=device,
        )
    )
    robot.write_root_velocity_to_sim_index(root_velocity=torch.zeros(1, 6, device=device))
    robot.write_joint_state_to_sim_index(
        position=torch.tensor(q0, dtype=torch.float32, device=device).unsqueeze(0),
        velocity=torch.zeros(1, n_j, device=device),
        full_data=True,
    )
    robot.write_data_to_sim()
    hist = History()
    last_action = np.zeros(29, dtype=np.float32)

    def _proprio():
        q_all = _batch_row(robot.data.joint_pos)
        dq_all = _batch_row(robot.data.joint_vel)
        q = q_all[sonic_ids]
        dq = dq_all[sonic_ids]
        ang = _batch_row(robot.data.root_ang_vel_b)
        grav = _batch_row(robot.data.projected_gravity_b)
        pos = _batch_row(robot.data.root_pos_w)
        quat = _xyzw_to_wxyz(_batch_row(robot.data.root_quat_w))
        return q, dq, ang, grav, pos, quat

    sim.step()
    robot.update(_SIM_DT)
    if obj is not None:
        obj.update(_SIM_DT)
    camera.update(_CTRL_DT)

    q, dq, ang, grav, pos, quat = _proprio()
    hist.fill(ang_vel=ang, q_rel=q - default, dq=dq, action=last_action, gravity=grav)
    hip_i = int(robot.joint_names.index("left_hip_pitch_joint"))
    hip_kp = float(_batch_row(robot.data.joint_stiffness)[hip_i])
    print(
        f"[sonic] start root_z={pos[2]:.3f}  q[:4]={np.array2string(q[:4], precision=3)}  "
        f"left_hip_pitch Kp={hip_kp:.3f} (0 = PD wiring bug)",
        flush=True,
    )

    stand_local_pos, stand_local_quat = _stand_vr3_local(robot, pos, quat)
    vr_local_pos, vr_local_quat = vr3_local_targets(
        ref,
        stand_local_pos=stand_local_pos,
        stand_local_quat=stand_local_quat,
        track_hand_orientation=args_cli.track_hand_orientation,
    )
    print(
        "[sonic] vr3 pelvis-local  L="
        f"{np.array2string(stand_local_pos[0], precision=3)}  "
        f"R0={np.array2string(vr_local_pos[0, 1], precision=3)}  "
        f"torso={np.array2string(stand_local_pos[2], precision=3)}",
        flush=True,
    )

    if obj is not None and ref.object_pos is not None and ref.object_wxyz is not None:
        pose7 = np.concatenate([ref.object_pos[0], _wxyz_to_xyzw(ref.object_wxyz[0])])
        obj.write_root_pose_to_sim_index(
            root_pose=torch.tensor(pose7, dtype=torch.float32, device=device).unsqueeze(0)
        )
        obj.write_root_velocity_to_sim_index(root_velocity=torch.zeros(1, 6, device=device))

    frames: list[np.ndarray] = []
    try:
        for t in range(n_steps):
            if not simulation_app.is_running():
                break
            q, dq, ang, grav, pos, quat = _proprio()
            enc = pack_encoder(
                mode=args_cli.mode,
                t=t,
                joint_pos=ref.joint_pos,
                joint_vel=ref.joint_vel,
                ref_quat_wxyz=ref.root_quat,
                robot_quat_wxyz=quat,
                vr_local_pos=vr_local_pos,
                vr_local_quat=vr_local_quat,
            )
            token = agent.encode(enc)
            dec = pack_decoder(token, hist)
            action = np.clip(agent.decode(dec), -ACTION_CLIP, ACTION_CLIP)
            last_action = action.astype(np.float32)
            q_des = default + scale * last_action

            robot.set_joint_position_target_index(
                target=torch.tensor(q_des, dtype=torch.float32, device=device).unsqueeze(0),
                joint_ids=sonic_ids_list,
            )
            robot.write_data_to_sim()
            for _ in range(_DECIMATION):
                sim.step()
                robot.update(_SIM_DT)
                if obj is not None:
                    obj.update(_SIM_DT)
            camera.update(_CTRL_DT)
            hist.push(ang_vel=ang, q_rel=q - default, dq=dq, action=last_action, gravity=grav)

            rgb = _rgb_frame(camera)
            if rgb is not None:
                frames.append(rgb)
            if t % 50 == 0:
                print(
                    f"  step {t}/{n_steps}  root_z={pos[2]:.3f}  "
                    f"a=[{float(last_action.min()):+.3f},{float(last_action.max()):+.3f}] "
                    f"|a|={float(np.linalg.norm(last_action)):.3f}  frames={len(frames)}",
                    flush=True,
                )
    except Exception:
        import traceback

        traceback.print_exc()
        print(f"[sonic] stopped after {len(frames)} frames", flush=True)
        if frames:
            _write_mp4(out_mp4, frames, 30.0)
            print(f"[sonic] wrote partial {out_mp4}", flush=True)
        raise

    _write_mp4(out_mp4, frames, 30.0)
    print(f"[sonic] wrote {out_mp4} ({len(frames)} frames)", flush=True)


if __name__ == "__main__":
    try:
        main()
    except Exception:
        import traceback

        traceback.print_exc()
        sys.exit(1)
    finally:
        simulation_app.close()