File size: 11,277 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
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
#!/usr/bin/env python
"""Re-simulate a 4DCodeBench rigid-body world in Blender with a chosen parameter card.

Run inside Blender (background):
  blender --background --python resim_blender.py -- \
      --world work/B_03/world --out work/B_03/out_p1 --kinematic Ball \
      --friction 0.5 --restitution 0.05 --mass 1.5 --samples 32

Split (verified on B_03):
  * static meshes          -> passive rigid bodies, exact geometry, collision as-is
  * the --kinematic group  -> passive+kinematic body replaying the baked trajectory
                              (the driver; identical impact conditions in every preset)
  * every other dynamics group -> active rigid body spawned at its frame-0 pose with
                              the parameter card (this is what we sweep)

Output: <out>/sim.mp4, <out>/simtraj.npz (per-object mean-vertex positions, (F,3))
"""
import argparse
import json
import sys
from math import radians
from pathlib import Path

import bpy
import numpy as np
from mathutils import Matrix, Vector


def parse_args():
    ap = argparse.ArgumentParser()
    ap.add_argument("--world", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--preset", default="p")
    ap.add_argument("--kinematic", default=None, help="dynamics group name to replay as driver")
    ap.add_argument("--friction", type=float, default=0.5)
    ap.add_argument("--restitution", type=float, default=0.05)
    ap.add_argument("--mass", type=float, default=1.5)
    ap.add_argument("--lin_damp", type=float, default=0.04)
    ap.add_argument("--ang_damp", type=float, default=0.04)
    ap.add_argument("--samples", type=int, default=32)
    ap.add_argument("--substeps", type=int, default=20)
    ap.add_argument("--iters", type=int, default=20)
    ap.add_argument("--device", default="gpu", choices=["gpu", "cpu"])
    return ap.parse_args(sys.argv[sys.argv.index("--") + 1:])


def rigid_tf(A, B):
    """Least-squares rigid transform mapping A -> B (both (N,3))."""
    ca, cb = A.mean(0), B.mean(0)
    H = (A - ca).T @ (B - cb)
    U, _, Vt = np.linalg.svd(H)
    D = np.diag([1.0, 1.0, float(np.sign(np.linalg.det(Vt.T @ U.T)))])
    R = Vt.T @ D @ U.T
    return R, cb - R @ ca


def add_mesh(name, verts, faces, mat=None):
    me = bpy.data.meshes.new(name)
    me.from_pydata([tuple(float(x) for x in v) for v in verts], [],
                   [tuple(int(x) for x in f) for f in faces])
    me.update()
    ob = bpy.data.objects.new(name, me)
    bpy.context.scene.collection.objects.link(ob)
    if mat is not None:
        ob.data.materials.append(mat)
    return ob


def add_rb(ob, rbtype, shape, mass=1.0, friction=0.5, restitution=0.5,
           lin_damp=0.04, ang_damp=0.04, kinematic=False, margin=0.001):
    # deselect everything first: the operator acts on ALL selected objects
    for other in bpy.context.selected_objects:
        other.select_set(False)
    bpy.context.view_layer.objects.active = ob
    ob.select_set(True)
    try:
        bpy.ops.rigidbody.objects_add(type=rbtype)
    except RuntimeError:
        with bpy.context.temp_override(active_object=ob, object=ob,
                                       selected_objects=[ob],
                                       selected_editable_objects=[ob]):
            bpy.ops.rigidbody.objects_add(type=rbtype)
    rb = ob.rigid_body
    rb.collision_shape = shape
    rb.mass = mass
    rb.friction = friction
    rb.restitution = restitution
    rb.linear_damping = lin_damp
    rb.angular_damping = ang_damp
    rb.use_margin = True
    rb.collision_margin = margin
    rb.kinematic = kinematic
    return rb


def mat_simple(name, rgb):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    bsdf = m.node_tree.nodes["Principled BSDF"]
    bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
    bsdf.inputs["Roughness"].default_value = 0.6
    return m


def setup_cycles(scene, samples, use_gpu):
    scene.render.engine = "CYCLES"
    if use_gpu:
        prefs = bpy.context.preferences.addons["cycles"].preferences
        for ctype in ("OPTIX", "CUDA"):
            try:
                prefs.compute_device_type = ctype
                prefs.get_devices()
                devs = [d for d in prefs.devices if d.type == ctype]
                if devs:
                    for d in prefs.devices:
                        d.use = d.type == ctype
                    scene.cycles.device = "GPU"
                    print(f"[cycles] using {ctype}: {[d.name for d in devs]}")
                    return
            except Exception as e:
                print(f"[cycles] {ctype} failed: {e}")
        print("[cycles] no GPU backend, falling back to CPU")
    scene.cycles.device = "CPU"


def main():
    args = parse_args()
    world = Path(args.world)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)

    spec = json.loads((world / "spec.json").read_text())
    cam = json.loads((world / "camera.json").read_text())
    K = np.array(cam["intrinsics"], float)
    E = np.array(cam["extrinsic"], float)
    F = int(spec["F"])
    W, H = spec["video"]["width"], spec["video"]["height"]
    fps = float(spec["video"]["fps"])

    # ---------- clean scene ----------
    scene = bpy.context.scene
    for ob in list(bpy.data.objects):
        bpy.data.objects.remove(ob, do_unlink=True)

    mats = {"ball": mat_simple("m_ball", (0.10, 0.25, 0.75)),
            "pin": mat_simple("m_pin", (0.92, 0.92, 0.90)),
            "deck": mat_simple("m_deck", (0.25, 0.15, 0.10)),
            "static": mat_simple("m_static", (0.55, 0.55, 0.58))}

    # ---------- rigid body world ----------
    if scene.rigidbody_world is None:
        bpy.ops.rigidbody.world_add()
    rbw = scene.rigidbody_world
    rbw.substeps_per_frame = args.substeps
    rbw.solver_iterations = args.iters
    rbw.point_cache.frame_start = 1
    rbw.point_cache.frame_end = F
    scene.gravity = (0.0, 0.0, -9.81)

    dyn = {}
    for name in spec["dynamics"]:
        z = np.load(world / "dyn" / f"{name}.npz")
        dyn[name] = {"pos": z["pos"], "ids": z["ids"].tolist()}

    kin_name = args.kinematic or next(iter(dyn))
    active_names = [n for n in dyn if n != kin_name]
    static_ids = [int(m) for m, v in spec["meshes"].items() if v["static"]]

    # ---------- static geometry ----------
    for mid in static_ids:
        z = np.load(world / "mesh" / f"{mid}.npz")
        mat = mats["deck"] if z["vertices"].shape[1] <= 4 else mats["static"]
        ob = add_mesh(f"static_{mid}", z["vertices"][0], z["faces"][0], mat)
        add_rb(ob, "PASSIVE", "MESH", margin=0.001)

    # ---------- kinematic driver (replay baked trajectory) ----------
    driver_pos = dyn[kin_name]["pos"]  # (F,N,3)
    drv_ids = dyn[kin_name]["ids"]
    z = np.load(world / "mesh" / f"{drv_ids[0]}.npz")
    drv_ob = add_mesh(kin_name, z["vertices"][0], z["faces"][0], mats["ball"])
    drv_verts0 = z["vertices"][0].astype(np.float64)
    for t in range(F):
        R, tt = rigid_tf(driver_pos[0].astype(np.float64), driver_pos[t].astype(np.float64))
        drv_ob.location = Vector(tt)
        drv_ob.rotation_euler = Matrix(R).to_euler()
        drv_ob.keyframe_insert("location", frame=t + 1)
        drv_ob.keyframe_insert("rotation_euler", frame=t + 1)
    for fc in drv_ob.animation_data.action.fcurves:
        for kp in fc.keyframe_points:
            kp.interpolation = "LINEAR"
    add_rb(drv_ob, "PASSIVE", "CONVEX_HULL", kinematic=True, margin=0.002)

    # ---------- active bodies (parameter card) ----------
    actives = {}
    for name in active_names:
        ids = dyn[name]["ids"]
        z = np.load(world / "mesh" / f"{ids[0]}.npz")
        ob = add_mesh(name, z["vertices"][0], z["faces"][0], mats["pin"])
        add_rb(ob, "ACTIVE", "CONVEX_HULL", mass=args.mass, friction=args.friction,
               restitution=args.restitution, lin_damp=args.lin_damp,
               ang_damp=args.ang_damp, margin=0.001)
        actives[name] = (ob, z["vertices"][0].astype(np.float64))

    # ---------- camera ----------
    print("[rb-check] " + ", ".join(
        f"{o.name}:{o.rigid_body.type}{'/K' if o.rigid_body.kinematic else ''}"
        for o in bpy.data.objects if o.rigid_body))
    cam_data = bpy.data.cameras.new("cam")
    cam_data.sensor_fit = "HORIZONTAL"
    cam_data.sensor_width = 36.0
    cam_data.lens = float(K[0, 0]) * 36.0 / W
    cam_ob = bpy.data.objects.new("cam", cam_data)
    bpy.context.scene.collection.objects.link(cam_ob)
    D = Matrix.Diagonal((1.0, -1.0, -1.0, 1.0))  # cam axes (x right, y down, z fwd) -> Blender (-Z fwd)
    cam_ob.matrix_world = Matrix(E) @ D
    scene.camera = cam_ob

    # camera sanity: project driver COM at frame 0 both ways
    p0 = Vector(driver_pos[0].mean(0))
    import bpy_extras
    uv = bpy_extras.object_utils.world_to_camera_view(scene, cam_ob, p0)
    pc = E[:3, :3].T @ (np.asarray(p0) - E[:3, 3])
    proj = K @ pc
    u_px, v_px = float(proj[0]) / float(pc[2]), float(proj[1]) / float(pc[2])
    print(f"[cam-check] blender uv=({uv.x:.3f},{uv.y:.3f})  numpy px=({u_px:.1f},{v_px:.1f})/"
          f"({W},{H})  expect uv≈({u_px/W:.3f},{1-v_px/H:.3f})")

    # ---------- lights ----------
    world = bpy.data.worlds.new("w")
    world.use_nodes = True
    world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.85, 0.85, 0.85, 1)
    world.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.1
    scene.world = world
    sun = bpy.data.lights.new("sun", type="SUN")
    sun.energy = 3.0
    sun_ob = bpy.data.objects.new("sun", sun)
    bpy.context.scene.collection.objects.link(sun_ob)
    sun_ob.rotation_euler = (radians(50), 0, radians(30))

    # ---------- bake ----------
    scene.frame_start = 1
    scene.frame_end = F
    scene.frame_set(1)
    bpy.ops.ptcache.free_bake_all()
    bpy.ops.ptcache.bake_all(bake=True)
    print("[bake] done")

    # ---------- record trajectories ----------
    traj = {kin_name: np.zeros((F, 3), np.float32)}
    for name, (ob, v0) in actives.items():
        traj[name] = np.zeros((F, 3), np.float32)
    for t in range(1, F + 1):
        scene.frame_set(t)
        bpy.context.view_layer.update()
        M = np.array(drv_ob.matrix_world)
        traj[kin_name][t - 1] = (M[:3, :3] @ drv_verts0.T).T.mean(0)
        for name, (ob, v0) in actives.items():
            M = np.array(ob.matrix_world)
            traj[name][t - 1] = (M[:3, :3] @ v0.T).T.mean(0)
    np.savez_compressed(out / "simtraj.npz", **traj)
    print(f"[traj] saved {list(traj)}")

    # ---------- render ----------
    scene.render.resolution_x = W
    scene.render.resolution_y = H
    scene.render.fps = int(round(fps))
    scene.render.fps_base = 1.0
    scene.cycles.samples = args.samples
    scene.cycles.use_denoising = True
    scene.cycles.max_bounces = 4
    setup_cycles(scene, args.samples, args.device == "gpu")
    scene.render.image_settings.file_format = "FFMPEG"
    scene.render.ffmpeg.format = "MPEG4"
    scene.render.ffmpeg.codec = "H264"
    scene.render.ffmpeg.constant_rate_factor = "HIGH"
    scene.render.ffmpeg.audio_codec = "NONE"
    scene.render.filepath = str(out / "sim.mp4")
    bpy.ops.render.render(animation=True)
    print(f"[render] wrote {out/'sim.mp4'}")


if __name__ == "__main__":
    main()