File size: 13,081 Bytes
80f0adb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Verify estimated pose by rendering the scene with the target object at the estimated position.
"""

import json
import os

import imageio
import numpy as np
import trimesh
from scipy.spatial.transform import Rotation as R
from trimesh.transformations import euler_matrix

import genesis as gs


def render_with_estimated_pose(
    output_dir: str,
    object_mesh_path: str,
    container_mesh_path: str,
    table_path: str = "../video_gen_assets/table.glb",
    use_icp_pose: bool = True,
    use_physics_pose: bool = False,
    use_physics_initial: bool = False,
    container_euler: list = None,
    pose_idx: int = None,
    wall_mode: bool = False,
    wall_x: float = -0.5,
    wall_height: float = 1.2,
    container_pos: list = None,
    object_scale: float = 1.0,
):
    """Render scene with target object at estimated pose."""

    pose_label = "estimated"

    if use_physics_pose or use_physics_initial:
        # Load physics-refined pose
        pose_path = os.path.join(output_dir, "physics_refinement", "refined_poses.json")
        with open(pose_path, "r") as f:
            pose_data = json.load(f)

        if pose_idx is not None:
            best_pose = pose_data["valid_poses"][pose_idx]
            print(f"Using physics pose at index {pose_idx}")
        else:
            best_pose = pose_data.get("best_pose")
        if best_pose is None:
            raise ValueError("No valid physics-refined pose found")

        if use_physics_initial:
            # Use initial pose (before physics settling)
            if "init_pos" not in best_pose:
                raise ValueError("Initial pose not stored. Re-run physics refinement.")
            tvec_w = np.array(best_pose["init_pos"])
            quat_wxyz = best_pose["init_quat_wxyz"]
            pose_label = "physics_initial"
            print("Using physics INITIAL pose (before settling)")
        else:
            # Use final pose (after physics settling)
            tvec_w = np.array(best_pose["pos"])
            quat_wxyz = best_pose["quat_wxyz"]
            pose_label = "physics_final"
            print("Using physics FINAL pose (after settling)")

        # Convert quaternion to rotation vector
        quat_xyzw = [quat_wxyz[1], quat_wxyz[2], quat_wxyz[3], quat_wxyz[0]]
        rvec_w = R.from_quat(quat_xyzw).as_rotvec()
        print(f"Stability: pos_drift={best_pose['pos_drift']:.4f}m, rot_drift={best_pose['rot_drift_deg']:.2f}°")
    else:
        # Load estimated pose
        pose_path = os.path.join(output_dir, "pose_estimation", "best_pose.json")
        with open(pose_path, "r") as f:
            pose_data = json.load(f)

        if use_icp_pose and "tvec_w_icp" in pose_data:
            tvec_w = np.array(pose_data["tvec_w_icp"])
            rvec_w = np.array(pose_data["rvec_w_icp"])
            print("Using ICP-refined pose")
        else:
            tvec_w = np.array(pose_data["tvec_w"])
            rvec_w = np.array(pose_data["rvec_w"])
            print("Using 3D-3D registration pose")

    print(f"Position: {tvec_w}")
    print(f"Rotation (rotvec): {rvec_w}")

    # Convert rotation vector to quaternion (scalar-first for Genesis)
    rot = R.from_rotvec(rvec_w)
    quat_xyzw = rot.as_quat()  # [x, y, z, w]
    quat_wxyz = np.array([quat_xyzw[3], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2]])  # [w, x, y, z]

    # Load camera parameters
    cam_pose = np.load(os.path.join(output_dir, "cam_pose.npy"))
    intrinsic_K = np.load(os.path.join(output_dir, "intrinsic_K.npy"))

    # Extract camera position from pose matrix
    # cam_pose is camera-to-world transform (OpenCV convention: Z points into scene)
    cam_pos = cam_pose[:3, 3]

    # Camera Z axis in world frame (third column of rotation) points into the scene
    forward = cam_pose[:3, 2]

    # Lookat point is camera position + forward direction
    lookat = cam_pos + forward * 1.0  # Look 1 meter ahead

    print(f"Camera position: {cam_pos}")
    print(f"Camera forward: {forward}")
    print(f"Camera lookat: {lookat}")

    # Initialize Genesis
    gs.init(seed=0, precision="32", logging_level="warning")

    # Use same HDR environment + lighting as place_scene.py
    DEFAULT_HDR_PATH = os.environ.get(
        "DEMO_HDR_PATH",
        os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "..", "video_gen_assets",
            "9286496a-b761-4bdf-9f08-7966281b9c69.hdr",
        ),
    )
    renderer_kwargs = {
        "env_radius": 200.0,
        "lights": [
            {"pos": (0, -70, 40), "color": (255.0, 255.0, 255.0),
             "radius": 7, "intensity": 0.42},
        ],
    }
    if os.path.exists(DEFAULT_HDR_PATH):
        renderer_kwargs["env_surface"] = gs.surfaces.Emission(
            emissive_texture=gs.textures.ImageTexture(
                image_path=DEFAULT_HDR_PATH,
                image_color=(0.5, 0.5, 0.5),
            )
        )

    scene = gs.Scene(
        sim_options=gs.options.SimOptions(dt=0.01, substeps=5, gravity=(0, 0, -9.8)),
        show_viewer=False,
        rigid_options=gs.options.RigidOptions(enable_collision=False),
        renderer=gs.renderers.RayTracer(**renderer_kwargs),
    )

    # Add camera with same parameters as original render
    cam = scene.add_camera(
        pos=tuple(cam_pos),
        lookat=tuple(lookat),
        res=(1200, 896),
        fov=50.0,
        GUI=False,
        spp=1024,
    )

    mat_rigid = gs.materials.Rigid()

    if wall_mode:
        # Wall-mounted scene (e.g., hanger_hooks)
        from place_scene import add_wall, DEFAULT_WALL_TEXTURE
        c_euler = container_euler if container_euler is not None else [-180, 0, 90]

        # Add wall
        if os.path.exists(DEFAULT_WALL_TEXTURE):
            add_wall(scene, wall_x, wall_x, -3, 3, height=3.0,
                     texture=DEFAULT_WALL_TEXTURE, wall_id=0)

        # Place container flush against wall at wall_height
        crx, cry, crz = np.deg2rad(c_euler)
        cmesh = trimesh.load(container_mesh_path, force="mesh")
        cmesh.apply_transform(euler_matrix(crx, cry, crz, "sxyz"))
        min_x = cmesh.bounds[0][0]
        container_x = wall_x - min_x
        container_entity = scene.add_entity(
            material=mat_rigid,
            morph=gs.morphs.Mesh(
                file=container_mesh_path,
                pos=[container_x, 0.0, wall_height],
                euler=c_euler,
                collision=False,
            ),
            surface=gs.surfaces.Plastic(),
        )
    else:
        # Table-mounted scene (default)
        scene.add_entity(
            material=mat_rigid,
            morph=gs.morphs.Mesh(
                file=table_path,
                pos=[0.0, 0.0, 0.485403],
                euler=[90, 0, 90],
                collision=False,
            ),
        )

        # Background wall (same as place_scene.py)
        DEFAULT_WALL_TEXTURE = os.environ.get(
            "DEMO_WALL_TEXTURE",
            os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                "..", "video_gen_assets", "wall-basecolor.jpg",
            ),
        )
        if os.path.exists(DEFAULT_WALL_TEXTURE):
            from place_scene import add_wall
            add_wall(scene, -0.345, -0.345, -3, 3,
                     texture=DEFAULT_WALL_TEXTURE, wall_id=0)

        c_euler = container_euler if container_euler is not None else [90, 0, 0]
        table_height = 0.7451
        if container_pos is not None:
            c_pos = list(container_pos)
            print(f"Container placed at pos={c_pos} (override)")
        else:
            crx, cry, crz = np.deg2rad(c_euler)
            cmesh = trimesh.load(container_mesh_path, force="mesh")
            cmesh.apply_transform(euler_matrix(crx, cry, crz, "sxyz"))
            container_z = table_height - cmesh.bounds[0][2]
            c_pos = [0.0, 0.0, container_z]
            print(f"Container auto-placed at z={container_z:.4f}")
        container_entity_kwargs = {
            "material": mat_rigid,
            "morph": gs.morphs.Mesh(
                file=container_mesh_path,
                pos=c_pos,
                euler=c_euler,
                collision=False,
            ),
        }
        # Match place_scene.py: only apply Metal surface to .obj files
        if container_mesh_path.endswith(".obj"):
            container_entity_kwargs["surface"] = gs.surfaces.Metal()
        container_entity = scene.add_entity(**container_entity_kwargs)

    # Add target object (mug) at estimated pose
    # Convert euler to degrees for Genesis
    euler_deg = rot.as_euler('xyz', degrees=True)

    target_mesh_kwargs = {
        "file": object_mesh_path,
        "pos": list(tvec_w),
        "quat": list(quat_wxyz),
        "collision": False,
    }
    if object_scale != 1.0:
        target_mesh_kwargs["scale"] = object_scale
    target_entity = scene.add_entity(
        material=mat_rigid,
        morph=gs.morphs.Mesh(**target_mesh_kwargs),
    )

    scene.build()

    # Render
    img, depth, seg, _ = cam.render(depth=True, segmentation=True)

    # Save outputs
    verify_dir = os.path.join(output_dir, "pose_verification")
    os.makedirs(verify_dir, exist_ok=True)

    output_path = os.path.join(verify_dir, f"rendered_at_{pose_label}_pose.png")
    imageio.imwrite(output_path, img)
    print(f"\nSaved verification render: {output_path}")

    # Also save a comparison side-by-side
    goal_image_path = os.path.join(output_dir, "image_goal.png")
    if os.path.exists(goal_image_path):
        goal_img = imageio.imread(goal_image_path)

        # Resize if needed
        if goal_img.shape[:2] != img.shape[:2]:
            from PIL import Image
            goal_pil = Image.fromarray(goal_img)
            goal_pil = goal_pil.resize((img.shape[1], img.shape[0]), Image.BILINEAR)
            goal_img = np.array(goal_pil)

        # Create side-by-side comparison
        comparison = np.concatenate([goal_img[:, :, :3], img], axis=1)
        comparison_path = os.path.join(verify_dir, "comparison_goal_vs_estimated.png")
        imageio.imwrite(comparison_path, comparison)
        print(f"Saved comparison: {comparison_path}")

    return img


def main():
    import argparse

    parser = argparse.ArgumentParser(description="Verify estimated pose by rendering")
    parser.add_argument("--output_dir", type=str, default="./outputs/mug_tree_goal",
                        help="Output directory with pipeline outputs")
    parser.add_argument("--object_mesh_path", type=str, default="./assets/mug_0.glb",
                        help="Path to target object mesh")
    parser.add_argument("--container_mesh_path", type=str,
                        default="./assets/metal_mug_holder/metal_mug_holder.obj",
                        help="Path to container mesh")
    parser.add_argument("--table_path", type=str,
                        default="../video_gen_assets/table.glb",
                        help="Path to table mesh")
    parser.add_argument("--no_icp", action="store_true",
                        help="Use pose before ICP refinement")
    parser.add_argument("--physics", action="store_true",
                        help="Use physics-refined final pose (after settling)")
    parser.add_argument("--physics_initial", action="store_true",
                        help="Use physics initial pose (before settling)")
    parser.add_argument("--container_euler", type=float, nargs=3, default=None,
                        help="Container euler angles (default: [90, 0, 0])")
    parser.add_argument("--pose_idx", type=int, default=None,
                        help="Index into valid_poses (default: use best_pose)")
    parser.add_argument("--container_pos", type=float, nargs=3, default=None,
                        help="Override container position [x y z] (default: auto-compute from mesh bounds)")
    parser.add_argument("--wall", action="store_true",
                        help="Use wall-mounted scene instead of table")
    parser.add_argument("--wall_x", type=float, default=-0.5,
                        help="X position of wall plane (default: -0.5)")
    parser.add_argument("--wall_height", type=float, default=1.2,
                        help="Z height to mount container on wall (default: 1.2)")
    parser.add_argument("--object_scale", type=float, default=1.0,
                        help="Scale factor for target object mesh (default: 1.0)")

    args = parser.parse_args()

    render_with_estimated_pose(
        output_dir=args.output_dir,
        object_mesh_path=args.object_mesh_path,
        container_mesh_path=args.container_mesh_path,
        table_path=args.table_path,
        use_icp_pose=not args.no_icp,
        use_physics_pose=args.physics,
        use_physics_initial=args.physics_initial,
        container_euler=args.container_euler,
        pose_idx=args.pose_idx,
        wall_mode=args.wall,
        wall_x=args.wall_x,
        wall_height=args.wall_height,
        container_pos=args.container_pos,
        object_scale=args.object_scale,
    )


if __name__ == "__main__":
    main()