File size: 23,960 Bytes
a84ddf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"""Build the objects of our robocurve-inspired tasks (rc_*, PROD-120) from boxes and cylinders, as RoboDojo objects.

    /data1/viet/venv/usdtools/bin/python dev_suite/robocurve/make_objects.py [--out $ROBOCURVE_OBJECTS]

Needs `pxr` and `trimesh`. Writes, under --out (default $ROBOCURVE_OBJECTS or /data1/viet/robocurve_objects):

    <Rigid|Geometry|Articulation>/rc_<name>/00000/object.usd, metadata.json, description.json

scripts/install_into_robodojo.sh links them into RoboDojo's Assets/Object/RoboDojo. Every part is its own convex
collision mesh. As in RoboDojo's objects the bbox centre is the origin (articulations: in their rest pose, joints at 0).
Rigid: RoboDojo sets mass and friction from metadata.json (mass capped at 0.5 kg). Articulation: the masses and the
friction are in the USD (RoboDojo sets neither); the first link is the base (`fixed_base` in the layout pins it), and
`metadata.passive.functional` names each joint under its tag, for the joint-ratio checks.

Sizes: metres, the asset frame, x to the robot's right, y away from it, z up, as the objects stand in the scene at yaw 0.
The ARX X5 gripper opens about 8.8 cm: a part meant to be "wider than the gripper" is 11 cm or more.
"""

from __future__ import annotations

import argparse
import json
import math
import os
import uuid
from pathlib import Path

import numpy as np
import trimesh
from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics, UsdShade

HERE = Path(__file__).resolve().parent
COLOURS = {
    "pine": (0.80, 0.62, 0.38), "wood": (0.36, 0.22, 0.12), "grey": (0.55, 0.56, 0.58), "dark": (0.22, 0.23, 0.25),
    "steel": (0.70, 0.72, 0.75), "blue": (0.15, 0.35, 0.80), "red": (0.80, 0.12, 0.10), "green": (0.20, 0.60, 0.25),
    "yellow": (0.95, 0.80, 0.10), "white": (0.92, 0.92, 0.90), "kraft": (0.66, 0.50, 0.32), "tan": (0.78, 0.66, 0.48),
    "orange": (0.95, 0.45, 0.10), "black": (0.08, 0.08, 0.09),
}


def box(size, at=(0, 0, 0), colour="grey"):
    return {"shape": "box", "size": list(size), "at": list(at), "colour": colour}


def cyl(radius, length, at=(0, 0, 0), axis="z", colour="grey", sections=24):
    """A cylinder; few `sections` make a prism that does not roll."""
    return {"shape": "cyl", "radius": radius, "length": length, "at": list(at), "axis": axis, "colour": colour,
            "sections": sections}


def walls(inner_x, inner_y, height, t, floor, colour, at=(0.0, 0.0), z=0.0):
    """An open-top tray / bin from z up: floor `floor` thick (0: none), four walls `t` thick, inside inner_x by inner_y."""
    x0, y0 = at
    ox = inner_x + 2 * t
    parts = [box((ox, t, height), (x0, y0 - (inner_y + t) / 2, z + height / 2), colour),
             box((ox, t, height), (x0, y0 + (inner_y + t) / 2, z + height / 2), colour),
             box((t, inner_y, height), (x0 - (inner_x + t) / 2, y0, z + height / 2), colour),
             box((t, inner_y, height), (x0 + (inner_x + t) / 2, y0, z + height / 2), colour)]
    if floor:
        parts.append(box((inner_x, inner_y, floor), (x0, y0, z + floor / 2), colour))
    return parts


# ----------------------------------------------------------------------------------------------------------------------
# name -> spec. kind: Rigid | Geometry | Articulation. Rigid: parts, mass, friction. Articulation: links {name: {parts,
# mass}}, the first one the base, and joints. desc: the words of description.json (the agent never sees them).
OBJECTS = {
    # rc_plank_unload (idea: plank-unload)
    "rc_plank": {"kind": "Rigid", "mass": 0.24, "friction": 0.6, "desc": "pine plank",
                 "parts": [box((0.40, 0.08, 0.015), colour="pine")]},
    "rc_fulcrum": {"kind": "Geometry", "desc": "wooden block",
                   "parts": [box((0.08, 0.10, 0.10), colour="wood")]},
    "rc_steel_block": {"kind": "Rigid", "mass": 0.38, "friction": 0.6, "desc": "steel block",
                       "parts": [box((0.04, 0.04, 0.03), colour="steel")]},
    "rc_tray": {"kind": "Geometry", "desc": "blue tray",
                "parts": walls(0.16, 0.12, 0.03, 0.008, 0.004, "blue")},
    # rc_carry_box_stack (idea: carry-a-stack-of-three-boxes-as-one-with-both-arms)
    "rc_box_long": {"kind": "Rigid", "mass": 0.12, "friction": 0.7, "desc": "long cardboard box",
                    "parts": [box((0.22, 0.06, 0.05), colour="kraft")]},  # 6 cm deep: a sure pinch
    "rc_box_mid": {"kind": "Rigid", "mass": 0.06, "friction": 0.7, "desc": "cardboard box",
                   "parts": [box((0.12, 0.06, 0.035), colour="tan")]},
    "rc_box_small": {"kind": "Rigid", "mass": 0.04, "friction": 0.7, "desc": "small cardboard box",
                     "parts": [box((0.08, 0.05, 0.03), colour="kraft")]},
    "rc_platform": {"kind": "Geometry", "desc": "grey platform",
                    "parts": [box((0.26, 0.16, 0.06), colour="grey")]},
    # rc_box_on_edge_in_slot (idea: box-on-edge-in-slot): the riser and the wall, 11.5 cm apart, on one base plate
    "rc_flat_box": {"kind": "Rigid", "mass": 0.2, "friction": 1.0, "desc": "flat white box",
                    "poses": {"edge": [math.sqrt(0.5), 0.0, math.sqrt(0.5), 0.0]},  # on end: its 20 cm side upright
                    "parts": [box((0.20, 0.12, 0.09), colour="white")]},
    "rc_slot_riser": {"kind": "Geometry", "desc": "wooden riser and wall with a slot between",
                      "parts": [box((0.12, 0.12, 0.10), (0.06, 0.0, 0.05), "wood"),
                                box((0.015, 0.14, 0.09), (-0.115 - 0.0075, 0.0, 0.045), "wood")]},
    # rc_turn_parcel_into_bay (idea: turn-parcel-into-bay)
    "rc_parcel": {"kind": "Rigid", "mass": 0.5, "friction": 0.5, "desc": "long brown parcel",
                  "parts": [box((0.42, 0.14, 0.10), colour="kraft")]},
    "rc_white_box": {"kind": "Rigid", "mass": 0.5, "friction": 0.8, "desc": "white box",
                     "parts": [box((0.16, 0.14, 0.10), colour="white")]},
    # the bay: red tape marks 0.16 wide and 0.46 long (along y) and a stop bar across its far end; two bollards 0.37
    # apart (less than the parcel) in front of the parcel's far side, so it cannot be shoved round
    "rc_bay": {"kind": "Geometry", "desc": "taped bay with a stop bar",
               "parts": [box((0.01, 0.46, 0.002), (-0.085, 0.0, 0.001), "red"),
                         box((0.01, 0.46, 0.002), (0.085, 0.0, 0.001), "red"),
                         box((0.18, 0.01, 0.002), (0.0, -0.225, 0.001), "red"),
                         box((0.18, 0.02, 0.03), (0.0, 0.24, 0.015), "yellow")]},
    "rc_bollard": {"kind": "Geometry", "desc": "yellow bollard", "parts": [box((0.03, 0.03, 0.08), colour="yellow")]},
    # rc_bin_from_lane (idea: pull-reject-bin-from-flow-lane): a lane along x sloping down to +x, its stop at the low end
    "rc_lane": {"kind": "Geometry", "desc": "sloped flow lane", "slope": {"deg": 12.0, "axis": "y", "low": "+x"},
                "friction": 0.0,  # RoboDojo averages friction: with the bins' 0.35 that is 0.175, under tan 12 deg = 0.21
                "parts": [box((0.50, 0.13, 0.01), (0.0, 0.0, 0.005), "dark"),
                          box((0.50, 0.008, 0.03), (0.0, -0.069, 0.015), "steel"),  # rails 2 cm over the bed: a hand
                          box((0.50, 0.008, 0.03), (0.0, 0.069, 0.015), "steel"),  # on a bin's rim can still open
                          box((0.012, 0.13, 0.05), (0.256, 0.0, 0.025), "yellow")]},
    "rc_lane_bin_red": {"kind": "Rigid", "mass": 0.15, "friction": 0.35, "desc": "red-tagged bin",
                        "parts": walls(0.09, 0.10, 0.07, 0.012, 0.006, "red")},  # 12 mm walls: a sure rim pinch
    "rc_lane_bin": {"kind": "Rigid", "mass": 0.15, "friction": 0.35, "desc": "grey bin",
                    "parts": walls(0.09, 0.10, 0.07, 0.012, 0.006, "grey")},
    "rc_tote": {"kind": "Geometry", "desc": "reject tote", "parts": walls(0.22, 0.20, 0.05, 0.008, 0.006, "orange")},
    # rc_spool_into_saddles (idea: lamp-tube-replace, toilet-roll-spindle): a cable drum too fat to grip, on an axle
    # whose two ends are the only handles; two posts with U notches carry the axle ends
    "rc_spool": {"kind": "Rigid", "mass": 0.45, "friction": 0.8, "desc": "cable spool on an axle",
                 "parts": [cyl(0.06, 0.18, axis="x", colour="orange", sections=8),  # octagonal: it does not roll away
                           cyl(0.0125, 0.42, axis="x", colour="steel")]},
    "rc_saddles": {"kind": "Geometry", "desc": "two posts with notches",
                   "parts": [box((0.03, 0.08, 0.004), (x, 0.0, 0.002), "grey") for x in (-0.175, 0.175)]
                   + [p for x in (-0.175, 0.175) for p in (
                       box((0.03, 0.02, 0.15), (x, -0.03, 0.075), "grey"),  # notch 4 cm wide, 3 cm deep: bottom 12 cm up
                       box((0.03, 0.02, 0.15), (x, 0.03, 0.075), "grey"),
                       box((0.03, 0.03, 0.12), (x, 0.0, 0.06), "grey"))]},
    # rc_mug_into_drawer (idea: open-barred-drawer; a part that closes itself, as in drive-thru-window-serve)
    "rc_drawer_cabinet": {
        "kind": "Articulation", "desc": "cabinet with a self-closing drawer",
        "links": {
            "carcass": {"mass": 2.0, "parts": [
                box((0.30, 0.26, 0.012), (0.0, 0.0, 0.006), "grey"),  # floor
                box((0.30, 0.26, 0.012), (0.0, 0.0, 0.158), "grey"),  # top
                box((0.012, 0.26, 0.14), (-0.144, 0.0, 0.082), "grey"),
                box((0.012, 0.26, 0.14), (0.144, 0.0, 0.082), "grey"),
                box((0.276, 0.012, 0.14), (0.0, 0.124, 0.082), "grey")]},  # back
            "drawer": {"mass": 0.3, "parts": walls(0.24, 0.21, 0.11, 0.008, 0.008, "blue", at=(0.0, -0.005), z=0.013)
                       + [box((0.27, 0.012, 0.13), (0.0, -0.126, 0.077), "blue"),  # front panel
                          box((0.012, 0.04, 0.02), (-0.04, -0.152, 0.10), "black"),  # handle stems and bar: 4 cm
                          box((0.012, 0.04, 0.02), (0.04, -0.152, 0.10), "black"),  # clear of the panel
                          box((0.10, 0.015, 0.02), (0.0, -0.1795, 0.10), "black")]}},
        "joints": [{"name": "drawer_slide", "tag": "drawer", "type": "prismatic", "parent": "carcass", "child": "drawer",
                    "axis": "Y", "at": (0.0, 0.0, 0.07), "lower": -0.20, "upper": 0.0,
                    "drive": {"stiffness": 20.0, "damping": 5.0, "target": 0.0}}],  # a spring pulls it shut (4 N fully open)
        "friction": 0.6},
    # rc_ball_into_lidded_bin (idea: the held-up airbox cover; jack-in-the-box lid): the lid opens 80 deg at most, so it
    # always falls shut
    "rc_lidded_bin": {
        "kind": "Articulation", "desc": "bin with a hinged lid",
        "links": {
            "body": {"mass": 2.0, "parts": walls(0.18, 0.16, 0.12, 0.01, 0.01, "green")},
            "lid": {"mass": 0.25, "parts": [box((0.20, 0.18, 0.01), (0.0, 0.0, 0.125), "dark"),
                                            box((0.06, 0.03, 0.012), (0.0, -0.10, 0.126), "yellow")]}},  # front tab
        "joints": [{"name": "lid_hinge", "tag": "lid", "type": "revolute", "parent": "body", "child": "lid",
                    "axis": "X", "at": (0.0, 0.09, 0.12), "lower": -80.0, "upper": 0.0,
                    "drive": {"stiffness": 0.0, "damping": 0.0005, "target": 0.0}}],
        "friction": 0.6},
    # rc_jar_off_board (idea: pull-board-retrieve)
    "rc_board": {"kind": "Rigid", "mass": 0.27, "friction": 0.5, "desc": "green board",
                 "parts": [box((0.064, 0.48, 0.019), colour="green")]},
    "rc_jar": {"kind": "Rigid", "mass": 0.10, "friction": 0.8, "desc": "small red jar",
               "parts": [cyl(0.0225, 0.05, (0, 0, 0.025), colour="red"), cyl(0.024, 0.012, (0, 0, 0.056), colour="white")]},
    "rc_basket_tray": {"kind": "Geometry", "desc": "blue tray", "parts": walls(0.14, 0.14, 0.06, 0.006, 0.004, "blue")},
    # rc_refit_drawer (idea and sizes: refit-drawer-past-rear-hooks, MIT): a cabinet with two slide rails, and the loose
    # drawer, which rides on them by the lips along its side walls
    "rc_rail_cabinet": {"kind": "Geometry", "desc": "cabinet with drawer slides",
                        "parts": [box((0.34, 0.24, 0.012), (0.0, 0.0, 0.006), "wood"),
                                  box((0.34, 0.24, 0.018), (0.0, 0.0, 0.221), "wood"),  # top 21 cm up: a fingers-down
                                  box((0.018, 0.24, 0.20), (-0.161, 0.0, 0.112), "wood"),  # hand pushing the drawer in
                                  box((0.018, 0.24, 0.20), (0.161, 0.0, 0.112), "wood"),  # keeps its wrist under it
                                  box((0.304, 0.018, 0.20), (0.0, 0.111, 0.112), "wood"),
                                  box((0.012, 0.22, 0.012), (-0.146, -0.005, 0.084), "steel"),  # rails: tops 9 cm up
                                  box((0.012, 0.22, 0.012), (0.146, -0.005, 0.084), "steel")]},
    "rc_loose_drawer": {"kind": "Rigid", "mass": 0.3, "friction": 0.4, "desc": "wooden drawer",
                        "parts": walls(0.24, 0.20, 0.08, 0.008, 0.008, "pine")
                        + [box((0.018, 0.21, 0.010), (x, 0.0, 0.075), "pine") for x in (-0.138, 0.138)]  # lips: over the rails
                        + [box((0.34, 0.012, 0.10), (0.0, -0.112, 0.05), "pine"),  # front panel: stops at the cabinet's face
                           box((0.08, 0.02, 0.015), (0.0, -0.128, 0.07), "black")]},  # pull
    # rc_carry_open_carton (MIT: open-carton-cans): open top, the bottom only two hinged flaps that hang open unless held
    "rc_open_carton": {
        "kind": "Articulation", "desc": "carton with a loose bottom",
        "links": {
            "walls": {"mass": 0.10, "parts": walls(0.144, 0.144, 0.152, 0.004, 0.0, "kraft")},
            "flap_l": {"mass": 0.01, "parts": [box((0.070, 0.140, 0.004), (-0.036, 0.0, 0.002), "tan")]},  # 1-2 mm clear of
            "flap_r": {"mass": 0.01, "parts": [box((0.070, 0.140, 0.004), (0.036, 0.0, 0.002), "tan")]}},  # the walls
        "joints": [{"name": "flap_l_crease", "tag": "flap_l", "type": "revolute", "parent": "walls", "child": "flap_l",
                    "axis": "Y", "at": (-0.072, 0.0, 0.002), "lower": 0.0, "upper": 120.0,
                    "drive": {"stiffness": 0.0, "damping": 0.00002, "target": 0.0}},
                   {"name": "flap_r_crease", "tag": "flap_r", "type": "revolute", "parent": "walls", "child": "flap_r",
                    "axis": "Y", "at": (0.072, 0.0, 0.002), "lower": -120.0, "upper": 0.0,
                    "drive": {"stiffness": 0.0, "damping": 0.00002, "target": 0.0}}],
        "friction": 0.7},
}


# ----------------------------------------------------------------------------------------------------------------------
def mesh(part) -> trimesh.Trimesh:
    if part["shape"] == "box":
        m = trimesh.creation.box(extents=part["size"])
    else:
        m = trimesh.creation.cylinder(radius=part["radius"], height=part["length"], sections=part["sections"])
        m.apply_transform(trimesh.transformations.rotation_matrix(math.pi / part["sections"], [0, 0, 1]))  # a face down
        if part["axis"] != "z":
            m.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0] if part["axis"] == "x" else [1, 0, 0]))
    m.apply_translation(part["at"])
    return m


def all_parts(spec) -> list:
    return spec["parts"] if "parts" in spec else [p for link in spec["links"].values() for p in link["parts"]]


def slope_matrix(spec) -> np.ndarray:
    """A sloped fixture: its parts turned about `axis` so the `low` end is lower (4x4)."""
    s = spec.get("slope")
    if not s:
        return np.eye(4)
    sign = 1.0 if s["low"] == "+x" else -1.0
    return trimesh.transformations.rotation_matrix(math.radians(s["deg"] * sign), [0, 1, 0])


def material(stage, colour: str) -> UsdShade.Material:
    path = f"/root/Looks/{colour}"
    if stage.GetPrimAtPath(path):
        return UsdShade.Material(stage.GetPrimAtPath(path))
    mat = UsdShade.Material.Define(stage, path)
    sh = UsdShade.Shader.Define(stage, path + "/shader")
    sh.CreateIdAttr("UsdPreviewSurface")
    sh.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*COLOURS[colour]))
    sh.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.7)
    mat.CreateSurfaceOutput().ConnectToSource(sh.ConnectableAPI(), "surface")
    return mat


def add_mesh(stage, path: str, m: trimesh.Trimesh, colour: str) -> None:
    g = UsdGeom.Mesh.Define(stage, path)
    g.CreatePointsAttr([Gf.Vec3f(*v) for v in m.vertices.tolist()])
    g.CreateFaceVertexCountsAttr([3] * len(m.faces))
    g.CreateFaceVertexIndicesAttr(m.faces.flatten().tolist())
    g.CreateSubdivisionSchemeAttr("none")
    g.CreateDisplayColorAttr([Gf.Vec3f(*COLOURS[colour])])
    UsdPhysics.CollisionAPI.Apply(g.GetPrim())
    UsdPhysics.MeshCollisionAPI.Apply(g.GetPrim()).CreateApproximationAttr("convexHull")
    UsdShade.MaterialBindingAPI.Apply(g.GetPrim()).Bind(material(stage, colour))


def physics_material(stage, friction: float) -> UsdShade.Material:
    mat = UsdShade.Material.Define(stage, "/root/PhysicsMaterial")
    api = UsdPhysics.MaterialAPI.Apply(mat.GetPrim())
    api.CreateStaticFrictionAttr(friction)
    api.CreateDynamicFrictionAttr(friction)
    api.CreateRestitutionAttr(0.0)
    return mat


def write_usd(path: Path, spec: dict, shift: np.ndarray) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.unlink(missing_ok=True)
    stage = Usd.Stage.CreateNew(str(path))
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
    UsdGeom.SetStageMetersPerUnit(stage, 1.0)
    root = UsdGeom.Xform.Define(stage, "/root")
    stage.SetDefaultPrim(root.GetPrim())
    tilt = slope_matrix(spec)

    def parts_under(prim_path: str, parts: list) -> None:
        for i, part in enumerate(parts):
            m = mesh(part)
            m.apply_transform(tilt)
            m.apply_translation(shift)
            add_mesh(stage, f"{prim_path}/part{i}", m, part["colour"])

    if spec["kind"] != "Articulation":
        if spec["kind"] == "Rigid":
            UsdPhysics.RigidBodyAPI.Apply(root.GetPrim())
        UsdGeom.Xform.Define(stage, "/root/body")
        parts_under("/root/body", spec["parts"])
        stage.GetRootLayer().Save()
        return
    pm = physics_material(stage, spec.get("friction", 0.6))
    links = list(spec["links"])
    for k, name in enumerate(links):
        link = UsdGeom.Xform.Define(stage, f"/root/{name}")
        UsdPhysics.RigidBodyAPI.Apply(link.GetPrim())
        UsdPhysics.MassAPI.Apply(link.GetPrim()).CreateMassAttr(spec["links"][name]["mass"])
        if k == 0:
            UsdPhysics.ArticulationRootAPI.Apply(link.GetPrim())
            link.GetPrim().AddAppliedSchema("PhysxArticulationAPI")  # usd-core has no PhysxSchema: by name
            link.GetPrim().CreateAttribute("physxArticulation:enabledSelfCollisions", Sdf.ValueTypeNames.Bool).Set(False)
        parts_under(f"/root/{name}", spec["links"][name]["parts"])
        for prim in Usd.PrimRange(link.GetPrim()):
            if prim.IsA(UsdGeom.Mesh):
                UsdShade.MaterialBindingAPI(prim).Bind(pm, UsdShade.Tokens.weakerThanDescendants, "physics")
    for j in spec["joints"]:
        at = Gf.Vec3f(*(np.asarray(j["at"]) + shift).tolist())
        jp = f"/root/{j['child']}/{j['name']}"
        joint = (UsdPhysics.PrismaticJoint if j["type"] == "prismatic" else UsdPhysics.RevoluteJoint).Define(stage, jp)
        joint.CreateBody0Rel().SetTargets([f"/root/{j['parent']}"])
        joint.CreateBody1Rel().SetTargets([f"/root/{j['child']}"])
        joint.CreateLocalPos0Attr(at)
        joint.CreateLocalPos1Attr(at)
        joint.CreateAxisAttr(j["axis"])
        joint.CreateLowerLimitAttr(j["lower"])
        joint.CreateUpperLimitAttr(j["upper"])
        kind = "linear" if j["type"] == "prismatic" else "angular"
        d = j["drive"]
        drive = UsdPhysics.DriveAPI.Apply(joint.GetPrim(), kind)
        drive.CreateTypeAttr("force")
        drive.CreateStiffnessAttr(d["stiffness"])
        drive.CreateDampingAttr(d["damping"])
        drive.CreateTargetPositionAttr(d["target"])
        drive.CreateMaxForceAttr(1000.0)
    stage.GetRootLayer().Save()


def resting(q, ext) -> dict:
    """A place tag: turned by q (w, x, y, z; quarter turns), the asset point that touches the plane is the box corner
    lowest in that turn (zero along the axes that stay level)."""
    m = trimesh.transformations.quaternion_matrix(q)[:3, :3]
    point = [round(-math.copysign(e / 2, m[2, i]) if abs(m[2, i]) > 0.5 else 0.0, 4) for i, e in enumerate(ext)]
    flat = sorted(abs(float(np.dot(m[:2, i], m[:2, i]))) * e for i, e in enumerate(ext))
    circle = {"center": point + [1.0, 0.0, 0.0, 0.0], "radius": round(math.hypot(*flat[-2:]) / 2, 4)}
    return {"orientation": [round(float(v), 6) for v in q], "projection_circle": circle, "contact_circle": circle}


def metadata(name: str, spec: dict, ext: list, lo_z: float, mass: float) -> dict:
    hx, hy, hz = (e / 2 for e in ext)
    corners = [[x, y, z] for x in (-hx, hx) for y in (-hy, hy) for z in (-hz, hz)]
    ground = {"center": [0.0, 0.0, round(lo_z, 4), 1.0, 0.0, 0.0, 0.0], "radius": round(math.hypot(ext[0], ext[1]) / 2, 4)}
    meta = {
        "uuid": str(uuid.uuid5(uuid.NAMESPACE_URL, f"robodojo-agent/robocurve/{name}")),
        "physics": {"mass": mass, "friction": spec.get("friction", 0.6), "size": ext},
        "geometry": {"aligned_bbox": {"vertices": corners, "extents": ext},
                     "oriented_bbox": {"vertices": corners, "extents": ext},
                     "bbox": ext, "center": [0.0, 0.0, 0.0], "radius": round(math.sqrt(sum(e * e for e in ext)) / 2, 4)},
        "active": {"place": {"up": {"orientation": [1.0, 0.0, 0.0, 0.0], "projection_circle": ground, "contact_circle": ground}}
                   | {tag: resting(q, ext) for tag, q in spec.get("poses", {}).items()}},
        "robocurve": {"kind": spec["kind"], "description": spec["desc"]},
    }
    if spec["kind"] == "Articulation":
        base = next(iter(spec["links"]))
        meta["passive"] = {"support": {}, "functional": {
            j["tag"]: {"base_link": base, "parent_joint": j["name"], "frame": [[*j["at"], 1.0, 0.0, 0.0, 0.0]],
                       "limits": [j["lower"], j["upper"]]}
            for j in spec["joints"]}}
    return meta


def main() -> None:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--out", type=Path, default=Path(os.environ.get("ROBOCURVE_OBJECTS", "/data1/viet/robocurve_objects")))
    p.add_argument("--only", nargs="*", help="these objects only")
    args = p.parse_args()
    manifest = {}
    for name, spec in OBJECTS.items():
        if args.only and name not in args.only:
            continue
        both = trimesh.util.concatenate([mesh(pt) for pt in all_parts(spec)])
        both.apply_transform(slope_matrix(spec))
        lo, hi = both.bounds
        shift = -(lo + hi) / 2
        ext = [round(float(v), 4) for v in hi - lo]
        mass = spec.get("mass", sum(link["mass"] for link in spec.get("links", {}).values()))
        folder = args.out / spec["kind"] / name / "00000"
        write_usd(folder / "object.usd", spec, shift)
        meta = metadata(name, spec, ext, -ext[2] / 2, round(min(mass, 0.5), 3) if spec["kind"] == "Rigid" else mass)
        (folder / "metadata.json").write_text(json.dumps(meta, indent=1))
        desc = {"uuid": meta["uuid"], "description": [spec["desc"]], "caption": {"name": [spec["desc"]]}}
        (folder / "description.json").write_text(json.dumps(desc, indent=1))
        manifest[name] = {"kind": spec["kind"], "size": ext, "mass": mass, "description": spec["desc"]}
        print(f"{name:22} {spec['kind']:12} size {ext} mass {mass}")
    if not args.only:
        (HERE / "objects.json").write_text(json.dumps(manifest, indent=1) + "\n")
    print(f"{len(manifest)} objects -> {args.out}")


if __name__ == "__main__":
    main()