XPandora77 commited on
Commit
e796c4e
·
1 Parent(s): ba151a1

Add the reconstruction video viewer and its G1 body parameters

Browse files
README.md CHANGED
@@ -166,6 +166,27 @@ categories. Differences:
166
 
167
  ## Data Visualization:
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  Released data can be rendered into kinematic-replay MP4s using [GRAIL data visualization](https://NVlabs.github.io/GRAIL/visualization.html). The output can then be browsed using [GRAIL web visualizer](https://NVlabs.github.io/GRAIL/web_visualizer.html) for hover-to-play previews.
170
 
171
  ```bash
 
166
 
167
  ## Data Visualization:
168
 
169
+ ### Reconstruction videos
170
+
171
+ Render a human and its object to a 1280×720 H.264 video on a Linux CPU. The camera stays fixed throughout the clip, and the MP4 plays every frame at the rate recorded in the reconstruction. Download [the viewer](https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-Locomanipulation-GRAIL/resolve/main/tools/visualize_recon.py?download=true) and [the G1 body parameters](https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-Locomanipulation-GRAIL/resolve/main/tools/g1_body_parameters.json?download=true) into the same directory. Install the pip packages listed at the top of the script. For SMPL-X, supply your own licensed [neutral model](https://smpl-x.is.tue.mpg.de/). SOMA uses the identity stored in the recording.
172
+
173
+ ```bash
174
+ python visualize_recon.py data/pickup_table/recon/pickup_table__alcohol_0__000.pkl --model /path/to/SMPLX_NEUTRAL.npz -o pickup.mp4
175
+ python visualize_recon.py data/manip_table/recon/manip_table__cordless_drill__000.pkl -o drill.mp4
176
+ ```
177
+
178
+ <video controls preload="metadata" src="https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-Locomanipulation-GRAIL/resolve/main/samples/pickup_table.mp4"></video>
179
+
180
+ Table pick-up of a bottle with the G1-proportioned SMPL-X body.
181
+
182
+ <video controls preload="metadata" src="https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-Locomanipulation-GRAIL/resolve/main/samples/cordless_drill.mp4"></video>
183
+
184
+ Cordless drill manipulation with the SOMA body.
185
+
186
+ For shared videos, keep the credits with the video. The table pick-up shows the [SMPL-X Body](https://smpl-x.is.tue.mpg.de/bodylicense.html), courtesy of the Max Planck Institute for Intelligent Systems ([CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)), posed with GRAIL’s G1 proportions. Its bottle is courtesy of the [RoboCasa Team](https://robocasa.ai/) (CC BY 4.0). The drill is [Tools Drilling Machine by ROY](https://sketchfab.com/3d-models/tools-drilling-machine-ef0a15e3fc9344c7a66e1f06f4464cfb) (Creative Commons Attribution), via [ComAsset](https://huggingface.co/datasets/SShowbiz/ComAsset) (Kim et al., ODC-By 1.0). Both videos show the object in a single color. See the [dataset terms](#licenseterms-of-use) for motion and asset credits for other clips.
187
+
188
+ A dataset path fetches the reconstruction and its paired object USD. To render offline, use a local trusted PKL and its sibling `object_usd/<name>.usd` or pass `--object-usd`. The gray support is taken from the reconstruction when available. For a tabletop clip with no recorded support mesh, the viewer uses the matching simulation table from `meta/<name>.pkl` when available. The grid marks world height zero. SOMA assets can be cached or supplied with `--soma-assets`. Add `--html scene.html` for a self-contained interactive view.
189
+
190
  Released data can be rendered into kinematic-replay MP4s using [GRAIL data visualization](https://NVlabs.github.io/GRAIL/visualization.html). The output can then be browsed using [GRAIL web visualizer](https://NVlabs.github.io/GRAIL/web_visualizer.html) for hover-to-play previews.
191
 
192
  ```bash
samples/cordless_drill.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7696f3a1960fdc5ca5664a32af2d216c66b77c373ffd6411924b4c6da53cac89
3
+ size 422862
samples/pickup_table.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3918714b762461536b25d248240f7239897947d1126b1e9abd2d4834534ca20d
3
+ size 478153
tools/g1_body_parameters.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "betas": [
3
+ -0.39721256494522095,
4
+ -1.5454789400100708,
5
+ -0.20236802101135254,
6
+ 0.42262497544288635,
7
+ 0.0727967768907547,
8
+ 0.3877381682395935,
9
+ 0.059950243681669235,
10
+ 0.3791115880012512,
11
+ -0.14643998444080353,
12
+ 0.2420760691165924
13
+ ],
14
+ "scale": 0.7633275389671326,
15
+ "segment_lengths_m": {
16
+ "thigh": 0.340923457575587,
17
+ "shin": 0.30001001486593415,
18
+ "forearm": 0.1842812095797293
19
+ }
20
+ }
tools/visualize_recon.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Render a released GRAIL human–object reconstruction to a 1280x720 H.264 video on the CPU.
3
+
4
+ Linux CPU, Python 3.12, in a fresh virtual environment:
5
+ python -m pip install torch==2.10.0 --index-url https://download.pytorch.org/whl/cpu
6
+ python -m pip install "numpy>=1.26.4,<3" joblib smplx py-soma-x==0.3.3 scenepic==1.1.2 usd-core huggingface_hub numba av scipy
7
+
8
+ Keep g1_body_parameters.json beside this script for SMPL-X. Supply your own
9
+ licensed neutral SMPL-X NPZ. SOMA uses the identity in the motion itself.
10
+ python visualize_recon.py data/pickup_table/recon/pickup_table__alcohol_0__000.pkl --model SMPLX_NEUTRAL.npz -o pickup.mp4
11
+ python visualize_recon.py data/manip_table/recon/manip_table__cordless_drill__000.pkl -o drill.mp4
12
+
13
+ python visualize_recon.py data/sitting/recon/sitting__acadian_rustic_wooden_dining_chair_distressed_white__000.pkl --model SMPLX_NEUTRAL.npz -o sitting.mp4
14
+
15
+ Add --html scene.html alongside -o for an interactive, self-contained copy.
16
+ With --html alone only the page is written. With neither option the movie is recon.mp4. Video uses every source frame, a fixed
17
+ orthographic camera and a z=0 world grid. The camera fits the bounds over
18
+ the whole sequence, including the recorded support geometry, with a margin.
19
+ Where a tabletop reconstruction has no authored support, the video uses the
20
+ paired meta/<stem>.pkl simulation table when available. Its placement can
21
+ differ from the reconstructed surface. Local files use sibling directories.
22
+ The software rasterizer and PyAV encoder need neither a display nor a GPU.
23
+ Dataset paths download the PKL and the matching USD. An existing local PKL
24
+ reads its sibling object_usd/<stem>.usd or --object-usd. A movie requires the object mesh; HTML alone can show pose axes instead. For offline SOMA, supply --soma-assets
25
+ or use the previously downloaded assets. All poses are in world-space metres.
26
+ Open an optional HTML copy in a WebGL-capable browser. Load pickle files only from sources you trust.
27
+ """
28
+
29
+ import argparse
30
+ import sys
31
+ from dataclasses import dataclass
32
+ from fractions import Fraction
33
+ from itertools import product
34
+ import tempfile
35
+ import time
36
+ from pathlib import Path
37
+ from unittest.mock import patch
38
+
39
+ import joblib
40
+ import numpy as np
41
+
42
+ DATASET = "nvidia/PhysicalAI-Robotics-Locomanipulation-GRAIL"
43
+ REVISION = "ba151a1adc4b2fc45c75f5cc3cfd12b7ad288bb0"
44
+
45
+
46
+ def resolve_inputs(source, object_usd, revision):
47
+ path = Path(source)
48
+ if path.is_file():
49
+ sibling = path.parent.parent / "object_usd" / path.with_suffix(".usd").name
50
+ return path, object_usd or (sibling if sibling.is_file() else None)
51
+ if (
52
+ path.is_absolute()
53
+ or path.parts[:1] != ("data",)
54
+ or len(path.parts) != 4
55
+ or path.parts[2] != "recon"
56
+ or path.suffix != ".pkl"
57
+ or ".." in path.parts
58
+ ):
59
+ raise ValueError(
60
+ "Provide an existing PKL or a dataset path data/<category>/recon/<name>.pkl"
61
+ )
62
+
63
+ from huggingface_hub import hf_hub_download
64
+
65
+ def download(relative):
66
+ return Path(
67
+ hf_hub_download(DATASET, relative.as_posix(), repo_type="dataset", revision=revision)
68
+ )
69
+
70
+ recon = download(path)
71
+ usd = path.parent.parent / "object_usd" / path.with_suffix(".usd").name
72
+ return recon, object_usd or download(usd)
73
+
74
+
75
+ def load_reconstruction(path):
76
+ # NumPy 2 pickles refer to numeric._frombuffer through the new module path.
77
+ if np.__version__.split(".")[0] == "1":
78
+ from numpy.core import numeric
79
+
80
+ with patch.dict(sys.modules, {"numpy._core.numeric": numeric}):
81
+ return joblib.load(path)
82
+ return joblib.load(path)
83
+
84
+
85
+ def g1_layer(model_path):
86
+ """Rebuild the released rest shape using only the reader's licensed model."""
87
+ import json
88
+ import smplx
89
+ import torch
90
+
91
+ profile = json.loads(Path(__file__).with_name("g1_body_parameters.json").read_text())
92
+ layer = smplx.SMPLX(str(model_path), use_pca=False, flat_hand_mean=True)
93
+ layer.eval().requires_grad_(False)
94
+ beta = torch.tensor(profile["betas"], dtype=torch.float32)[None]
95
+ scale = profile["scale"]
96
+ # The original one-time bake used a zero-pose SMPL-X forward pass.
97
+ rest = layer(betas=beta).vertices[0] * scale
98
+ regressor = layer.J_regressor.to_dense()
99
+ joints = regressor @ rest
100
+ target = joints.clone()
101
+ parents = layer.parents.tolist()
102
+ segments = [(1, 4, "thigh"), (2, 5, "thigh"), (4, 7, "shin"),
103
+ (5, 8, "shin"), (18, 20, "forearm"), (19, 21, "forearm")]
104
+ for parent, child, segment in segments:
105
+ bone = target[child] - target[parent]
106
+ offset = bone * (profile["segment_lengths_m"][segment] / bone.norm().item() - 1)
107
+ descendants = {child}
108
+ for index, ancestor in enumerate(parents):
109
+ if ancestor in descendants:
110
+ descendants.add(index)
111
+ target[sorted(descendants)] += offset
112
+ displacement = target - joints
113
+ skin = layer.lbs_weights @ displacement
114
+ # The joint-regressor correction preserves the requested segment lengths.
115
+ correction = regressor.T @ torch.linalg.solve(
116
+ regressor @ regressor.T, displacement - regressor @ skin
117
+ )
118
+ layer.v_template.copy_(rest + skin + correction)
119
+ layer.shapedirs.zero_()
120
+ layer.expr_dirs.zero_()
121
+ layer.posedirs.mul_(scale)
122
+ return layer
123
+
124
+
125
+ def smplx_meshes(human, model_path, indices):
126
+ import torch
127
+
128
+ layer = g1_layer(model_path)
129
+ poses = torch.as_tensor(human["poses"], dtype=torch.float32).reshape(-1, 165)
130
+ trans = torch.as_tensor(human["trans"], dtype=torch.float32).reshape(len(poses), 3)
131
+ vertices = []
132
+ for ids in np.array_split(indices, (len(indices) + 15) // 16):
133
+ hands = {}
134
+ for side in ("left_hand_pose", "right_hand_pose"):
135
+ value = human.get(side)
136
+ hands[side] = (torch.zeros(len(ids), 45) if value is None else
137
+ torch.as_tensor(value, dtype=torch.float32).reshape(-1, 45)[ids])
138
+ zeros = torch.zeros(len(ids), 3)
139
+ output = layer(
140
+ global_orient=poses[ids, :3], body_pose=poses[ids, 3:66], transl=trans[ids],
141
+ betas=torch.zeros(len(ids), 10), expression=torch.zeros(len(ids), 10),
142
+ jaw_pose=zeros, leye_pose=zeros, reye_pose=zeros, **hands
143
+ )
144
+ vertices.append(output.vertices.numpy())
145
+ return np.concatenate(vertices), layer.faces.astype(np.uint32)
146
+
147
+
148
+
149
+ def soma_meshes(human, assets, indices, *, offline=False):
150
+ import torch
151
+ from soma import SOMALayer, Unit
152
+
153
+ if assets is None:
154
+ from huggingface_hub import snapshot_download
155
+ assets = snapshot_download(
156
+ "nvidia/SOMA-X", revision="d281db2d01553f7230c56e764cec00fe27ef23f7",
157
+ local_files_only=offline,
158
+ allow_patterns=["SOMA_neutral.npz", "SOMA_template_rig.usda",
159
+ "SOMA_procedural_transforms.json", "correctives_model.pt"],
160
+ )
161
+ layer = SOMALayer(data_root=str(assets), lod="low", mode="torch", device="cpu",
162
+ identity_model_type="soma", output_unit=Unit.METERS,
163
+ enable_procedural_transforms=True, reference_pose=None)
164
+ layer.requires_grad_(False)
165
+ poses = torch.as_tensor(human["poses"], dtype=torch.float32).reshape(-1, 77, 3)
166
+ trans = torch.as_tensor(human["trans"], dtype=torch.float32).reshape(len(poses), 3)
167
+ identity = torch.as_tensor(human["identity_coeffs"], dtype=torch.float32).reshape(-1, 128)
168
+ scales = torch.as_tensor(human["scale_params"], dtype=torch.float32).reshape(-1, 57)
169
+ identity = identity.expand(len(poses), -1)
170
+ scales = scales.expand(len(poses), -1)
171
+ vertices = []
172
+ with torch.no_grad():
173
+ for ids in np.array_split(indices, (len(indices) + 15) // 16):
174
+ scale = scales[ids]
175
+ local = torch.cat((scale[:, 1:], torch.ones_like(scale[:, :4])), dim=1)
176
+ layer.prepare_identity(identity[ids], local, global_scale=scale[:, :1],
177
+ repose_to_bind_pose=True)
178
+ posed = layer.pose(poses[ids].contiguous(), transl=trans[ids],
179
+ pose2rot=True, apply_correctives=True)
180
+ vertices.append(posed["vertices"].cpu().numpy())
181
+ return np.concatenate(vertices), np.asarray(layer.faces, dtype=np.uint32)
182
+
183
+
184
+
185
+ def usd_geometry(path):
186
+ from pxr import Usd, UsdGeom
187
+
188
+ stage = Usd.Stage.Open(str(path))
189
+ if UsdGeom.GetStageUpAxis(stage) != UsdGeom.Tokens.z:
190
+ raise ValueError("Expected the released Z-up GRAIL object USD")
191
+ cache = UsdGeom.XformCache()
192
+ vertices, faces, offset = [], [], 0
193
+ for prim in stage.Traverse():
194
+ if not prim.IsA(UsdGeom.Mesh):
195
+ continue
196
+ mesh = UsdGeom.Mesh(prim)
197
+ if mesh.ComputeVisibility() == UsdGeom.Tokens.invisible or mesh.ComputePurpose() in (
198
+ UsdGeom.Tokens.guide,
199
+ UsdGeom.Tokens.proxy,
200
+ ):
201
+ continue
202
+ points = np.asarray(mesh.GetPointsAttr().Get(), dtype=np.float32)
203
+ matrix = np.asarray(cache.GetLocalToWorldTransform(prim))
204
+ vertices.append(points @ matrix[:3, :3] + matrix[3, :3])
205
+ counts = np.asarray(mesh.GetFaceVertexCountsAttr().Get())
206
+ corners = np.asarray(mesh.GetFaceVertexIndicesAttr().Get(), dtype=np.int64)
207
+ if np.all(counts == 3):
208
+ tris = corners.reshape(-1, 3)
209
+ else:
210
+ polys = np.split(corners, np.cumsum(counts)[:-1])
211
+ tris = np.array([(p[0], p[i], p[i + 1]) for p in polys for i in range(1, len(p) - 1)])
212
+ left_handed = mesh.GetOrientationAttr().Get() == UsdGeom.Tokens.leftHanded
213
+ if left_handed != (np.linalg.det(matrix[:3, :3]) < 0):
214
+ tris = tris[:, [0, 2, 1]]
215
+ faces.append(tris + offset)
216
+ offset += len(points)
217
+ if not vertices:
218
+ raise ValueError(f"No visible object mesh in {path}")
219
+ # Export already bakes the original obj_scale into the paired asset.
220
+ return (np.concatenate(vertices) * UsdGeom.GetStageMetersPerUnit(stage)).astype(
221
+ np.float32
222
+ ), np.concatenate(faces).astype(np.uint32)
223
+
224
+
225
+ @dataclass
226
+ class Motion:
227
+ vertices: np.ndarray
228
+ faces: np.ndarray
229
+ rotations: np.ndarray
230
+ positions: np.ndarray
231
+ points: np.ndarray
232
+ triangles: np.ndarray
233
+ fps: float
234
+
235
+
236
+ def load_motion(data, model, assets, usd, offline):
237
+ human, obj = data["human_data"], data["obj_data"]
238
+ ids = np.arange(len(human["poses"]))
239
+ body = human["model"]
240
+ if body == "smplx":
241
+ if model is None or not model.is_file():
242
+ raise ValueError("SMPL-X requires --model /path/to/SMPLX_NEUTRAL.npz")
243
+ vertices, faces = smplx_meshes(human, model, ids)
244
+ elif body == "soma03":
245
+ vertices, faces = soma_meshes(human, assets, ids, offline=offline)
246
+ else:
247
+ raise ValueError(f"Unsupported human_data.model: {body!r}")
248
+ frames = len(human["poses"])
249
+ rotations = np.broadcast_to(np.asarray(obj["obj_R"]).reshape(-1, 3, 3), (frames, 3, 3))[ids]
250
+ positions = np.broadcast_to(np.asarray(obj["obj_t"]).reshape(-1, 3), (frames, 3))[ids]
251
+ points, triangles = usd_geometry(usd) if usd is not None else (None, None)
252
+ fps = float(human["mocap_frame_rate"])
253
+ if not np.isfinite(fps) or fps <= 0:
254
+ raise ValueError("The recording must have a positive frame rate")
255
+ return Motion(vertices, faces, rotations, positions, points, triangles, fps)
256
+
257
+
258
+ def view_direction(vertices, positions, meta, ids, frames):
259
+ hold = (ids >= (meta.get("inter_start_idx") or 0)) & (ids < (meta.get("inter_end_idx") or frames))
260
+ horizontal = np.array([1.0, 0.72])
261
+ if hold.any():
262
+ towards_object = np.median(positions[hold, :2] - vertices[hold, :, :2].mean(axis=1), axis=0)
263
+ if np.linalg.norm(towards_object) > 0.03:
264
+ horizontal = towards_object + 0.45 * np.array([-towards_object[1], towards_object[0]])
265
+ return horizontal / np.linalg.norm(horizontal)
266
+
267
+
268
+ def write_html(data, motion, stride, out, *, case_stem):
269
+ import scenepic as sp
270
+
271
+ body = data["human_data"]["model"]
272
+ label = "SMPL-X" if body == "smplx" else "SOMA"
273
+ frames = len(motion.vertices)
274
+ ids = np.arange(0, frames, stride)
275
+ vertices, faces = motion.vertices[::stride], motion.faces
276
+ rotations, positions = motion.rotations[::stride], motion.positions[::stride]
277
+ scene = sp.Scene()
278
+ scene.framerate = motion.fps / stride
279
+ skin = scene.create_mesh("body", layer_id=label, shared_color=sp.Color(0.35, 0.66, 0.86))
280
+ skin.add_mesh_without_normals(vertices[0], faces)
281
+ bounds = [
282
+ vertices.min(axis=(0, 1)),
283
+ vertices.max(axis=(0, 1)),
284
+ positions.min(0),
285
+ positions.max(0),
286
+ ]
287
+ if motion.points is not None:
288
+ points, triangles = motion.points, motion.triangles
289
+ prop = scene.create_mesh(layer_id="Object", shared_color=sp.Color(0.94, 0.56, 0.23))
290
+ prop.add_mesh_without_normals(points, triangles)
291
+ corners = np.array(list(product(*zip(points.min(0), points.max(0)))))
292
+ world = corners @ rotations.transpose(0, 2, 1) + positions[:, None]
293
+ bounds.extend([world.min(axis=(0, 1)), world.max(axis=(0, 1))])
294
+ else:
295
+ prop = scene.create_mesh(layer_id="Object pose (XYZ)")
296
+ prop.add_coordinate_axes(length=0.15, thickness=0.009)
297
+ print("Object USD absent. HTML shows its recorded position and orientation as axes.")
298
+
299
+ static = []
300
+ for name, entry in (data.get("scene_data") or {}).items():
301
+ if "vertices" in entry and "faces" in entry:
302
+ pts = np.asarray(entry["vertices"], dtype=np.float32)
303
+ mesh = scene.create_mesh(layer_id=name, shared_color=sp.Color(0.65, 0.65, 0.65))
304
+ mesh.add_mesh_without_normals(pts, np.asarray(entry["faces"], dtype=np.uint32))
305
+ bounds.extend([pts.min(0), pts.max(0)])
306
+ elif name == "table" and "pos" in entry and "size" in entry:
307
+ pos, size = np.asarray(entry["pos"]), np.asarray(entry["size"])
308
+ transform = np.diag([*size, 1.0])
309
+ transform[:3, 3] = pos
310
+ mesh = scene.create_mesh(layer_id=name, shared_color=sp.Color(0.65, 0.65, 0.65))
311
+ mesh.add_cube(transform=transform)
312
+ bounds.extend([pos - size / 2, pos + size / 2])
313
+ else:
314
+ continue
315
+ static.append(mesh)
316
+
317
+ low, high = np.min(bounds, axis=0), np.max(bounds, axis=0)
318
+ focus = (low + high) / 2
319
+ meta = data.get("meta") or {}
320
+ horizontal = view_direction(vertices, positions, meta, ids, frames)
321
+ camera = sp.Camera(
322
+ center=focus + np.linalg.norm(high - low) * np.array([*horizontal, 0.36]),
323
+ look_at=focus,
324
+ up_dir=(0, 0, 1),
325
+ aspect_ratio=1.5,
326
+ )
327
+ canvas = scene.create_canvas_3d(width=900, height=600, camera=camera)
328
+ for frame_index, verts in enumerate(vertices):
329
+ frame = canvas.create_frame()
330
+ frame.add_mesh(
331
+ skin if frame_index == 0 else scene.update_mesh_positions(skin.mesh_id, verts)
332
+ )
333
+ transform = np.eye(4, dtype=np.float32)
334
+ transform[:3, :3], transform[:3, 3] = rotations[frame_index], positions[frame_index]
335
+ frame.add_mesh(prop, transform=transform)
336
+ for mesh in static:
337
+ frame.add_mesh(mesh)
338
+ if len(vertices) > 1:
339
+ # Display compression in metres. The forward pass retains float32 vertices.
340
+ scene.quantize_updates(relative_error_threshold=-1, absolute_error_threshold=0.00005)
341
+ scene.save_as_html(str(out), title=f"GRAIL {label} reconstruction")
342
+ credits = ['<a href="https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-Locomanipulation-GRAIL">GRAIL reconstruction and object asset</a>.']
343
+ if case_stem.startswith(("pickup_table__", "pickup_ground__")):
344
+ credits.append('Pick-up object assets courtesy of the RoboCasa Team '
345
+ '(<a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>).')
346
+ if case_stem == "manip_table__cordless_drill__000":
347
+ credits.append('Drill geometry from <a href="https://sketchfab.com/3d-models/tools-drilling-machine-ef0a15e3fc9344c7a66e1f06f4464cfb">Tools Drilling Machine</a> '
348
+ 'by ROY, via ComAsset (Creative Commons Attribution), displayed in a single color.')
349
+ if body == "smplx":
350
+ credit = ('SMPL-X Body courtesy of the Max Planck Institute for Intelligent Systems. '
351
+ 'GRAIL applies Unitree G1 proportions and the recorded poses. '
352
+ '<a href="https://smpl-x.is.tue.mpg.de/bodylicense.html">Body license</a> · '
353
+ '<a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.')
354
+ credits.append(credit)
355
+ out.write_text(out.read_text(encoding="utf-8").replace("</body>", "<p>" + " ".join(credits) + "</p></body>"),
356
+ encoding="utf-8")
357
+ print(f"{out}: {len(ids)} frames at {scene.framerate:g} fps")
358
+
359
+
360
+ def video_support(data, source, revision):
361
+ """Prefer the reconstruction surface; use the released simulation box as context."""
362
+ if data.get("scene_data"):
363
+ return data
364
+ category = source.parent.parent.name
365
+ if category not in ("pickup_table", "manip_table") and not source.stem.startswith(("pickup_table__", "manip_table__")):
366
+ return data
367
+ relative = source.parent.parent / "meta" / source.name
368
+ if source.is_file():
369
+ if not relative.is_file():
370
+ print("No local table record. Place the matching PKL in the sibling meta directory to show it.")
371
+ return data
372
+ meta_path = relative
373
+ else:
374
+ from huggingface_hub import hf_hub_download
375
+ from huggingface_hub.errors import EntryNotFoundError
376
+
377
+ try:
378
+ meta_path = hf_hub_download(DATASET, str(relative), repo_type="dataset", revision=revision)
379
+ except EntryNotFoundError:
380
+ print("No paired table metadata available. Showing the world ground grid.")
381
+ return data
382
+ meta = load_reconstruction(meta_path)
383
+ if not all(meta.get(key) is not None for key in ("table_pos", "table_size", "table_quat")):
384
+ return data
385
+ table = {"pos": meta["table_pos"], "size": meta["table_size"], "quat": meta["table_quat"]}
386
+ print("Table source: paired simulation metadata; body and object use the reconstruction coordinates.")
387
+ return {**data, "scene_data": {"table": table}}
388
+
389
+
390
+ def scene_meshes(data):
391
+ """World-space support geometry authored in the reconstruction."""
392
+ for name, entry in (data.get("scene_data") or {}).items():
393
+ if "vertices" in entry and "faces" in entry:
394
+ yield np.asarray(entry["vertices"], dtype=np.float32), np.asarray(entry["faces"], dtype=np.int32)
395
+ elif name == "table" and "pos" in entry and "size" in entry:
396
+ # The released table box records full side lengths, not half-extents.
397
+ corners = np.array(list(product((-0.5, 0.5), repeat=3)), dtype=np.float32)
398
+ quads = [(0, 4, 6, 2), (1, 3, 7, 5), (0, 1, 5, 4),
399
+ (2, 6, 7, 3), (0, 2, 3, 1), (4, 5, 7, 6)]
400
+ faces = [(a, b, c) for a, b, c, d in quads] + [(a, c, d) for a, b, c, d in quads]
401
+ points = corners * np.asarray(entry["size"]).reshape(3)
402
+ if "quat" in entry:
403
+ from scipy.spatial.transform import Rotation
404
+ points = Rotation.from_quat(np.asarray(entry["quat"]).reshape(4)).apply(points)
405
+ yield points + np.asarray(entry["pos"]).reshape(3), np.asarray(faces, dtype=np.int32)
406
+
407
+
408
+ def camera_projection(motion, static, meta, width, height):
409
+ verts, points = motion.vertices, motion.points
410
+ ids = np.arange(len(verts))
411
+ horizontal = view_direction(verts, motion.positions, meta, ids, len(ids))
412
+ # Show a seated/approaching person from beside their path instead of through the chair back.
413
+ if (np.ptp(motion.positions, axis=0).max() < 1e-5
414
+ and np.ptp(motion.rotations, axis=0).max() < 1e-5):
415
+ approach = verts[0, :, :2].mean(0) - motion.positions[0, :2]
416
+ if np.linalg.norm(approach) > 0.15:
417
+ horizontal = 0.65 * approach + np.array([-approach[1], approach[0]])
418
+ horizontal /= np.linalg.norm(horizontal)
419
+ toward = np.array([*horizontal, 0.36])
420
+ toward /= np.linalg.norm(toward)
421
+ right = np.array([-horizontal[1], horizontal[0], 0.0])
422
+ up = np.cross(toward, right)
423
+ basis = np.column_stack((right, up, toward)).astype(np.float32)
424
+ corners = np.array(list(product(*zip(points.min(0), points.max(0)))))
425
+ sweep = corners @ motion.rotations.transpose(0, 2, 1) + motion.positions[:, None]
426
+ bounds = [sweep.reshape(-1, 3) @ basis] + [p @ basis for p, _ in static]
427
+ # Include the world-ground footprint. Limit memory to one posed body at a time.
428
+ for frame in verts:
429
+ projected = frame @ basis
430
+ bounds.append(np.stack((projected.min(0), projected.max(0))))
431
+ foot_xy = np.median(verts[:, :, :2].mean(axis=1), axis=0)
432
+ bounds.append(np.array([[*foot_xy, 0]]) @ basis)
433
+ all_bounds = np.concatenate(bounds)
434
+ low, high = all_bounds.min(0), all_bounds.max(0)
435
+ mid = (low + high) / 2
436
+ scale = 0.88 * min(width / max(high[0]-low[0], 1e-6), height / max(high[1]-low[1], 1e-6))
437
+ matrix = (basis * np.array([scale, -scale, 1.0])).astype(np.float32)
438
+ offset = np.array([width/2 - mid[0]*scale, height/2 + mid[1]*scale, 0], dtype=np.float32)
439
+ return matrix, offset, scale
440
+
441
+
442
+ def ground_background(matrix, offset, width, height):
443
+ # A metric reference grid at world Z=0, drawn behind the recorded geometry.
444
+ yy, xx = np.mgrid[:height, :width].astype(np.float32)
445
+ plane_to_pixel = matrix[:2, :2]
446
+ inv = np.linalg.inv(plane_to_pixel)
447
+ x = (xx-offset[0])*inv[0, 0] + (yy-offset[1])*inv[1, 0]
448
+ y = (xx-offset[0])*inv[0, 1] + (yy-offset[1])*inv[1, 1]
449
+ grid = np.zeros_like(x)
450
+ for coord, gradient in [(x, np.linalg.norm(inv[:, 0])), (y, np.linalg.norm(inv[:, 1]))]:
451
+ distance = np.abs((coord + 0.125) % 0.25 - 0.125) / max(gradient, 1e-8)
452
+ grid = np.maximum(grid, np.clip(1.2-distance, 0, 1))
453
+ fade = np.exp(-((xx - width/2)**2 + (yy - height*0.8)**2) / (0.70*width)**2)
454
+ return np.uint8(np.array([242, 244, 246]) - (grid * fade * 20)[..., None])
455
+
456
+
457
+ def rasterize(xyz, faces, color, pixels, depth, scale, smooth):
458
+ """Rasterize double-sided orthographic triangles with a per-pixel depth test."""
459
+ height, width = pixels.shape[:2]
460
+ normals = np.zeros((len(xyz), 3), np.float32)
461
+ shades = np.empty(len(faces), np.float32)
462
+ for i in range(len(faces)):
463
+ a, b, c = faces[i]
464
+ ux, uy, uz = (xyz[b, 0]-xyz[a, 0])/scale, -(xyz[b, 1]-xyz[a, 1])/scale, xyz[b, 2]-xyz[a, 2]
465
+ vx, vy, vz = (xyz[c, 0]-xyz[a, 0])/scale, -(xyz[c, 1]-xyz[a, 1])/scale, xyz[c, 2]-xyz[a, 2]
466
+ nx, ny, nz = uy*vz-uz*vy, uz*vx-ux*vz, ux*vy-uy*vx
467
+ if smooth:
468
+ for j in (a, b, c):
469
+ normals[j, 0] += nx
470
+ normals[j, 1] += ny
471
+ normals[j, 2] += nz
472
+ length = max((nx*nx+ny*ny+nz*nz)**0.5, 1e-15)
473
+ dot = (-0.35*nx + 0.65*ny + 0.67*nz)/length
474
+ shades[i] = 0.62 + 0.38*max(0., dot if nz >= 0 else -dot)
475
+ tones = np.ones(len(xyz), np.float32)
476
+ if smooth:
477
+ for j in range(len(xyz)):
478
+ nx, ny, nz = normals[j]
479
+ length = max((nx*nx+ny*ny+nz*nz)**0.5, 1e-15)
480
+ dot = (-0.35*nx + 0.65*ny + 0.67*nz)/length
481
+ tones[j] = 0.62 + 0.38*max(0., dot if nz >= 0 else -dot)
482
+ for i in range(len(faces)):
483
+ a, b, c = faces[i]
484
+ x0, y0, z0 = xyz[a]
485
+ x1, y1, z1 = xyz[b]
486
+ x2, y2, z2 = xyz[c]
487
+ xlo = max(0, int(np.ceil(min(x0, x1, x2)-0.5)))
488
+ xhi = min(width-1, int(np.floor(max(x0, x1, x2)-0.5)))
489
+ ylo = max(0, int(np.ceil(min(y0, y1, y2)-0.5)))
490
+ yhi = min(height-1, int(np.floor(max(y0, y1, y2)-0.5)))
491
+ det = (x1-x0)*(y2-y0)-(y1-y0)*(x2-x0)
492
+ if abs(det) < 1e-8:
493
+ continue
494
+ for y in range(ylo, yhi+1):
495
+ for x in range(xlo, xhi+1):
496
+ dx, dy = x+0.5-x0, y+0.5-y0
497
+ u = (dx*(y2-y0)-dy*(x2-x0))/det
498
+ v = (dy*(x1-x0)-dx*(y1-y0))/det
499
+ if u < 0 or v < 0 or u+v > 1:
500
+ continue
501
+ z = z0 + (z1-z0)*u + (z2-z0)*v
502
+ if z <= depth[y, x]:
503
+ continue
504
+ depth[y, x] = z
505
+ tone = shades[i]
506
+ if smooth:
507
+ tone = tones[a]+(tones[b]-tones[a])*u+(tones[c]-tones[a])*v
508
+ for channel in range(3):
509
+ pixels[y, x, channel] = tone*color[channel]
510
+
511
+
512
+ def write_video(data, motion, out):
513
+ import av
514
+ from numba import njit
515
+
516
+ start = time.perf_counter()
517
+ draw = njit(rasterize)
518
+ width, height = 1280, 720
519
+ static = list(scene_meshes(data))
520
+ matrix, offset, scale = camera_projection(motion, static, data.get("meta") or {}, width, height)
521
+ background = ground_background(matrix, offset, width, height)
522
+ base_depth = np.full((height, width), -np.inf, dtype=np.float32)
523
+ for points, faces in static:
524
+ draw(np.asarray(points @ matrix + offset, dtype=np.float32), np.asarray(faces, dtype=np.int32),
525
+ (166, 166, 166), background, base_depth, scale, False)
526
+ body_faces = np.asarray(motion.faces, dtype=np.int32)
527
+ prop_faces = np.asarray(motion.triangles, dtype=np.int32)
528
+ # Keep an existing movie intact if rendering or finalizing the container fails.
529
+ with tempfile.TemporaryDirectory(dir=out.parent) as tmp:
530
+ dest = Path(tmp) / "movie.mp4"
531
+ with av.open(str(dest), "w", options={"movflags": "+faststart"}) as movie:
532
+ rate = Fraction(str(motion.fps)).limit_denominator(100000)
533
+ stream = movie.add_stream("libx264", rate=rate)
534
+ stream.width, stream.height, stream.pix_fmt = width, height, "yuv420p"
535
+ stream.options = {"crf": "18", "preset": "fast"}
536
+ for i, body in enumerate(motion.vertices):
537
+ pixels, depth = background.copy(), base_depth.copy()
538
+ draw(body @ matrix + offset, body_faces, (89, 168, 219), pixels, depth, scale, True)
539
+ prop = motion.points @ motion.rotations[i].T + motion.positions[i]
540
+ draw(np.asarray(prop @ matrix + offset, dtype=np.float32), prop_faces,
541
+ (240, 143, 59), pixels, depth, scale, False)
542
+ frame = av.VideoFrame.from_ndarray(pixels, format="rgb24")
543
+ for packet in stream.encode(frame):
544
+ movie.mux(packet)
545
+ for packet in stream.encode():
546
+ movie.mux(packet)
547
+ dest.replace(out)
548
+ seconds = time.perf_counter() - start
549
+ print(f"{out}: {len(motion.vertices)} frames, {motion.fps:g} fps, {width}x{height}; "
550
+ f"CPU render and encode {seconds:.2f} s ({seconds/len(motion.vertices):.3f} s/frame)")
551
+
552
+
553
+ def main():
554
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
555
+ parser.add_argument("recon", help="Local trusted PKL or dataset-relative reconstruction path")
556
+ parser.add_argument("--model", type=Path, help="Licensed neutral SMPL-X NPZ")
557
+ parser.add_argument("--soma-assets", type=Path, help="Local SOMA-X 0.3.3 asset directory")
558
+ parser.add_argument("--object-usd", type=Path, help="Override the paired object USD")
559
+ parser.add_argument("--revision", default=REVISION, help="GRAIL dataset revision")
560
+ parser.add_argument("--stride", type=int, default=1, help="Display every Nth frame in optional HTML only")
561
+ parser.add_argument("-o", "--output", type=Path, help="H.264 movie, default recon.mp4 when no output is given")
562
+ parser.add_argument("--html", type=Path, help="Write an interactive HTML page")
563
+ args = parser.parse_args()
564
+ if args.output is None and args.html is None:
565
+ args.output = Path("recon.mp4")
566
+ if (args.output and args.output.suffix.lower() != ".mp4") or (args.html and args.html.suffix.lower() != ".html"):
567
+ parser.error("Use -o file.mp4 for the video and --html file.html for an interactive copy")
568
+ if args.stride < 1:
569
+ parser.error("--stride must be positive")
570
+ if args.object_usd and not args.object_usd.is_file():
571
+ parser.error("--object-usd must identify an existing USD")
572
+ offline = Path(args.recon).is_file()
573
+ path, usd = resolve_inputs(args.recon, args.object_usd, args.revision)
574
+ if {p.resolve() for p in (args.output, args.html) if p} & {p.resolve() for p in (path, usd, args.model) if p}:
575
+ parser.error("Choose an output path distinct from the input files")
576
+ if args.output and usd is None:
577
+ parser.error("The movie needs the matching object mesh. Supply --object-usd or its sibling object_usd file.")
578
+ data = load_reconstruction(path)
579
+ start = time.perf_counter()
580
+ motion = load_motion(data, args.model, args.soma_assets, usd, offline)
581
+ if args.output:
582
+ write_video(video_support(data, Path(args.recon), args.revision), motion, args.output)
583
+ print(f"Body, scene, and video: {(time.perf_counter() - start) / len(motion.vertices):.3f} s/frame")
584
+ if args.html:
585
+ write_html(data, motion, args.stride, args.html, case_stem=Path(args.recon).stem)
586
+
587
+
588
+ if __name__ == "__main__":
589
+ main()