File size: 4,583 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
"""Rest attitude for a reconstructed SAM3D object on a Z-up table.

The generated URDF applies no ``rpy``, so identity in Isaac Lab lays the object on
its side. The clip quaternion has the right attitude but is tilted a few degrees,
which is enough to roll a box. Snap that tilt out, keep the clip's yaw and its
resting face, and sit the origin on the lowest vertex.
"""

from __future__ import annotations

import re
from pathlib import Path

import numpy as np

from .math_np import quat_mul_wxyz, quat_rotate

_MESH_RE = re.compile(
    r'filename="([^"]+\.obj)".*?scale="([0-9.eE+-]+)',
    re.IGNORECASE | re.DOTALL,
)


def urdf_mesh(urdf: str | Path) -> tuple[Path, float] | None:
    path = Path(urdf)
    if not path.is_file():
        return None
    text = path.read_text()
    m = _MESH_RE.search(text)
    if m is None:
        return None
    mesh = (path.parent / m.group(1)).resolve()
    if not mesh.is_file():
        return None
    return mesh, float(m.group(2))


def load_obj_verts(mesh: Path, scale: float) -> np.ndarray:
    verts: list[list[float]] = []
    with mesh.open() as f:
        for line in f:
            if line.startswith("v "):
                verts.append([float(x) for x in line.split()[1:4]])
    if not verts:
        raise RuntimeError(f"no vertices in {mesh}")
    return np.asarray(verts, dtype=np.float64) * float(scale)


def _quat_align_wxyz(src: np.ndarray, dst: np.ndarray) -> np.ndarray:
    """Shortest rotation taking ``src`` onto ``dst`` (wxyz)."""
    a = np.asarray(src, dtype=np.float64)
    b = np.asarray(dst, dtype=np.float64)
    a = a / (np.linalg.norm(a) + 1e-12)
    b = b / (np.linalg.norm(b) + 1e-12)
    ax = np.cross(a, b)
    s = float(np.linalg.norm(ax))
    c = float(np.dot(a, b))
    if s < 1e-9:
        return np.array([1.0, 0.0, 0.0, 0.0] if c > 0.0 else [0.0, 1.0, 0.0, 0.0])
    ax = ax / s
    half = 0.5 * np.arctan2(s, c)
    return np.concatenate([[np.cos(half)], ax * np.sin(half)])


#: The six signed body axes, candidates for the one the object rests on.
_BODY_AXES = np.vstack([np.eye(3), -np.eye(3)])


def upright_body_axis(clip_wxyz: np.ndarray) -> np.ndarray:
    """The body axis the clip already points most nearly upward.

    Which way a SAM3D mesh is "up" is not a fixed convention: the coffee can rests
    on body +Y, the sugar box on -Y. Reading it off the demonstration avoids
    assuming, and avoids standing an object on a face the human never rested it on.
    """
    q = np.asarray(clip_wxyz, dtype=np.float64)
    q = q / (np.linalg.norm(q) + 1e-12)
    world = quat_rotate(np.tile(q, (len(_BODY_AXES), 1)), _BODY_AXES)
    return _BODY_AXES[int(np.argmax(world[:, 2]))]


def flatten_upright_wxyz(
    clip_wxyz: np.ndarray,
    up_axis: np.ndarray | None = None,
) -> np.ndarray:
    """Drop the clip's residual tilt, keeping its yaw and its resting face.

    A few degrees of tilt is enough to roll a box, so the axis nearest vertical is
    snapped exactly to world +Z. ``up_axis`` defaults to :func:`upright_body_axis`.
    """
    q = np.asarray(clip_wxyz, dtype=np.float64)
    q = q / (np.linalg.norm(q) + 1e-12)
    axis = upright_body_axis(q) if up_axis is None else np.asarray(up_axis, dtype=np.float64)
    up_w = quat_rotate(q, axis)
    return quat_mul_wxyz(_quat_align_wxyz(up_w, np.array([0.0, 0.0, 1.0])), q)


def demo_rest_wxyz(urdf: str | Path) -> np.ndarray | None:
    """Object attitude at the moment it sits lowest in the clip, i.e. on the table.

    Frame 0 is not reliable: some clips open with the object already lifted.
    """
    replay = Path(urdf).resolve().parent.parent / "isaaclab_replay.npz"
    if not replay.is_file():
        return None
    data = np.load(replay, allow_pickle=True)
    if "object_wxyz" not in data or "object_pos" not in data:
        return None
    pos, quat = data["object_pos"], data["object_wxyz"]
    if len(pos) == 0:
        return None
    return np.asarray(quat[int(np.argmin(pos[:, 2]))], dtype=np.float64)


def support_height(verts: np.ndarray, wxyz: np.ndarray) -> float:
    vr = quat_rotate(np.tile(np.asarray(wxyz, dtype=np.float64), (len(verts), 1)), verts)
    return float(-vr[:, 2].min())


def rest_pose(
    urdf: str | Path,
    clip_wxyz: np.ndarray,
) -> tuple[np.ndarray, float] | None:
    """``(wxyz, origin height above table)`` for a firm rest, or None if no mesh."""
    parsed = urdf_mesh(urdf)
    if parsed is None:
        return None
    mesh, scale = parsed
    verts = load_obj_verts(mesh, scale)
    q = flatten_upright_wxyz(clip_wxyz)
    return q, support_height(verts, q)