File size: 4,490 Bytes
42afafb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Unpack a 4DCodeBench synthetic world h5 into a plain directory + spec.json.

Usage:
  python unpack_world.py <case.h5> <outdir>

Output (our own simplified layout, plain numpy npz):
  <outdir>/camera.json     verbatim from the h5 (intrinsics K 3x3 px, extrinsic E 4x4 cam-to-world)
  <outdir>/render.mp4      verbatim from the h5 (the reference render)
  <outdir>/mesh/<id>.npz   vertices (F,V,3) f32, faces (F,T,3) i32, nverts/nfaces per frame
  <outdir>/dyn/<name>.npz  pos (F,N,3) f32, ids (M,) u16, faces (T,3) i32
  <outdir>/spec.json       F, video specs, per-object summary, static/dynamic split
"""
import argparse
import json
from pathlib import Path

import numpy as np
import h5py
import hdf5plugin  # noqa: F401  (registers the Zstd filter)


def read_series(group):
    """Per-frame series stored as (frames + stack) or (frames + flat + lengths)."""
    frames = group["frames"][()]
    if "stack" in group:
        parts = list(group["stack"][()])
    else:
        flat = group["flat"][()]
        lengths = group["lengths"][()]
        edges = np.concatenate([[0], np.cumsum(lengths)])
        parts = [flat[edges[i]:edges[i + 1]] for i in range(len(frames))]
    return frames, parts


def probe_video(path):
    try:
        import cv2
        cap = cv2.VideoCapture(str(path))
        fps = cap.get(cv2.CAP_PROP_FPS)
        w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        cap.release()
        if fps and fps > 0 and w > 0:
            return {"fps": round(float(fps), 6), "width": w, "height": h, "frames": n}
    except Exception:
        pass
    return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("h5")
    ap.add_argument("out")
    args = ap.parse_args()

    out = Path(args.out)
    (out / "mesh").mkdir(parents=True, exist_ok=True)
    (out / "dyn").mkdir(parents=True, exist_ok=True)

    spec = {"source": str(args.h5)}
    with h5py.File(args.h5, "r") as h:
        (out / "camera.json").write_bytes(bytes(h["camera.json"][()]))
        (out / "render.mp4").write_bytes(bytes(h["render.mp4"][()]))
        vid = probe_video(out / "render.mp4") or {"fps": 24.0, "width": 1280, "height": 720, "frames": None}
        spec["video"] = vid

        F = int(h[f"dynamics/{next(iter(h['dynamics']))}/pos"].shape[0]) if len(h["dynamics"]) \
            else int(h[f"meshes/{next(iter(h['meshes']))}/vertices/frames"].shape[0])
        spec["F"] = F

        dyn = {}
        for name in h["dynamics"]:
            g = h[f"dynamics/{name}"]
            np.savez_compressed(out / "dyn" / f"{name}.npz",
                                pos=g["pos"][()].astype(np.float32),
                                ids=g["ids"][()].astype(np.uint16),
                                faces=g["faces"][()].astype(np.int32))
            dyn[name] = {"ids": [int(i) for i in g["ids"][()]], "N": int(g["pos"].shape[1])}
        spec["dynamics"] = dyn

        dyn_ids = {i for v in dyn.values() for i in v["ids"]}
        meshes = {}
        for mid in h["meshes"]:
            vf, vp = read_series(h[f"meshes/{mid}/vertices"])
            ff, fp = read_series(h[f"meshes/{mid}/faces"])
            V = max(len(p) for p in vp)
            T = max(len(p) for p in fp)
            vert = np.zeros((len(vp), V, 3), np.float32)
            face = np.zeros((len(fp), T, 3), np.int32)
            for i, (pv, pf) in enumerate(zip(vp, fp)):
                vert[i, :len(pv)] = pv
                face[i, :len(pf)] = pf
            np.savez_compressed(out / "mesh" / f"{int(mid)}.npz", vertices=vert, faces=face,
                                frames=np.asarray(vf, np.int32),
                                nverts=np.array([len(p) for p in vp], np.int32),
                                nfaces=np.array([len(p) for p in fp], np.int32))
            meshes[int(mid)] = {"nverts": int(len(vp[0])), "nfaces": int(len(fp[0])),
                                "static": int(mid) not in dyn_ids}
        spec["meshes"] = {str(k): v for k, v in sorted(meshes.items())}

        cam = json.loads((out / "camera.json").read_text())
        K = np.array(cam["intrinsics"], float)
        spec["camera"] = {"K": K.tolist(), "E": np.array(cam["extrinsic"], float).tolist()}

    (out / "spec.json").write_text(json.dumps(spec, indent=1))
    print(f"unpacked to {out} | F={spec['F']} | video={vid}")


if __name__ == "__main__":
    main()