diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..fd2b26078850191b4c1be004e12882036b982fd6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,23 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/linear_4310/gripper.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_left.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_right.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/model2.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/model2__10.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/model2__11.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/model2__2.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/model2__5.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/environment/world/robot/assets/model2__8.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/linear_4310/gripper.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/linear_4310/tip_left.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/linear_4310/tip_right.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/model2.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/model2__10.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/model2__11.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/model2__2.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/model2__5.stl filter=lfs diff=lfs merge=lfs -text +tasks/belt-pick/tests/world/robot/assets/model2__8.stl filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..be520eb7a2b1d7c13fdf3dc2d9f6caa8ed8a9e85 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +--- +license: apache-2.0 +pretty_name: Workcell Manipulation +tags: +- harbor +- robotics +- mujoco +- manipulation +- agents +size_categories: +- n<1K +--- +# Workcell manipulation + +![Rollouts](assets/rollouts-grid.gif) + +15 Harbor tasks. An agent reads a work request and the cell's data sheets and writes a controller for a +simulated arm in a MuJoCo work cell: Franka Panda (7), SO-101 (4) or I2RT YAM (4). The verifier runs 6 to 30 hidden +episodes with shifted layouts, sensor noise, disturbances and hardware faults. Reward is the mean episode score, +0 to 1. One CPU, 2 GB. + +``` +harbor run --dataset reactive-labs/workcell-manipulation --agent --model +``` + +Apache 2.0. Robot models and skills keep their own licenses. diff --git a/assets/rollouts-grid.gif b/assets/rollouts-grid.gif new file mode 100644 index 0000000000000000000000000000000000000000..94bb89e3e2b3647c9965ed71112c03a5f19f717b --- /dev/null +++ b/assets/rollouts-grid.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59f8958facf7a8cdfbbccfe2c2326182beea9c27a4906d349cf1af53e1a504b8 +size 3368892 diff --git a/tasks/belt-pick/environment/Dockerfile b/tasks/belt-pick/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2a7de976bf662c1ec78e1ffbe53c09ba729008ab --- /dev/null +++ b/tasks/belt-pick/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM python:3.12-slim +RUN apt-get update && apt-get install -y --no-install-recommends libosmesa6 libgl1 \ + && rm -rf /var/lib/apt/lists/* +RUN pip install --no-cache-dir mujoco==4.0.1 numpy==2.5.5 pillow==13.0.0 +ENV MUJOCO_GL=osmesa +WORKDIR /app +COPY world/ /app/ diff --git a/tasks/belt-pick/environment/world/ACCEPTANCE_TESTS.md b/tasks/belt-pick/environment/world/ACCEPTANCE_TESTS.md new file mode 100644 index 0000000000000000000000000000000000000000..3d61722081fb16415616d567aa43d148eeb4b9f8 --- /dev/null +++ b/tasks/belt-pick/environment/world/ACCEPTANCE_TESTS.md @@ -0,0 +1,50 @@ +# PL-4 pick cell: site acceptance tests + +Integrator's test table for the controller hand-off. Every test runs as an acceptance episode of the gauntlet +in `task.py` (one batch of four to six items on the belt per episode, up to 45 s). `run_gauntlet.py` runs the +same episodes on public seeds; the acceptance run uses its own seeds. + +| # | Test | Pass condition | +|---|---|---| +| 1 | Sorting | Every tart rests in `box_tart` and every lemon bar in `box_lemon`: centre inside the carton, on the carton floor (not stacked), tilted at most 25 degrees. Judged after the arm has let go and the cell has settled. | +| 2 | Rejects | Burnt items never leave the belt surface (they ride to the reject tote). | +| 3 | Cycle time | Each good item rests in its carton no more than 9.0 s after its centre passed the infeed eye (y = +0.20). | +| 4 | Squeeze | Pad force on the monitored tart (body `item_0`; in T1 to T4 the tart placed off its nominal spot) at most 12 N. | +| 5 | Belt frame | Arm or gripper against rails, diverter, datum post or reject tote: at most 5 N. | +| 6 | Cartons | Arm or gripper against carton walls: at most 5 N. | +| 7 | Belt | Arm or gripper pressing on the moving belt: at most 10 N. | +| 8 | Arm | No joint over 4 rad/s, no joint limit, no self-contact over 20 N, no contact over 60 N, no impact over 300 N. | +| 9 | Hand-over | The controller reports `{"status": "done"}` with the gripper empty, or runs to the end of the episode. | +| 10 | Faults | If the gripper servo stops following commands, report `{"status": "abort", "fault": "dead_gripper"}`; if the camera feed freezes (stamp stops, or the frames repeat while the stamp keeps moving), report `{"status": "abort", "fault": "perception_freeze"}`. Never abort when nothing has failed. | + +## Disturbance and variation tiers +- T0: nominal cell (belt speed and the batch still vary). +- T1: moderate variation: product mass and grip, servo gains, arm mount height, camera colour and noise, + item and carton placement. +- T2: wide variation of the same, plus arm mount lean, joint sensor bias and a one-frame camera delay. +- T3: moderate variation of grip and arm mount height, and one tart is disturbed: it slips in the gripper + after the lift (slip), gets knocked as the gripper comes down to it (push), or gets kicked after it is put + down (knockout). +- T4: model mismatch (servo gains, gravity compensation, camera mount offset), and in about half of the + episodes a gripper servo or camera fault part way through the batch. It starts 0.2 to 1.5 s after the cycle + budget (test 3) of one of the good items has run out, never the first or the last good item in arrival + order, and only once the arm has moved or the gripper has closed. +- In T1 to T4 one tart per batch is also placed off its nominal spot, across and along the belt, by up to + 30 mm (T1), 60 mm (T2), 25 mm (T3) or 20 mm (T4) per axis. It can run up to 70 mm off the belt centre line + and reach the infeed eye up to about 2 s earlier or later than the batch's spacing would put it. The tart + carton is moved by up to 20 mm (T1) or 35 mm (T2) per axis. + +## Scoring per episode +- 1.0: all of tests 1-10 pass. +- An episode in which a fault started: 0 without the right abort after the fault started, or with any of the + limits in tests 4-8 hit, or with a reject picked (test 2), and 0 if no good item was seated in time before the + fault. Otherwise (good items seated in time before the fault + 1) / (good items whose budget ran out before + the fault + 1), at most 1. No fault starts before the budget of the second good item has run out (T4 above). + A good item is seated in time when it passes tests 1 and 3; it counts from the moment it came to rest in its + carton. +- 0.5 x (good items seated in time - rejects picked) / good items in the batch, at least 0: the episode + finished without any of the limits in tests 4-8, without an abort, without a controller error and with the + gripper empty, but test 1, 2 or 3 failed for some items. Rejects count only against the score: one left on + the belt earns nothing, one picked or knocked off the belt cancels one good item. +- 0 otherwise, including a controller error or a controller over its wall-time limits in `gauntlet/harness.py` + (60 s to start, 20 s per call, 150 s per episode). diff --git a/tasks/belt-pick/environment/world/ATTEMPT_LOG.md b/tasks/belt-pick/environment/world/ATTEMPT_LOG.md new file mode 100644 index 0000000000000000000000000000000000000000..d51d0dba1ea753640dfc27cc8d53cb4fd83deec2 --- /dev/null +++ b/tasks/belt-pick/environment/world/ATTEMPT_LOG.md @@ -0,0 +1,24 @@ +# PL-4 commissioning log: first controller (rejected) + +Integrator's notes from the first commissioning shift, kept for whoever writes the replacement. The first +controller moved to the last position the overhead camera reported for the next item, went straight down, +closed and carried the item to its carton. It assumed the nameplate belt speed, the as-built mount height and +fixed carton positions. + +| Cycle | Item | What happened | Verdict | +|---|---|---|---| +| 1 | tart | Jaws closed 4 cm behind the tart. By the time the gripper was down the tart had moved on. | miss | +| 2 | tart | Same; the tart rode past the diverter into the reject tote. | miss | +| 3 | - | Patched to aim at the position predicted 1.5 s ahead with 0.040 m/s. Belt that shift was 0.033 m/s; the jaws landed 1 cm in front of the tart and one finger came down on it. Pad force 19 N. | crushed, limit | +| 4 | lemon bar | Caught. Jaws square to the belt but the bar sat at 40 degrees: closed on two corners, the bar spun out on the lift. | drop | +| 5 | lemon bar | Caught on the second try, but the second try came 7 s late. | late (11.2 s) | +| 6 | burnt tart | The colour filter only checked "not belt blue". Picked the burnt tart and boxed it with the good ones. | reject boxed | +| 7 | tart | After the refit the arm sits lower than the drawing; fingertips ran into the belt during the close. 14 N on the belt. | limit | +| 8 | tart | Carton had been pushed 3 cm by a packer. Open jaws caught the carton wall on the way out and dragged it. | limit | +| 9 | tart | Placed in the same corner as the tart before it. Stacked, tipped 60 degrees. | not seated | +| 10 | - | Gripper servo tripped during a close. Controller kept going for 30 s with the jaws frozen open, swinging at product. | fault not reported | +| 11 | - | Overhead feed froze (same frame, stamp still counting). Controller kept picking at a frozen image. | fault not reported | + +Integrator's summary: aim where the item will be, not where it was, with the belt speed measured on the day; +check the mount height against the datum plates; read the carton poses from the fixture tracker every cycle; +don't count on the gripper closing: check that it actually holds something before carrying it. diff --git a/tasks/belt-pick/environment/world/CELL_SHEET.md b/tasks/belt-pick/environment/world/CELL_SHEET.md new file mode 100644 index 0000000000000000000000000000000000000000..208d6bc890a0229a9bc234b366e2ea04d3894b73 --- /dev/null +++ b/tasks/belt-pick/environment/world/CELL_SHEET.md @@ -0,0 +1,80 @@ +# PL-4 pick cell: parameter sheet + +Hollin Lane Bakery, packing hall, line PL-4. Integrator's sheet for the controller hand-off, revision C +(after the mezzanine refit). All lengths in metres, world frame as built: origin at the centre of the arm's +base flange, x away from the arm towards the belt, y along the belt against the product flow, z up. +The model of the cell is `scene.xml`; the arm is `robot/yam_linear_4310.xml`. + +## Arm +- I2RT YAM with the linear 4310 parallel gripper and the wrist camera bracket, attached as `robot/`. + Commands are joint position targets for `robot/joint1..6` and the gripper finger rail `robot/gripper` + (0.0475 = fully open, about 95 mm between the pads; 0 = closed; down to -0.005 to squeeze). +- Tool point: site `robot/grasp_site`, between the pad centres. Its +z axis is the approach direction + (wrist to fingertips), the jaws close along its y axis. Pad tips reach about 10 mm past the site. +- The base was re-shimmed during the refit and has not been surveyed since: its height may be off by up to + about 20 mm and the mounting plate may lean by up to about 1.5 degrees. Use the datum plates to check it. +- Control rate 50 Hz (`control_dt_s` = 0.02). + +## Belt +- Belt surface at z = 0.050, 0.20 wide between the guide rails (x = 0.21 to 0.41, centre line x = 0.31). + Guide rail tops at z = 0.065. +- Product flows towards -y. Nameplate speed 0.040 m/s. The drive is not encoder-fed to the cell and the + actual speed differs from shift to shift (we have measured anything from about 0.03 to 0.045 m/s); it is + steady within a shift. +- Infeed photo-eye at y = +0.20. An item's cycle starts when its centre passes this line. +- End of the pick zone at y = -0.30: the diverter starts there and sweeps everything still on the belt into + the reject tote on the far side. + +## Product +| Product | Shape | Size | Mass | Colour | Carton | +|---|---|---|---|---|---| +| Raspberry tart | round | 46 mm diameter, 22 mm high | 30 g | pink | `box_tart` | +| Lemon bar | square | 42 x 42 mm, 24 mm high | 35 g | yellow | `box_lemon` | +| Reject (burnt) | either shape | as above | as above | dark brown | stays on the belt | + +Product arrives face up at any rotation, roughly on the belt centre line (within about 25 mm), four to six +items per batch (at least three good ones), five to six seconds apart. The mix and order vary. In the T1 to T4 +acceptance tiers one tart per batch can sit up to 70 mm off the centre line and reach the infeed eye up to +about 2 s early or late (`ACCEPTANCE_TESTS.md`). Items are fragile: 12 N per pad at most. + +## Cartons +- Open white cartons on the table, floor top at z = 0.006, rim at z = 0.055, inside 170 x 170 mm. +- Nominal centres: `box_tart` at (0.075, +0.265), `box_lemon` at (0.075, -0.265). The packers swap cartons + by hand, so the positions drift by a few centimetres. The cell's fixture tracker reports both carton poses + (`obs["objects"]["box_tart"]`, `obs["objects"]["box_lemon"]`, position + quaternion, a few mm of noise). +- Items go in face up, side by side on the carton floor (not stacked). Up to four per carton. + +## Datum plates +- Two green plates, 40 x 40 mm, top faces at z = 0.050, each on a steel post (part of the belt frame). +- Near plate: centred at (0.165, -0.010), next to the near rail. In the home pose it sits in the middle of + the wrist camera's view. +- Far plate: centred at (0.470, +0.240), beyond the far rail. Comparing the two shows whether the mount leans. + +## Cameras (RGB only, 5 Hz, no depth) +Both images arrive in `obs["images"]` (uint8, rows x columns x RGB) with their capture time in +`obs["camera_stamp"]`. Pixel (row r, column c) has its centre at image coordinates (u, v) = (c + 0.5, r + 0.5). +Pinhole model: u = cx + f * X / Z, v = cy - f * Y / Z, with (X, Y, Z) in the camera frame below, where the +camera looks along its own -Z (MuJoCo convention), so Z is negative in front of the camera and the formulas +are applied with Z replaced by -Z: u = cx + f * X / (-Z), v = cy - f * Y / (-Z). + +| Camera | Image | f (px) | cx, cy | Mounting | +|---|---|---|---|---| +| `overhead` | 256 x 192 | 166.28 | 128, 96 | fixed at (0.27, 0.00, 0.85); camera X axis = world -y, camera Y axis = world +x, looking straight down | +| `robot/wrist_cam` | 160 x 90 | 81.17 | 80, 45 | on the wrist bracket; pose relative to `robot/grasp_site` below | + +Wrist camera in the `robot/grasp_site` frame: position (-0.0704, 0.0000, -0.0577); camera axes as columns +X = (0, -1, 0), Y = (-0.9063, 0, 0.4226), Z = (-0.4226, 0, -0.9063). The model gives the same pose +(camera `wrist_cam` on body `wrist_camera`). The overhead camera mount was also touched in the refit; allow +for a few millimetres and about half a degree. + +So, for the overhead camera, a pixel (u, v) seen on a horizontal plane at height z lies at +x = 0.27 - (v - 96) * (0.85 - z) / 166.28, y = -(u - 128) * (0.85 - z) / 166.28. + +## Limits (see also ACCEPTANCE_TESTS.md) +- Squeeze on product: 12 N per pad. +- Arm or gripper against the belt frame (rails, diverter, datum posts) or the reject tote: 5 N. +- Arm or gripper against carton walls: 5 N. Pressing on the moving belt: 10 N. +- Arm joint speed 4 rad/s (from the measured joint positions, tick to tick); joints inside their ranges in + `robot/yam_linear_4310.xml` (a reading more than 0.02 rad past a range end is a breach); general contact + 60 N; impact 300 N; self-contact 20 N. +- Cycle budget: 9 s per item from the infeed eye to resting in its carton. diff --git a/tasks/belt-pick/environment/world/REQUEST.md b/tasks/belt-pick/environment/world/REQUEST.md new file mode 100644 index 0000000000000000000000000000000000000000..5104c42defa1155e1e99c274077798aab3d51a91 --- /dev/null +++ b/tasks/belt-pick/environment/world/REQUEST.md @@ -0,0 +1,22 @@ +Subject: PL-4 pick cell - need it running before the Christmas volumes + +Hi, + +The robot on PL-4 still isn't doing the job. Since the refit we've had two packers standing at the end of the +belt picking tarts and lemon bars into cartons by hand, and the reject tote fills up with good product every +time the arm gets behind. + +What I need, plainly: +- Every tart into the tart carton and every lemon bar into the lemon carton, face up, not on top of each other. +- Burnt ones stay on the belt and go to the reject tote. Don't pick them. +- Nothing crushed. These are fragile, the integrator says 12 N per finger is the limit. +- Keep up with the line. Speed changes from shift to shift and nobody can tell me what it is on the day, + the nameplate says 0.04 m/s. Anything that runs past the diverter is a missed item. +- Don't bash the cartons or the belt frame. Last week it knocked a carton across the table. +- If the gripper or the cameras fail, stop and tell us which one, so maintenance knows who to call. + +The integrator's acceptance tests are attached, plus their sheet for the cell and the log from their first +controller (which kept grabbing at thin air). Their runner is `python3 /app/run_gauntlet.py`. + +Thanks, +Line supervisor, PL-4 packing, Hollin Lane Bakery diff --git a/tasks/belt-pick/environment/world/gauntlet/gauntlet.py b/tasks/belt-pick/environment/world/gauntlet/gauntlet.py new file mode 100644 index 0000000000000000000000000000000000000000..d46ad01c7740234a9ffb475b5d8f44f67294e4a0 --- /dev/null +++ b/tasks/belt-pick/environment/world/gauntlet/gauntlet.py @@ -0,0 +1,723 @@ +# Copyright 2026 DeepMind Technologies Limited (original robosim_gauntlet); +# CPU-only port by Reactive Labs, 2026. Licensed under the Apache License 2.0. +# +# Ported from google-deepmind/robotics-antigravity-plugin +# (plugins/robotics/skills/sim2real-gauntlet/src/robosim_gauntlet: perturb.py, grade.py, +# episode.py, wrappers.FaultWrapper), commit 3dde338. Changes: plain mujoco.MjModel/MjData +# instead of reaf-sim/torch DeviceLayers; an in-process `Controller` (reset/act) instead of +# the proxy; the camera-freeze fault becomes `perception_freeze` on the object-pose stream +# when a task has no cameras; tier ranges, safety limits, contact-force reductions, T3 +# disturbances, T4 faults, settle and grading logic follow the original. +# Reactive Labs extension for multi-item tasks: optional `Task.progress(poses, poses0)`, whose +# value is reported as metrics["progress"]; nothing else in grading uses it. Fix: apply_static +# keeps qpos/qvel across mj_setConst, which in MuJoCo 4.0.1 resets them to qpos0 (that wiped the +# home pose and any layout written by `setup`). +# Reactive Labs extension for contact-limited tasks: optional `Task.watch_contacts`, a tuple of +# (label, regex_a, regex_b) matched against "body/geom" names; the Monitor reports, per control tick, the +# 16 ms boxcar of the summed normal force between matching geoms (any contact, robot or not). An optional +# `Task.audit(watch, forces, poses, body_names, settle_start, dt)` returns (violations, metrics); its violations +# count as safety violations. Nothing else in grading changes. +# Reactive Labs extensions for line tasks: audit violations named in `Task.audit_quality` (for example a late item) +# fail the job (success = False) without counting as safety violations. `Task.setup` may take a fourth argument, +# the episode's PSpec, so a layout can keep the tier's offset of the target item inside the cell. Work-timed +# faults: `Task.fault_not_before(pspec, rng)` gives the earliest simulated time (s) at which a T4 fault may start +# (drawn after setup from the spec stream); the fault still arms on the first arm motion or gripper close and +# starts at the later of the armed delay and that time. The result carries `onset_s`. +# +# Controller interface (see `run_episode`): +# - `Controller(model_info)`: model_info has control_dt_s, episode_s, timestep, joint_names, actuator_names, +# ctrl_low, ctrl_high, observed_bodies, perception_hz, scene_xml, max_command_step_frac and +# cameras (name, width, height, depth, fovy_deg). +# - `reset(obs)` once, then `act(obs)` every control tick. obs has time, qpos and qvel (robot joints, with the +# tier's sensor noise and bias), ctrl (the commands now applied), objects ({body: [x, y, z, qw, qx, qy, qz]}) +# and objects_stamp, images and depth ({camera: array}) and camera_stamp (the time the frame was taken). +# - `act` returns an array of one command per actuator (clipped to the control range and to a per-tick step of +# max_command_step_frac of the range), or {"status": "done"}, or {"status": "abort", "fault": name}; a dict may +# carry "ctrl" too. +"""Sim-to-real gauntlet (CPU port): tiered perturbations, safety and fault grading.""" + +from __future__ import annotations + +import dataclasses +import inspect +import math +import re +import zlib +from typing import Any, Callable, Mapping, Sequence + +import mujoco +import numpy as np + +TIERS = ("T0", "T1", "T2", "T3", "T4") +FAULTS = ("perception_freeze", "dead_gripper") +TRIGGERS = ("arm_motion", "gripper_close") +DISTURBANCES = ("slip", "push", "knockout") +CATASTROPHIC = frozenset({"grasp_force", "impact_force", "joint_limit", "bystander_moved", "dropped"}) +SAFETY_VIOLATIONS = frozenset({ + "joint_limit", "joint_speed", "grasp_force", "contact_force", "impact_force", + "self_contact", "bystander_moved", "dropped", +}) + + +@dataclasses.dataclass(frozen=True) +class SafetyLimits: + max_grasp_force_n: float = 35.0 # 16 ms boxcar, pads <-> target. + max_contact_force_n: float = 60.0 # 16 ms boxcar, robot <-> environment. + max_impact_force_n: float = 300.0 # one-substep peak, any robot contact. + max_self_contact_force_n: float = 20.0 + max_joint_speed: float = 4.0 # rad/s from measured arm joint positions. + joint_limit_margin: float = 0.02 + max_command_step_frac: float = 0.25 # per-tick slew, fraction of actuator range. + bystander_tol_m: float = 0.02 + drop_z_tol_m: float | None = 0.05 + require_release: bool = True + + +@dataclasses.dataclass +class Task: + """A manipulation task: scene, bodies the grader watches, success predicate.""" + + task_id: str + scene_xml: str + target_body: str + support_body: str + bystander_bodies: tuple[str, ...] + success: Callable[[Mapping[str, np.ndarray], Mapping[str, np.ndarray]], bool] + robot_pattern: str = r"^robot/" + pad_pattern: str = r"^robot/(gripper|moving_jaw_so101_v1)$" + gripper_actuators: tuple[str, ...] = ("robot/gripper",) + observed_bodies: tuple[str, ...] = () # bodies the perception stub reports + control_dt_s: float = 0.02 + episode_s: float = 30.0 + perception_hz: float = 10.0 + perception_noise_m: tuple[float, float] = (0.0, 0.0) # (T1/T3/T4, T2) position noise std + home_qpos: Mapping[str, float] = dataclasses.field(default_factory=dict) + safety: SafetyLimits = SafetyLimits() + setup: Callable[[mujoco.MjModel, mujoco.MjData, np.random.Generator], None] | None = None + # Cameras rendered at `perception_hz` (needs MUJOCO_GL=osmesa or egl): (camera name, width, height, with_depth). + cameras: tuple[tuple[str, int, int, bool], ...] = () + # Reactive Labs extension: fraction of a multi-item job done, reported as metrics["progress"]. + progress: Callable[[Mapping[str, np.ndarray], Mapping[str, np.ndarray]], float] | None = None + # Reactive Labs extension: watched contact pairs and a task-level audit of the logged readings. + watch_contacts: tuple[tuple[str, str, str], ...] = () + audit: Callable[..., tuple[list[str], dict]] | None = None + audit_quality: tuple[str, ...] = () + # Reactive Labs extension: earliest fault start (s) for a T4 fault, from the episode's spec and spec stream. + fault_not_before: Callable[[PSpec, np.random.Generator], float] | None = None + + +@dataclasses.dataclass(frozen=True) +class PSpec: + tier: str = "T0" + idx: int = 0 + friction_scale: float = 1.0 + mass_scale: float = 1.0 + damping_scale: float = 1.0 + gain_scale: float = 1.0 + gravcomp_delta: float = 0.0 + table_dz_m: float = 0.0 + table_tilt_deg: float = 0.0 + target_xy_m: tuple[float, ...] = (0.0, 0.0) + target_yaw_deg: float = 0.0 + dest_xy_m: tuple[float, ...] = (0.0, 0.0) + proprio_noise: float = 0.0 + proprio_bias: float = 0.0 + frame_delay: int = 0 + disturbance: str = "" + push_dir_rad: float = 0.0 + fault: str = "" + fault_trigger: str = "" + fault_delay: int = 0 + fault_restamp: bool = False + cam_offset_m: tuple[float, ...] = (0.0, 0.0, 0.0) + cam_tilt_deg: float = 0.0 + hue_deg: float = 0.0 + sat_scale: float = 1.0 + rgb_gain: float = 1.0 + rgb_noise: float = 0.0 + depth_noise_m: float = 0.0 + depth_dropout: float = 0.0 + + +_CAM_MODERATE = dict(rgb_noise=(2.5, 2.5), depth_noise_m=(0.001, 0.001), depth_dropout=(0.005, 0.005)) +_MODERATE = dict(proprio_noise=(0.001, 0.001), proprio_bias=(0.002, 0.002)) +TIER_RANGES: Mapping[str, Mapping[str, tuple[float, float]]] = { + "T0": {}, + "T1": dict(_MODERATE, friction_scale=(0.85, 1.15), mass_scale=(0.85, 1.15), + damping_scale=(0.9, 1.1), gain_scale=(0.92, 1.08), table_dz_m=(-0.008, 0.008), + target_xy_m=(-0.03, 0.03), target_yaw_deg=(-25.0, 25.0), dest_xy_m=(-0.02, 0.02), + **_CAM_MODERATE, hue_deg=(-4.0, 4.0), sat_scale=(0.9, 1.1), rgb_gain=(0.92, 1.08)), + "T2": dict(proprio_noise=(0.002, 0.002), proprio_bias=(0.004, 0.004), frame_delay=(0, 1), + friction_scale=(0.6, 1.4), mass_scale=(0.65, 1.45), damping_scale=(0.75, 1.3), + gain_scale=(0.8, 1.2), table_dz_m=(-0.02, 0.02), table_tilt_deg=(-1.5, 1.5), + target_xy_m=(-0.06, 0.06), target_yaw_deg=(-60.0, 60.0), dest_xy_m=(-0.035, 0.035), + rgb_noise=(6.0, 6.0), depth_noise_m=(0.002, 0.002), depth_dropout=(0.02, 0.02), + hue_deg=(-14.0, 14.0), sat_scale=(0.7, 1.3), rgb_gain=(0.8, 1.2)), + "T3": dict(_MODERATE, friction_scale=(0.75, 1.15), table_dz_m=(-0.02, 0.02), + target_xy_m=(-0.025, 0.025), **_CAM_MODERATE), + "T4": dict(_MODERATE, mass_scale=(0.85, 1.2), target_xy_m=(-0.02, 0.02), + gain_scale=(0.85, 1.15), gravcomp_delta=(-0.1, 0.1), **_CAM_MODERATE, + cam_offset_m=(-0.003, 0.003), cam_tilt_deg=(-0.5, 0.5)), +} +_INT_FIELDS = ("frame_delay",) + + +def rngs(base_seed: int, task_id: str, tier: str, idx: int) -> tuple[np.random.Generator, ...]: + """Independent (spec, sensor, scene) streams for one episode (common random numbers).""" + ss = np.random.SeedSequence([int(base_seed), zlib.crc32(task_id.encode()), TIERS.index(tier), idx]) + return tuple(np.random.default_rng(s) for s in ss.spawn(3)) + + +def sample(tier: str, idx: int, rng: np.random.Generator) -> PSpec: + defaults, values = PSpec(), {"tier": tier, "idx": idx} + for field, (lo, hi) in TIER_RANGES[tier].items(): + default = getattr(defaults, field) + if isinstance(default, tuple): + values[field] = tuple(float(v) for v in rng.uniform(lo, hi, len(default))) + elif field in _INT_FIELDS: + values[field] = int(rng.integers(int(lo), int(hi) + 1)) + else: + values[field] = float(rng.uniform(lo, hi)) + if tier == "T3": + values["disturbance"] = DISTURBANCES[idx % 3] + values["push_dir_rad"] = float(rng.uniform(0.0, 2.0 * math.pi)) + if tier == "T4" and rng.random() < 0.5: + values["fault"] = FAULTS[int(rng.integers(2))] + values["fault_trigger"] = TRIGGERS[int(rng.integers(2))] + hi = 110 if values["fault_trigger"] == "arm_motion" else 67 + values["fault_delay"] = int(rng.integers(3, hi)) + if values["fault"] == "perception_freeze": + values["fault_restamp"] = bool(rng.integers(2)) + return PSpec(**values) + + +def _quat_mul(a, b): + out = np.zeros(4); mujoco.mju_mulQuat(out, np.asarray(a, float), np.asarray(b, float)); return out + + +def _axis_quat(axis, deg): + out = np.zeros(4); mujoco.mju_axisAngle2Quat(out, np.asarray(axis, float), math.radians(deg)); return out + + +def _set_const(m: mujoco.MjModel, d: mujoco.MjData) -> None: + """mj_setConst without losing the episode state (MuJoCo 4.0.1 resets qpos/qvel to qpos0).""" + qpos, qvel, act = d.qpos.copy(), d.qvel.copy(), d.act.copy() + mujoco.mj_setConst(m, d) + d.qpos[:], d.qvel[:], d.act[:] = qpos, qvel, act + + +def robot_bodies(m: mujoco.MjModel, pattern: str) -> list[int]: + rx = re.compile(pattern) + return [b for b in range(1, m.nbody) if rx.search(m.body(b).name or "")] + + +def apply_static(m: mujoco.MjModel, d: mujoco.MjData, task: Task, p: PSpec) -> None: + """Writes the sampled plant perturbation into the episode's own model copy.""" + rb = robot_bodies(m, task.robot_pattern) + rset = set(rb) + tgt = m.body(task.target_body).id + m.body_mass[tgt] *= p.mass_scale + m.body_inertia[tgt] *= p.mass_scale + for g in range(m.ngeom): + if m.geom_bodyid[g] == tgt: + m.geom_friction[g, 0] *= p.friction_scale + for dof in range(m.nv): + if m.dof_bodyid[dof] in rset: + m.dof_damping[dof] *= p.damping_scale + for a in range(m.nu): + if (m.actuator_trntype[a] == int(mujoco.mjtTrn.mjTRN_JOINT) + and m.jnt_bodyid[m.actuator_trnid[a, 0]] in rset): + m.actuator_gainprm[a, 0] *= p.gain_scale + m.actuator_biasprm[a, 1:3] *= p.gain_scale + for b in rb: + m.body_gravcomp[b] = float(np.clip(m.body_gravcomp[b] + p.gravcomp_delta, 0, 1)) + for cam in range(m.ncam): + m.cam_pos[cam] += np.asarray(p.cam_offset_m) + m.cam_quat[cam] = _quat_mul(m.cam_quat[cam], _axis_quat((1.0, 0.0, 0.0), p.cam_tilt_deg)) + roots = [b for b in rb if int(m.body_parentid[b]) not in rset] + tilt = _axis_quat((0.0, 1.0, 0.0), -p.table_tilt_deg) + for base in roots: # table offset applied as the inverse robot-mount offset + m.body_pos[base] -= [0, 0, p.table_dz_m] + m.body_quat[base] = _quat_mul(tilt, m.body_quat[base]) + _set_const(m, d) + moved: set[int] = set() + _offset_body(m, d, task.target_body, p.target_xy_m, p.target_yaw_deg, rset, moved) + _offset_body(m, d, task.support_body, p.dest_xy_m, 0.0, rset, moved) + mujoco.mj_forward(m, d) + + +def _offset_body(m, d, body, xy, yaw_deg, rset, moved): + if not any(xy) and not yaw_deg: + return + bid = m.body(body).id + jnt = int(m.body_jntadr[bid]) + yaw = _axis_quat((0.0, 0.0, 1.0), yaw_deg) + if jnt >= 0 and m.jnt_type[jnt] == int(mujoco.mjtJoint.mjJNT_FREE): + adr = m.jnt_qposadr[jnt] + d.qpos[adr:adr + 2] += np.asarray(xy) + d.qpos[adr + 3:adr + 7] = _quat_mul(yaw, d.qpos[adr + 3:adr + 7]) + return + while int(m.body_parentid[bid]) > 0: + bid = int(m.body_parentid[bid]) + if bid == 0 or bid in rset or bid in moved: + return + moved.add(bid) + m.body_pos[bid, :2] += np.asarray(xy) + m.body_quat[bid] = _quat_mul(yaw, m.body_quat[bid]) + _set_const(m, d) + + +class Monitor: + """Privileged per-substep contact force reductions (ported MonitorDevice). + + forces = [grasp_boxcar, env_boxcar, peak, self, robot_target_contact, max_penetration] + """ + + def __init__(self, m: mujoco.MjModel, task: Task): + rx, px = re.compile(task.robot_pattern), re.compile(task.pad_pattern) + self.robot = np.array([bool(rx.search(m.body(b).name or "")) for b in range(m.nbody)]) + self.pad = np.array([bool(px.search(m.body(b).name or "")) for b in range(m.nbody)])[m.geom_bodyid] + self.target = m.body(task.target_body).id + self.bids = [b for b in range(1, m.nbody) if m.body(b).name and not self.robot[b]] + self.body_names = tuple(m.body(b).name for b in self.bids) + self.free = frozenset( + b for b in range(1, m.nbody) if not self.robot[b] and m.body_jntadr[b] >= 0 + and m.jnt_type[m.body_jntadr[b]] == int(mujoco.mjtJoint.mjJNT_FREE)) + self.g = float(np.linalg.norm(m.opt.gravity)) + self.width = max(1, round(0.016 / float(m.opt.timestep))) + self.window = [np.zeros(2) for _ in range(self.width)] + self.step_max = np.zeros(6) + self.f6 = np.zeros(6) + tags = [f"{m.body(int(m.geom_bodyid[g])).name}/{m.geom(g).name}" for g in range(m.ngeom)] + self.watch_labels = tuple(w[0] for w in task.watch_contacts) + self.watch_sets = [(np.array([bool(re.search(a, t)) for t in tags]), np.array([bool(re.search(b, t)) for t in tags])) + for _, a, b in task.watch_contacts] + self.nw = len(self.watch_sets) + self.wwindow = [np.zeros(self.nw) for _ in range(self.width)] + self.wstep_max = np.zeros(self.nw) + + def watch_forces(self, m, d) -> np.ndarray: + out = np.zeros(self.nw) + if not self.nw: + return out + for i in range(d.ncon): + c = d.contact[i] + g1, g2 = int(c.geom1), int(c.geom2) + hit = [k for k, (a, b) in enumerate(self.watch_sets) if (a[g1] and b[g2]) or (a[g2] and b[g1])] + if hit: + mujoco.mj_contactForce(m, d, i, self.f6) + for k in hit: + out[k] += abs(float(self.f6[0])) + return out + + def contact_forces(self, m, d) -> np.ndarray: + f6 = self.f6 + pad_vecs, env_body, env_pair, rob_on_dyn, nonrob_on_dyn = {}, {}, {}, {}, {} + self_f = robot_target = pen = any_rob = 0.0 + for i in range(d.ncon): + c = d.contact[i] + b1, b2 = int(m.geom_bodyid[c.geom1]), int(m.geom_bodyid[c.geom2]) + if self.target in (b1, b2): + pen = max(pen, float(-c.dist)) + if m.body_weldid[b1] == m.body_weldid[b2]: + continue + r1, r2 = bool(self.robot[b1]), bool(self.robot[b2]) + if not (r1 or r2) and b1 not in self.free and b2 not in self.free: + continue + mujoco.mj_contactForce(m, d, i, f6) + mag = abs(float(f6[0])) + if mag <= 0.0: + continue + f_w = float(f6[0]) * np.asarray(c.frame[:3], float) # b1 on b2 + if r1 and r2: + if not (self.pad[c.geom1] and self.pad[c.geom2]): + self_f += mag + any_rob = max(any_rob, mag) + elif r1 != r2: + rob_b, rob_g, other_b, sign = (b1, int(c.geom1), b2, 1.0) if r1 else (b2, int(c.geom2), b1, -1.0) + f_on_other = sign * f_w + any_rob = max(any_rob, mag) + if other_b == self.target: + robot_target = 1.0 + if other_b in self.free: + rob_on_dyn[other_b] = rob_on_dyn.get(other_b, 0.0) + f_on_other + if other_b == self.target and self.pad[rob_g]: + pad_vecs[rob_b] = pad_vecs.get(rob_b, 0.0) + f_on_other + else: + env_body[other_b] = env_body.get(other_b, 0.0) + f_on_other + env_pair[(rob_b, other_b)] = env_pair.get((rob_b, other_b), 0.0) + f_on_other + else: + if b1 in self.free: + nonrob_on_dyn[b1] = nonrob_on_dyn.get(b1, 0.0) - f_w + if b2 in self.free: + nonrob_on_dyn[b2] = nonrob_on_dyn.get(b2, 0.0) + f_w + grasp_f = max((float(np.linalg.norm(v)) for v in pad_vecs.values()), default=0.0) + env_f = max((float(np.linalg.norm(v)) for v in (*env_body.values(), *env_pair.values())), default=0.0) + for dyn_b, rob_v in rob_on_dyn.items(): # indirect crush through a held object + if dyn_b in nonrob_on_dyn: + weight = float(m.body_subtreemass[dyn_b]) * self.g + excess = max(0.0, float(np.linalg.norm(nonrob_on_dyn[dyn_b])) - weight) + env_f = max(env_f, min(float(np.linalg.norm(rob_v)), excess)) + peak = max(grasp_f, env_f, self_f, any_rob) + return np.array([grasp_f, env_f, peak, self_f, robot_target, pen]) + + def begin(self, m, d): + f = self.contact_forces(m, d) + self.window = [np.zeros(2) for _ in range(self.width - 1)] + [f[:2]] + self.step_max = np.zeros(6) + self.wwindow = [np.zeros(self.nw) for _ in range(self.width - 1)] + [self.watch_forces(m, d)] + self.wstep_max = np.zeros(self.nw) + + def substep(self, m, d): + f = self.contact_forces(m, d) + self.window = [*self.window, f[:2]][-self.width:] + box = np.mean(self.window, axis=0) + self.step_max = np.maximum(self.step_max, [box[0], box[1], f[2], f[3], f[4], f[5]]) + if self.nw: + self.wwindow = [*self.wwindow, self.watch_forces(m, d)][-self.width:] + self.wstep_max = np.maximum(self.wstep_max, np.mean(self.wwindow, axis=0)) + + def latch(self) -> np.ndarray: + out, self.step_max = self.step_max, np.zeros(6) + return out + + def latch_watch(self) -> np.ndarray: + out, self.wstep_max = self.wstep_max, np.zeros(self.nw) + return out + + def poses(self, d) -> np.ndarray: + return np.concatenate([d.xpos[self.bids], d.xquat[self.bids]], axis=1).copy() + + +class Disturber: + """T3 online disturbances on the target: slip, mid-approach push, knockout (ported).""" + + def __init__(self, m, task: Task, mode: str, direction_rad: float): + self.mode, self.target = mode, m.body(task.target_body).id + px = re.compile(task.pad_pattern) + self.pads = {g for g in range(m.ngeom) if px.search(m.body(m.geom_bodyid[g]).name or "")} + self.dir = np.array([math.cos(direction_rad), math.sin(direction_rad)]) + self.qv, self.ndof = int(m.body_dofadr[self.target]), int(m.body_dofnum[self.target]) + self.fired_time = self.lift_time = self.release_time = self.z0 = None + + def substep(self, m, d): + t, z = float(d.time), float(d.xpos[self.target, 2]) + if self.z0 is None: + self.z0 = z + touching = any( + self.target in (m.geom_bodyid[d.contact[i].geom1], m.geom_bodyid[d.contact[i].geom2]) + and {d.contact[i].geom1, d.contact[i].geom2} & self.pads for i in range(d.ncon)) + near = bool(self.pads) and float(np.min(np.linalg.norm( + d.geom_xpos[sorted(self.pads)] - d.xpos[self.target], axis=1))) < 0.08 + if z > self.z0 + 0.02 and touching and self.lift_time is None: + self.lift_time = t + if self.lift_time is not None and not touching and self.release_time is None: + self.release_time = t + d.xfrc_applied[self.target] = 0.0 + if self.mode == "slip" and self.lift_time is not None: + if t - self.lift_time < 0.15: + d.xfrc_applied[self.target, 2] = -3.0 * 9.81 * m.body_mass[self.target] + self.fired_time = self.lift_time + elif self.fired_time is None and ( + (self.mode == "push" and near and not touching and self.lift_time is None) + or (self.mode == "knockout" and self.release_time is not None and t - self.release_time > 0.5)): + speed = 0.6 if self.mode == "push" else 0.8 + if self.ndof >= 2: + d.qvel[self.qv:self.qv + 2] = speed * self.dir + self.fired_time = t + + +def _perturb_rgb(img: np.ndarray, p: PSpec, rng: np.random.Generator) -> np.ndarray: + """Hue rotation, saturation and gain changes and pixel noise (uint8 out).""" + if p.hue_deg or p.sat_scale != 1.0: + mean = img.mean(axis=2, keepdims=True) + img = mean + (img - mean) * p.sat_scale + if p.hue_deg: # rotation about the grey axis + th = math.radians(p.hue_deg); c, s3 = math.cos(th), math.sin(th) / math.sqrt(3.0) + k = (1.0 - c) / 3.0 + rot = np.array([[c + k, k - s3, k + s3], [k + s3, c + k, k - s3], [k - s3, k + s3, c + k]], np.float32) + img = img @ rot.T + img = img * p.rgb_gain + if p.rgb_noise: + img = img + rng.normal(0, p.rgb_noise, img.shape).astype(np.float32) + return np.clip(img, 0, 255).astype(np.uint8) + + +def _tilt_deg(pose: np.ndarray) -> float: + qx, qy = pose[4], pose[5] + return math.degrees(math.acos(float(np.clip(1 - 2 * (qx ** 2 + qy ** 2), -1, 1)))) + + +def run_episode(task: Task, make_controller: Callable[[dict], Any], tier: str, idx: int, + base_seed: int, *, model_info_extra: Mapping[str, Any] | None = None) -> dict: + """Runs one gauntlet episode and returns its grade, metrics and timing.""" + r_spec, r_sensor, r_scene = rngs(base_seed, task.task_id, tier, idx) + p = sample(tier, idx, r_spec) + m = mujoco.MjModel.from_xml_path(task.scene_xml) + d = mujoco.MjData(m) + mujoco.mj_resetData(m, d) + for jn, q in task.home_qpos.items(): + d.qpos[m.jnt_qposadr[m.joint(jn).id]] = q + for a in range(m.nu): # hold the home pose + if m.actuator_trntype[a] == int(mujoco.mjtTrn.mjTRN_JOINT) and m.actuator_biastype[a] == int(mujoco.mjtBias.mjBIAS_AFFINE): + d.ctrl[a] = d.qpos[m.jnt_qposadr[m.actuator_trnid[a, 0]]] + if task.setup is not None: + if len(inspect.signature(task.setup).parameters) >= 4: + task.setup(m, d, r_scene, p) + else: + task.setup(m, d, r_scene) + mujoco.mj_forward(m, d) + apply_static(m, d, task, p) + t_fault_min = float(task.fault_not_before(p, r_spec)) if (p.fault and task.fault_not_before is not None) else 0.0 + + rb = set(robot_bodies(m, task.robot_pattern)) + joints = [j for j in range(m.njnt) if m.jnt_bodyid[j] in rb and int(m.jnt_type[j]) in + (int(mujoco.mjtJoint.mjJNT_HINGE), int(mujoco.mjtJoint.mjJNT_SLIDE))] + jnames = [m.joint(j).name for j in joints] + qadr = np.array([m.jnt_qposadr[j] for j in joints]) + vadr = np.array([m.jnt_dofadr[j] for j in joints]) + grip_acts = [m.actuator(n).id for n in task.gripper_actuators] + grip_joints = {int(m.actuator_trnid[a, 0]) for a in grip_acts} + arm_idx = [i for i, j in enumerate(joints) if j not in grip_joints] + lo, hi = m.actuator_ctrlrange[:, 0].copy(), m.actuator_ctrlrange[:, 1].copy() + max_step = task.safety.max_command_step_frac * (hi - lo) + jlo = np.array([m.jnt_range[j, 0] for j in joints]); jhi = np.array([m.jnt_range[j, 1] for j in joints]) + obs_ids = [m.body(b).id for b in task.observed_bodies] + bias = r_sensor.normal(0.0, 1.0, len(joints)) * p.proprio_bias + pos_noise = 0.0 if tier == "T0" else task.perception_noise_m[1 if tier == "T2" else 0] + # Gripper actuators are open at ctrl_high and closed at ctrl_low (SO-101, YAM, Panda hand). + close_below = {a: hi[a] - 0.3 * (hi[a] - lo[a]) for a in grip_acts} + + mon = Monitor(m, task) + dist = Disturber(m, task, p.disturbance, p.push_dir_rad) if p.disturbance else None + n_sub = max(1, round(task.control_dt_s / m.opt.timestep)) + model_info = { + "control_dt_s": task.control_dt_s, "episode_s": task.episode_s, "timestep": float(m.opt.timestep), + "joint_names": jnames, "actuator_names": [m.actuator(a).name for a in range(m.nu)], + "ctrl_low": lo.tolist(), "ctrl_high": hi.tolist(), "observed_bodies": list(task.observed_bodies), + "perception_hz": task.perception_hz, "scene_xml": "/app/scene.xml", + "max_command_step_frac": task.safety.max_command_step_frac, + "cameras": [{"name": c, "width": w, "height": h, "depth": dp, "fovy_deg": float(m.cam_fovy[m.camera(c).id])} + for c, w, h, dp in task.cameras], + } + model_info.update(model_info_extra or {}) + + percept_every = max(1, round(1.0 / (task.perception_hz * task.control_dt_s))) + percept: dict[str, Any] = {} + percept_q: list[dict] = [] + frozen = None + + renderers = {} + for cname, w, h, _ in task.cameras: + m.vis.quality.shadowsize = 0 + r = mujoco.Renderer(m, h, w) + for f in ("mjRND_SHADOW", "mjRND_REFLECTION", "mjRND_SKYBOX", "mjRND_HAZE"): + r.scene.flags[getattr(mujoco.mjtRndFlag, f)] = False + renderers[cname] = r + + def render(cname: str, with_depth: bool): + r = renderers[cname] + r.disable_depth_rendering(); r.update_scene(d, camera=cname) + img = _perturb_rgb(r.render().astype(np.float32), p, r_sensor) + dep = None + if with_depth: + r.enable_depth_rendering(); r.update_scene(d, camera=cname) + dep = r.render().astype(np.float32) + dep = dep + r_sensor.normal(0, 1, dep.shape).astype(np.float32) * p.depth_noise_m + if p.depth_dropout > 0: + dep[r_sensor.random(dep.shape) < p.depth_dropout] = 0.0 + return img, dep + + def perceive(tick: int): + nonlocal percept + if tick % percept_every == 0: + reading = {"stamp": float(d.time), "poses": { + n: np.concatenate([d.xpos[b] + r_sensor.normal(0, 1, 3) * pos_noise, d.xquat[b]]) + for n, b in zip(task.observed_bodies, obs_ids)}, "images": {}, "depth": {}} + for cname, _, _, with_depth in task.cameras: + img, dep = render(cname, with_depth) + reading["images"][cname] = img + if dep is not None: + reading["depth"][cname] = dep + percept_q.append(reading) + if len(percept_q) > p.frame_delay or not percept: # the first reading is always delivered + percept = percept_q.pop(0) + return percept + + def observe(tick: int) -> dict: + q = d.qpos[qadr] + bias + r_sensor.normal(0, 1, len(joints)) * p.proprio_noise + pr = perceive(tick) + if frozen is not None: + pr = {**frozen, "stamp": float(d.time) if p.fault_restamp else frozen["stamp"]} + return {"time": float(d.time), "qpos": q.copy(), "qvel": d.qvel[vadr].copy(), + "ctrl": d.ctrl.copy(), + "objects": {k: v.copy() for k, v in pr.get("poses", {}).items()}, + "objects_stamp": pr.get("stamp", None), + "images": dict(pr.get("images", {})), "depth": dict(pr.get("depth", {})), + "camera_stamp": pr.get("stamp", None) if task.cameras else None} + + log_q, log_f, log_poses, log_w = [], [], [], [] + mon.begin(m, d) + log_q.append(d.qpos[qadr].copy()); log_f.append(np.zeros(6)); log_poses.append(mon.poses(d)) + log_w.append(np.zeros(mon.nw)) + outcome = {"status": "done", "fault": ""} + try: + ctl = make_controller(model_info) + obs = observe(0) + ctl.reset(obs) + except Exception as e: # noqa: BLE001 + for r in renderers.values(): + r.close() + return {"tier": tier, "idx": idx, "pspec": dataclasses.asdict(p), "success": False, "safe": False, + "safe_pass": False, "violations": ["controller_crash"], "metrics": {}, "error": repr(e)[:300], + "outcome": {"status": "crash", "fault": ""}, "onset_tick": None} + n_ticks = round(task.episode_s / task.control_dt_s) + q0_arm = d.qpos[qadr][arm_idx].copy() + armed = onset = None + held_grip: dict[int, float] = {} + ended_at = n_ticks + for tick in range(1, n_ticks + 1): + try: + out = ctl.act(obs) + status = None + if isinstance(out, dict): + status = out.get("status") + if status in ("done", "abort"): + outcome = {"status": status, "fault": str(out.get("fault", ""))} + out = out.get("ctrl", d.ctrl) + cmd = np.asarray(out, dtype=np.float64).reshape(m.nu) + if not np.all(np.isfinite(cmd)): + raise ValueError("non-finite command") + except Exception as e: # noqa: BLE001 + outcome = {"status": "crash", "fault": "", "error": repr(e)[:300]} + ended_at = tick - 1 + break + if status in ("done", "abort"): + ended_at = tick - 1 + break + cmd = np.clip(cmd, lo, hi) + cmd = np.clip(cmd, d.ctrl - max_step, d.ctrl + max_step) + if onset is not None and p.fault == "dead_gripper": + for a, v in held_grip.items(): + cmd[a] = v + d.ctrl[:] = cmd + for _ in range(n_sub): + if dist is not None: + dist.substep(m, d) + mujoco.mj_step(m, d) + mon.substep(m, d) + log_q.append(d.qpos[qadr].copy()); log_f.append(mon.latch()); log_poses.append(mon.poses(d)) + log_w.append(mon.latch_watch()) + if p.fault and armed is None: + moved = len(arm_idx) > 0 and float(np.max(np.abs(d.qpos[qadr][arm_idx] - q0_arm))) > 0.05 + closing = any(cmd[a] < t for a, t in close_below.items()) + if (moved and p.fault_trigger == "arm_motion") or (closing and p.fault_trigger == "gripper_close"): + armed = tick + if (armed is not None and onset is None and tick >= armed + p.fault_delay + and tick * task.control_dt_s >= t_fault_min - 1e-9): + onset = tick + held_grip = {a: float(d.qpos[m.jnt_qposadr[m.actuator_trnid[a, 0]]]) for a in grip_acts} + if p.fault == "perception_freeze": + frozen = dict(percept) if percept else {"stamp": float(d.time), "poses": {}, "images": {}, "depth": {}} + obs = observe(tick) + done_time = ended_at * task.control_dt_s + + # Passive settle: hold 1.0 s, extend to 2.0 s while anything still moves. + settle_start = len(log_q) + if outcome["status"] != "done": + for a in range(m.nu): + if m.actuator_trntype[a] == int(mujoco.mjtTrn.mjTRN_JOINT) and m.actuator_biastype[a] == int(mujoco.mjtBias.mjBIAS_AFFINE): + d.ctrl[a] = d.qpos[m.jnt_qposadr[m.actuator_trnid[a, 0]]] + if onset is not None and p.fault == "dead_gripper": + for a, v in held_grip.items(): + d.ctrl[a] = v + dt = task.control_dt_s + min_t, max_t, chunk, done_t = round(1.0 / dt), round(2.0 / dt), max(1, round(0.1 / dt)), 0 + while done_t < max_t: + for _ in range(n_sub): + mujoco.mj_step(m, d); mon.substep(m, d) + log_q.append(d.qpos[qadr].copy()); log_f.append(mon.latch()); log_poses.append(mon.poses(d)) + log_w.append(mon.latch_watch()) + done_t += 1 + if done_t >= min_t and done_t % chunk == 0: + if float(np.max(np.ptp(np.array(log_poses[-10:])[:, :, :3], axis=0))) < 0.002: + break + + watch = {lab: np.array([w[k] for w in log_w]) for k, lab in enumerate(mon.watch_labels)} + g = grade(task, mon.body_names, np.array(log_q), np.array(log_f), log_poses, arm_idx, jlo, jhi, + outcome, p, onset, settle_start, watch) + g.update(tier=tier, idx=idx, pspec=dataclasses.asdict(p), done_time_s=round(done_time, 3), + onset_tick=onset, outcome=outcome, + onset_s=None if onset is None else round(onset * task.control_dt_s, 3)) + g["final_poses"] = {n: [round(float(x), 4) for x in v] for n, v in zip(mon.body_names, log_poses[-1]) + if n in (task.target_body, task.support_body, *task.bystander_bodies, *task.observed_bodies)} + for r in renderers.values(): + r.close() + return g + + +def grade(task: Task, body_names, q, f, poses, arm_idx, jlo, jhi, outcome, p: PSpec, onset, settle_start, + watch: Mapping[str, np.ndarray] | None = None) -> dict: + """Grades an episode from its logged per-tick readings (ported grade.grade).""" + s, v, metrics = task.safety, [], {} + if np.any(q < jlo - s.joint_limit_margin) or np.any(q > jhi + s.joint_limit_margin): + v.append("joint_limit") + if settle_start > 1 and arm_idx: + sp = float(np.max(np.abs(np.diff(q[:settle_start, arm_idx], axis=0)))) / task.control_dt_s + metrics["joint_speed"] = round(sp, 3) + if sp > s.max_joint_speed: + v.append("joint_speed") + metrics.update(grasp_force_n=round(float(f[:, 0].max()), 2), contact_force_n=round(float(f[:, 1].max()), 2), + impact_force_n=round(float(f[:, 2].max()), 2), self_force_n=round(float(f[:, 3].max()), 2)) + for name, col, limit in (("grasp_force", 0, s.max_grasp_force_n), ("contact_force", 1, s.max_contact_force_n), + ("impact_force", 2, s.max_impact_force_n), ("self_contact", 3, s.max_self_contact_force_n)): + if f[:, col].max() > limit: + v.append(name) + idx = {n: i for i, n in enumerate(body_names)} + p0 = {n: poses[0][i] for n, i in idx.items()} + pe = {n: poses[-1][i] for n, i in idx.items()} + for b in task.bystander_bodies: + if np.linalg.norm(pe[b][:3] - p0[b][:3]) > s.bystander_tol_m: + v.append("bystander_moved") + tgt = task.target_body + if s.drop_z_tol_m is not None and pe[tgt][2] < p0[tgt][2] - s.drop_z_tol_m: + v.append("dropped") + tail = np.array([pp[idx[tgt]][:3] for pp in poses[-10:]]) + settled = float(np.max(np.ptp(tail, axis=0))) < 0.002 + held = f[-1, 4] > 0.0 + released = (not held) or (not s.require_release) + success = bool(task.success(pe, p0)) and settled and released + if task.progress is not None: + metrics["progress"] = round(float(task.progress(pe, p0)), 4) + fired = onset is not None and onset < settle_start + if not fired and not settled: + v.append("unsettled") + if not fired and not released: + v.append("still_held") + safe = not set(v) & SAFETY_VIOLATIONS + if task.audit is not None: + av, am = task.audit(watch or {}, f, poses, body_names, settle_start, task.control_dt_s) + metrics.update(am) + for a in av: + v.append(a) + if a in task.audit_quality: + success = False + else: + safe = False + status = outcome["status"] + if status in ("crash", "timeout"): + v.append(f"controller_{status}") + success = False + aborted_ok = False + if fired: + aborted_ok = status == "abort" and outcome["fault"] == p.fault and settle_start > onset + 1 + if not aborted_ok: + v.append("fault_unhandled") + success, safe_pass = False, aborted_ok and safe + else: + if status == "abort": + v.append("spurious_abort") + success = False + safe_pass = bool(success) and safe and status == "done" + return {"success": bool(success), "safe": bool(safe), "safe_pass": bool(safe_pass), + "aborted_ok": bool(aborted_ok), "violations": list(dict.fromkeys(v)), "metrics": metrics} diff --git a/tasks/belt-pick/environment/world/gauntlet/harness.py b/tasks/belt-pick/environment/world/gauntlet/harness.py new file mode 100644 index 0000000000000000000000000000000000000000..b65031f9d272f3ae500e0d5db78ffa9d2863cbd1 --- /dev/null +++ b/tasks/belt-pick/environment/world/gauntlet/harness.py @@ -0,0 +1,241 @@ +"""Runs a controller file in its own process, exactly as the acceptance run does (Reactive Labs, Apache 2.0). + +`run_gauntlet.py` and the acceptance grader both use this module, so a controller sees the same child process, +environment variables (PATH, HOME, MUJOCO_GL, single-threaded BLAS), working directory (a fresh temporary +directory) and user (nobody, when started as root) in both. Observations go to the child pickled; the child +answers with raw float64 commands or a small JSON status object. Per-call and per-episode wall-time limits apply. +""" +from __future__ import annotations + +import json +import os +import pickle +import select +import shutil +import struct +import subprocess +import sys +import tempfile +import time + +import numpy as np + +CALL_TIMEOUT = 20.0 # s for a single reset/act call +INIT_TIMEOUT = 60.0 # s for import + Controller(model_info) +EPISODE_WALL = 150.0 # s of controller wall time per episode before it is cut off + +RUNNER = r''' +import json, os, pickle, struct, sys, types +import numpy as np +proto_in = os.fdopen(0, "rb", buffering=0) +proto_out = os.fdopen(os.dup(1), "wb", buffering=0) +os.dup2(2, 1) # controller prints go to stderr +def read_exact(n): + buf = b"" + while len(buf) < n: + chunk = proto_in.read(n - len(buf)) + if not chunk: + sys.exit(0) + buf += chunk + return buf +def send(kind, payload=b""): + proto_out.write(struct.pack(" 1 << 16: + raise ControllerError("oversized reply") + payload = self._read_exact(n, t0 + timeout) if n else b"" + if msg[0] != "init": + self.used += time.monotonic() - t0 + if self.used > EPISODE_WALL: + raise ControllerError("controller exceeded its wall-time budget for the episode") + if kind == 2: + raise ControllerError(payload.decode("utf-8", "replace")) + return kind, payload + + def reset(self, obs): + self._call(("reset", obs), CALL_TIMEOUT) + + def act(self, obs): + kind, payload = self._call(("act", obs), CALL_TIMEOUT) + if kind == 1: + st = json.loads(payload.decode("utf-8", "replace")) + if not isinstance(st, dict): + raise ControllerError("bad status reply") + return st + if len(payload) != 8 * self.nu: + raise ControllerError("command has wrong length") + return np.frombuffer(payload, dtype=" float: + """Score of an episode in which a T4 fault started (the belt sets the pace). + + 0 without the right abort after the fault started, with a limit hit, or with a reject picked, and 0 when no good + item was seated in time before the fault. Otherwise (good items seated in their carton within their cycle budget + before the fault + 1) / (good items whose cycle budget ran out before the fault + 1), at most 1. A fault starts + only after the budget of at least two good items has run out (task.fault_not_before), so at least two items are + always due when it starts. + """ + if not r.get("safe_pass") or "reject_picked" in r.get("violations", []): + return 0.0 + m = r.get("metrics", {}) + t_fault = float(r.get("onset_s") or 0.0) + due = sum(1 for t in (m.get("deadlines_s") or []) if t <= t_fault) + met = sum(1 for t in (m.get("seated_s") or []) if t <= t_fault) + if met == 0: + return 0.0 + return min(1.0, (met + 1) / (due + 1)) + + +def episode_score(r: dict) -> float: + """Episode score of the PL-4 acceptance run. + - An episode in which a T4 fault started: `fault_episode_score`. + - A controller error or wall-time cut-off, or an abort when nothing failed: 0. + - A full pass (every acceptance test): 1.0. + - Otherwise, if no limit was hit and the gripper ended empty: 0.5 x (good items seated in their own carton within + the cycle budget - rejects picked) / good items in the batch, at least 0. Rejects left on the belt earn nothing, + so a controller that does nothing scores 0. + - Everything else: 0.""" + status = r.get("outcome", {}).get("status") + if r.get("onset_tick") is not None and status != "crash": + return fault_episode_score(r) + if status in ("crash", "timeout", "abort"): + return 0.0 + if r.get("safe_pass"): + return 1.0 + bad = set(r.get("violations", [])) - {"late_item", "reject_picked", "unsettled"} + if r.get("safe") and not bad and status == "done": + m = r.get("metrics", {}) + n_good = max(1, int(m.get("n_good") or 0)) + net = int(m.get("good_ok") or 0) - len(m.get("rejects_picked") or []) + return 0.5 * max(0, net) / n_good + return 0.0 + + +def run_episode(gauntlet, task, ws: Workspace, tier: str, idx: int, seed: int, scene_xml: str) -> dict: + """One gauntlet episode with the controller in a child process; adds the episode score.""" + procs: list = [] + try: + r = gauntlet.run_episode(task, ws.factory(procs), tier, idx, seed, model_info_extra={"scene_xml": scene_xml}) + finally: + for c in procs: + c.close() + r["score"] = episode_score(r) + return r diff --git a/tasks/belt-pick/environment/world/robot/CHANGELOG.md b/tasks/belt-pick/environment/world/robot/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..150b80f0e50bed7c78e0fac85fe980b54c30f990 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/CHANGELOG.md @@ -0,0 +1,19 @@ +# Changelog – YAM Description + +All notable changes to this model will be documented in this file. + +## [2026-10-30] + +- Removed spotlight from robot spec. + +## [2026-10-02] + +- Added [`yam_linear_4310.xml`](yam_linear_4310.xml) and + [`scene_linear_4310.xml`](scene_linear_4310.xml) for the YAM / YAM Pro with + I2RT's `linear_4310` linear gripper and wrist-mounted Intel RealSense D405 + camera. Includes mesh-fitted finger collision primitives, hardware-matched + actuator gains, and a 5 mm squeeze range past the closed stop. + +## [2025-05-19] + +- Initial release. diff --git a/tasks/belt-pick/environment/world/robot/LICENSE b/tasks/belt-pick/environment/world/robot/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..12db7704f0a71570309c12f351dd656a8dec3b63 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 i2rt robotics + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tasks/belt-pick/environment/world/robot/README.md b/tasks/belt-pick/environment/world/robot/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e085e282b79c94f1a46df3e62969dd4dcdc8dc7b --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/README.md @@ -0,0 +1,56 @@ +# Yet Another Manipulator (YAM) Description (MJCF) + +> [!IMPORTANT] +> Requires MuJoCo 3.2.0 or later. + +## Changelog + +See [CHANGELOG.md](./CHANGELOG.md) for a full history of changes. + +## Overview + +This package contains simplified robot descriptions (MJCF) of the [YAM +robot](https://i2rt.com/products/yam-manipulator) developed by [I2RT +Robotics](https://i2rt.com/): + +- [`yam.xml`](yam.xml) ([`scene.xml`](scene.xml)): YAM with the `linear_3507` + gripper, derived from I2RT's [publicly available URDF + description](https://github.com/i2rt-robotics/i2rt/blob/main/robot_models/yam/yam.urdf). +- [`yam_linear_4310.xml`](yam_linear_4310.xml) + ([`scene_linear_4310.xml`](scene_linear_4310.xml)): YAM / YAM Pro with the + `linear_4310` gripper and wrist-mounted Intel RealSense D405 camera on I2RT's + camera bracket, derived from I2RT's SDK repository + ([i2rt-robotics/i2rt](https://github.com/i2rt-robotics/i2rt) at tag `v1.3.6`, + commit `120c3c81400171174604e503943f8d1ebc891058`). + +

+ + +

+ +## MJCF derivation steps (`yam.xml`) + +1. Started from `yam.urdf` (commit SHA d4efb66d81bd8bde42909880b16591d4af82e8c0). +2. Added the following to the URDF `` tag ``. +3. Loaded the URDF into MuJoCo and saved a corresponding MJCF. +4. Added home keyframe. +5. Added tracking light. +6. Add frictionloss (not identified). +7. Added armature based on reflected inertia values provided by the manufacturer. +8. Switched to implicitfast and used position actuators with kp/kv semantics. + +## `linear_4310` gripper and wrist camera variant (`yam_linear_4310.xml`) + +Derived from `yam.xml` and I2RT's SDK repository ([i2rt-robotics/i2rt](https://github.com/i2rt-robotics/i2rt), tag `v1.3.6`): + +1. Added meshes for the `linear_4310` gripper and D405 bracket into `assets/linear_4310/`. +2. Updated arm joint ranges and actuator PD gains to match the YAM Pro + `linear_4310` SDK configuration. +3. Replaced the gripper on `link_6` with the `linear_4310` linear gripper: + - Finger travel is 0 to 47.5 mm, with joint and control limits extending 5 mm past closed to allow grasp squeezing. + - Actuator PD gains and force limits match the hardware's 50 N per-pad grip force limit. + - Modeled finger collision geometry using box primitives fitted to the visual meshes, with flat contact pads aligned for parallel grasping. +4. Added the wrist-mounted Intel RealSense D405 camera on `link_6` using extrinsics, intrinsics, and mass properties from I2RT's CAD station model. + +## License + +This model is released under an [MIT License](LICENSE). diff --git a/tasks/belt-pick/environment/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl b/tasks/belt-pick/environment/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl new file mode 100644 index 0000000000000000000000000000000000000000..9f0e95b8bf061d28ad0d558d9283cfd70efa7d2a --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f01bcd92b447c3a44c1ad9345367628d4157fe4c07b545ccbf9bc4ae81115112 +size 469584 diff --git a/tasks/belt-pick/environment/world/robot/assets/linear_4310/gripper.stl b/tasks/belt-pick/environment/world/robot/assets/linear_4310/gripper.stl new file mode 100644 index 0000000000000000000000000000000000000000..e0259ae10efec0fbdeb6e2aa5fcce2d2e005d6de --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/linear_4310/gripper.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d949c401186197d842ca8f9b23bfcbf24bed8461b421df06093c65e4ead21f5d +size 400084 diff --git a/tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_left.stl b/tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_left.stl new file mode 100644 index 0000000000000000000000000000000000000000..6cd45e201d1d9f155b2f8473e8061cd5bbb38b10 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_left.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03d94f53d7b5e9e1871ea6f3925c68d7a2f894b08e0c575fa0b9ed4024684ff7 +size 400084 diff --git a/tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_right.stl b/tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_right.stl new file mode 100644 index 0000000000000000000000000000000000000000..79f3ba9fcbbb9737870400957b9e6925f5b57a9c --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_right.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f620aae9c15e00e2ea4e5bf5e9a49e7edb2d23128b8955cfacc0da8da45c72f +size 400084 diff --git a/tasks/belt-pick/environment/world/robot/assets/model2.stl b/tasks/belt-pick/environment/world/robot/assets/model2.stl new file mode 100644 index 0000000000000000000000000000000000000000..ecaf4fed776a81d5a2307394705a010e83d0a5f1 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/model2.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ac61c0313ed00c38655e41681af1b8b307cf8d5ef57209a75f215cea02df754 +size 524284 diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__10.stl b/tasks/belt-pick/environment/world/robot/assets/model2__10.stl new file mode 100644 index 0000000000000000000000000000000000000000..c4c0bd8b1a8dcd4c88e48fae8df67b97f4a9e1c7 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/model2__10.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b879cc07f547b7a2ac52e428dd206e80a0d4b0e805cb56b9a8230df04a690923 +size 524284 diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__11.stl b/tasks/belt-pick/environment/world/robot/assets/model2__11.stl new file mode 100644 index 0000000000000000000000000000000000000000..8cf441930bd80f233b0fd4c4c54f7f77a30d3575 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/model2__11.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af220d2a51e8444392aef36e2fe4a6f69aed22bc292a7f38e54da3b4f5253434 +size 248584 diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__2.stl b/tasks/belt-pick/environment/world/robot/assets/model2__2.stl new file mode 100644 index 0000000000000000000000000000000000000000..08595a8d05cd66e9eeebf0e1e2d747b5303d3f6c --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/model2__2.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30dab41f14bae95d737abca3c934eb5d570ab107dff0b40952fbdfb9d07eab79 +size 524284 diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__3.stl b/tasks/belt-pick/environment/world/robot/assets/model2__3.stl new file mode 100644 index 0000000000000000000000000000000000000000..89c512c0f53733a6956a988c496db1b83830940d Binary files /dev/null and b/tasks/belt-pick/environment/world/robot/assets/model2__3.stl differ diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__4.stl b/tasks/belt-pick/environment/world/robot/assets/model2__4.stl new file mode 100644 index 0000000000000000000000000000000000000000..7186d0fa1b8c22fd43dbf9ee551d14f107f909f3 Binary files /dev/null and b/tasks/belt-pick/environment/world/robot/assets/model2__4.stl differ diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__5.stl b/tasks/belt-pick/environment/world/robot/assets/model2__5.stl new file mode 100644 index 0000000000000000000000000000000000000000..62df9d9e77dcc64b2f65798c29a91c0e6a413b53 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/model2__5.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09f08e7dead2d6363618471adadb1b94af39e8056676670f3fd21ec06c197b20 +size 524284 diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__6.stl b/tasks/belt-pick/environment/world/robot/assets/model2__6.stl new file mode 100644 index 0000000000000000000000000000000000000000..71fc6c2f8b58f4d6c663992c8e96b612c0f4ed22 Binary files /dev/null and b/tasks/belt-pick/environment/world/robot/assets/model2__6.stl differ diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__7.stl b/tasks/belt-pick/environment/world/robot/assets/model2__7.stl new file mode 100644 index 0000000000000000000000000000000000000000..1aef9c141dcc6135568c61c9c86ea9178e024b0c Binary files /dev/null and b/tasks/belt-pick/environment/world/robot/assets/model2__7.stl differ diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__8.stl b/tasks/belt-pick/environment/world/robot/assets/model2__8.stl new file mode 100644 index 0000000000000000000000000000000000000000..897890f2a9bc4e1e0c6dc88d8e69c3d35a756e0e --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/assets/model2__8.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db3708da6b14daf3fc9a1909a8325b68f65ff69146cdd20b69a9ddc4ce51f50d +size 524284 diff --git a/tasks/belt-pick/environment/world/robot/assets/model2__9.stl b/tasks/belt-pick/environment/world/robot/assets/model2__9.stl new file mode 100644 index 0000000000000000000000000000000000000000..e6287e0473db5b240be759fd44a63cdac8ae4536 Binary files /dev/null and b/tasks/belt-pick/environment/world/robot/assets/model2__9.stl differ diff --git a/tasks/belt-pick/environment/world/robot/yam_linear_4310.xml b/tasks/belt-pick/environment/world/robot/yam_linear_4310.xml new file mode 100644 index 0000000000000000000000000000000000000000..ddb60e49c668da8d29f0a16b6420d0d694776689 --- /dev/null +++ b/tasks/belt-pick/environment/world/robot/yam_linear_4310.xml @@ -0,0 +1,256 @@ + + + + diff --git a/tasks/belt-pick/environment/world/run_gauntlet.py b/tasks/belt-pick/environment/world/run_gauntlet.py new file mode 100644 index 0000000000000000000000000000000000000000..0f43d65993a1f34ae78557e2f42952f0d8321797 --- /dev/null +++ b/tasks/belt-pick/environment/world/run_gauntlet.py @@ -0,0 +1,59 @@ +"""Runs a controller through the PL-4 acceptance gauntlet on public seeds and prints the verdicts. + +usage: python3 run_gauntlet.py [--controller /app/controller.py] [--tiers T0,T1,T2,T3,T4] [--episodes 2] + [--seed 0] [--json out.json] + +The controller runs in its own process exactly as in the acceptance run (gauntlet/harness.py). Prints one line +per episode: tier, index, score, verdicts, violations and the main metrics. The acceptance run uses hidden seeds +and the same scoring. Needs MUJOCO_GL=osmesa (set in the image). +""" +import argparse +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import task as task_mod # noqa: E402 (puts gauntlet/ on sys.path) +import gauntlet as G # noqa: E402 +import harness # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--controller", default=os.path.join(HERE, "controller.py")) + ap.add_argument("--tiers", default="T0,T1,T2,T3,T4") + ap.add_argument("--episodes", type=int, default=2) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--json", default="") + a = ap.parse_args() + ws = harness.Workspace(os.path.abspath(a.controller), HERE) + task = task_mod.TASK + rows, t0 = [], time.time() + try: + for tier in a.tiers.split(","): + for i in range(a.episodes): + r = harness.run_episode(G, task, ws, tier, i, a.seed, task.scene_xml) + rows.append(r) + m = r.get("metrics", {}) + print(f"{tier} {i:2d} score={r['score']:.2f} success={r['success']} safe={r['safe']} " + f"safe_pass={r['safe_pass']} fault={r['pspec'].get('fault') or '-'} " + f"dist={r['pspec'].get('disturbance') or '-'} " + f"outcome={r.get('outcome', {}).get('status')}/{r.get('outcome', {}).get('fault', '')} " + f"violations={r['violations']} progress={m.get('progress')} items={m.get('items')} " + f"cycle_s={m.get('cycle_s')} grasp_N={m.get('grasp_force_n')} frame_N={m.get('frame_force_n')} " + f"wall_N={m.get('wall_force_n')} belt_N={m.get('belt_force_n')} t_done={r.get('done_time_s')}" + + (f" error={r['error']}" if r.get("error") else "") + + (f" ctl_error={r['outcome'].get('error')}" if r.get("outcome", {}).get("error") else ""), flush=True) + finally: + ws.close() + mean = sum(r["score"] for r in rows) / max(1, len(rows)) + print(f"mean score {mean:.3f} over {len(rows)} episodes ({time.time() - t0:.0f} s)") + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1, default=str) + + +if __name__ == "__main__": + main() diff --git a/tasks/belt-pick/environment/world/scene.xml b/tasks/belt-pick/environment/world/scene.xml new file mode 100644 index 0000000000000000000000000000000000000000..c31ac7e157af8d7415c8a639f029121d9773f3e1 --- /dev/null +++ b/tasks/belt-pick/environment/world/scene.xml @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/belt-pick/environment/world/skills/LICENSE b/tasks/belt-pick/environment/world/skills/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/tasks/belt-pick/environment/world/skills/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/belt-pick/environment/world/skills/SOURCE.md b/tasks/belt-pick/environment/world/skills/SOURCE.md new file mode 100644 index 0000000000000000000000000000000000000000..4bbd8aaa389f2d7c11955f9897fa949b235e1bb3 --- /dev/null +++ b/tasks/belt-pick/environment/world/skills/SOURCE.md @@ -0,0 +1,4 @@ +Copied unchanged from github.com/google-deepmind/robotics-antigravity-plugin (plugins/robotics/skills), +commit 3dde33820355c70fe8d8e33e42707cdcb742ceb4 (2026-11-20). Copyright 2026 Google LLC, Apache License 2.0 (LICENSE). +Shipped into task containers at /app/skills/ so agents can use the same workflow (iteration, gauntlet, critic rubric, +motion planning, IK, perception). diff --git a/tasks/belt-pick/environment/world/skills/blender-creation/SKILL.md b/tasks/belt-pick/environment/world/skills/blender-creation/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ff13d5d637af28f0f4bc055b659a2a7dc2f1ed52 --- /dev/null +++ b/tasks/belt-pick/environment/world/skills/blender-creation/SKILL.md @@ -0,0 +1,499 @@ +--- +name: blender-creation +description: >- + Creates physically calibrated, articulated, + PBR-textured 3D MuJoCo assets (MJCF + model.xml, .mjz, mjSpec) from scratch + using headless Blender (bpy, bmesh, + blender_mesh_utils, asset_build_utils), + convex collision synthesis, 10-scenario + auditing, and Studio preview. Use only + when asked to create, model, or build a + 3D MuJoCo object from a URL, image, or + text description, or when blender-creation + is named. Don't use for non-MuJoCo + Blender/Cycles/CAD modeling. +metadata: + publisher: google +--- + +# Authoring 3D MuJoCo Assets from Scratch in Blender (`bpy` / `bmesh` + PBR) + +> [!IMPORTANT] +> +> **Companion to [`rules/mujoco_asset_standards.md`][asset-standards]**: Read +> [`rules/mujoco_asset_standards.md`][asset-standards] first for the mandatory +> MuJoCo coordinate frame (`UP_POSZ_FORWARD_POSX_RIGHT_NEGY`), SI unit rules, +> group separation (`group="2"` visual, `group="3"` collision, `group="4"` +> sites), and physics/audit requirements. This guide covers how to research, +> measure, model, sculpt, UV-unwrap, texture, bake, export, verify, and +> interactively preview new assets from scratch using headless Blender +> (`PYTHONDONTWRITEBYTECODE=1 "$BLENDER_BIN" -b -P ...`), +> [`scripts/blender_mesh_utils.py`](scripts/blender_mesh_utils.py) (`bmu`), +> [`scripts/asset_build_utils.py`](scripts/asset_build_utils.py) (`abu`), +> [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md), +> [`mujoco-showcase-shot/SKILL.md`](../mujoco-showcase-shot/SKILL.md) +> ([`render_showcase_shot.py`](../mujoco-showcase-shot/scripts/render_showcase_shot.py)), +> and [`mujoco-studio-sidecar/SKILL.md`](../mujoco-studio-sidecar/SKILL.md) +> so they look, behave, and inspect accurately in **MuJoCo's Filament PBR +> renderer** and **MuJoCo Studio**. + +--- + +## 1. Entry Point, Subagent Orchestration, Local Blender Setup & Reference Intake + +### 1.0 Invocation, Defaults & Subagent Orchestration + +Users invoke this skill in natural language with a product URL, reference image(s), or text specifications: + +> *"Build a 3D MuJoCo asset for these kitchen tongs: ``"* +> *"Follow blender-creation to model the object in ``"* + +**Defaults & Optional Overrides**: +By default, the skill executes the full end-to-end pipeline: auto-detected articulations, intermediate diagnostic renders, 10-scenario dynamic physics simulation auditing (§7.3), and a 360° Filament turntable showcase video (§7.4). Users can optionally request overrides in plain English or bullet points: +- **`Fast` / `No Turntable`**: Skips Step 7.4 showcase video rendering (saves render time). +- **`Rigid-Only`**: Forces `0` joints, authoring the object as a single rigid body. +- **`Skip Physics Audit` / `Fast Audit`**: Skips the 10-scenario dynamic physics simulation suite in Step 7.3 (relying only on Step 7.1 static hygiene & collision alignment checks). + +1. **If you are the top-level / parent conversation**: + - Spawn a `self` subagent (`Model: "inherit"`) via `invoke_subagent` to build and verify the asset, passing all user-specified instructions, URLs, and overrides, `Parent Conversation ID: `, and the target asset output parent directory, and instructing the subagent to read this `blender-creation` skill, [`rules/mujoco_asset_standards.md`][asset-standards], [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md), and [`mujoco-showcase-shot/SKILL.md`](../mujoco-showcase-shot/SKILL.md). Do **not** instruct the subagent to write scratch/intake files inside the parent conversation's `brain//` directory (macOS Seatbelt sandboxing blocks cross-conversation `brain/` access with `PermissionError`); let the subagent use its own `/scratch/` and return the finished asset and preview paths. + - **When the subagent finishes**: Follow **Step 7.6** ([`mujoco-studio-sidecar/SKILL.md`](../mujoco-studio-sidecar/SKILL.md)) in the top-level conversation to launch (or reuse) the MuJoCo Studio Web sidecar daemon (`studiod.py`) pointed at the finished asset directory (`--workspace_dir=`) and verify `/_studio/status` (`"ok": true`, `"daemon_connected": true`). Launch `studiod.py` from the top-level conversation rather than inside the builder subagent so the background daemon is not reaped when the subagent exits. In your final response, first present the finished asset path, model summary (dimensions, mass, joints, visual/collision breakdown, audit status), side-by-side comparison, and turntable video (unless skipped via `Fast (No Turntable)`, briefly noting in a 1-line caption that the reel shows a full 360° textured visual spin followed by translucent physics collision hull inspection), and **place `[MuJoCo Studio](sidecar://robotics/mujoco_studio/)` (plus `http://127.0.0.1:/` from `$SESSION_FILE` if the Node sidecar proxy is not active) as the very last item at the bottom of your response** so the interactive sidecar pill is never missed at the top. + +2. **If you are already the spawned Main Builder Subagent**: + - Do **not** spawn a nested build subagent—execute **Sections 1.1 through 7.5** directly (you may still invoke the read-only `browser` subagent during Step 1.1 if a product URL requires client-side JS rendering). Keep all scratch/intake files in **this subagent's own** `/scratch/` so sandboxed `run_command` steps have local read/write access without `PermissionError`. Do **not** run **Step 7.6** (`studiod.py`) inside the subagent; instead, return the finished `` path, model summary, comparison images, and turntable video path to the parent conversation so the parent conversation launches `studiod.py` and presents the Studio link. + - **Ensure `uv` and Headless Blender (`4.2+`) Are Installed Locally (macOS & Linux)**: + ```bash + uv --version + if [ -x "/Applications/Blender.app/Contents/MacOS/Blender" ]; then + BLENDER_BIN="/Applications/Blender.app/Contents/MacOS/Blender" + else + BLENDER_BIN="blender" + fi + "$BLENDER_BIN" --version || (sudo apt-get update && sudo apt-get install -y blender) + ``` + Run Blender scripts with `PYTHONDONTWRITEBYTECODE=1 "$BLENDER_BIN" -b -P /scratch/build_asset.py` and add `/skills/blender-creation/scripts` to `sys.path` inside the Blender script to `import blender_mesh_utils as bmu`. + - **MuJoCo Compilation, Filament Showcase Renders & Reference Intake (`uv run`)**: + ```bash + uv run --with mujoco --with numpy --with scipy --with trimesh --with Pillow \ + python3 /scratch/script.py + ``` + Inside your scratch script, add the plugin script directories (`/skills/blender-creation/scripts`, `/skills/mujoco-audit/scripts`, and `/skills/mujoco-showcase-shot/scripts`) to `sys.path` to import `asset_build_utils as abu`, `audit_scenarios`, and `render_showcase_shot`. + - **Scope & Workspace Hygiene**: + - Run `audit_scenarios` 10-scenario physics drop/tip/grasp simulations (**Step 7.3**) by default, verifying all scenarios pass (or remediate failing checks following [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md)). Only skip dynamic simulations if the user explicitly specifies `Skip Physics Audit` or `Fast Audit`. Do not generate a second `_mechanical/` bundle unless requested. Verify clean static `MjModel` compilation, zero-backface normals (`abu.render_blender_diagnostic_sheet`), collision alignment (`audit_scenarios.compute_collision_alignment_summary`), kinematic joint poses (`Articulations: Auto`), and all dynamic physics drop/tip/settle scenarios. + - Keep all scratch scripts, downloaded reference photos, intermediate meshes, diagnostic `.jpg`/`.png` sheets, `.blend` files, virtual environments (`.venv`), and caches in `/scratch/`, `~/.venvs/`, and `~/.cache/mujoco_pbr_cache`. Only write final asset deliverables (`model.xml`, `meshes/*.obj`, `textures/*.png`) into the target asset directory, and never write `.pyc` / `__pycache__`, `.venv`, or `studiod` scaffold/runtime files into the asset directory. + - Honor knob overrides: `Articulations: Rigid-Only` -> `0` joints; `Depth: Fast (No Turntable)` -> skip Step 7.4; `Skip Physics Audit` / `Fast Audit` -> skip Step 7.3. + +### 1.1 Intake, Reference Contact/Detail Sheets & Form Brief + +1. **Product URL & Reference Intake (`<= 8` Image Reads)**: + - Never guess product identity, category, or dimensions from a URL path slug (e.g., `/Walnut-Elegant-Design-Coffee-Products/dp/...` may be a truncated SEO slug rather than a coffee table). + - **When a product URL is provided**: + 1. Invoke the read-only `browser` subagent to navigate to `` on behalf of the user. Inspect the live rendered page just as a human designer would: + - Extract the verified product title, materials, mechanism descriptions, and dimensional specs (`L × W × H` in `mm` and bare-product mass in `kg`, cross-checking retail `Item Weight` vs packaged shipping weight). + - Identify high-resolution product gallery / carousel image URLs. + 2. **If access is blocked by an interactive CAPTCHA or security gate**: stop without attempting to circumvent the gate and ask the user for the product dimensions, specifications, or reference photos directly. + 3. Download the collected high-resolution gallery images into `/scratch/intake/ref_*.jpg` (e.g. using `curl` or a minimal inline download script). + - **When no URL is provided (text-only query)**: Look up bare-product `L x W x H` (`mm`) and mass (`kg`) via `search_web` (or invoke the `browser` subagent if `search_web` returns only bare redirect links without snippets). Cross-check retail `Item Weight` against dimensions and material density. + - **Composite Sheets (`<= 8` Image Reads)**: Never call `read_file` on dozens of individual frames. Stitch the downloaded `ref_*.jpg` photos and sub-feature crops into `ref_contact_sheet` and `ref_details_grid` via `abu.build_ref_contact_and_detail_sheets`, then inspect those composite sheets with `read_file`. +2. **Sample Photometric RGB Percentiles Directly from Reference Crops (`rgb_sample_boxes`)**: + - Do **not** invent `RGB` values from verbal category names (*"red plastic"*, *"black rubber"*, *"green plush"*). Pass `rgb_sample_boxes=[('main_shell', ref_path, (x0, y0, x1, y1)), ...]` to `abu.build_ref_contact_and_detail_sheets` to measure `[p25, p50, p75]` sRGB tuples directly from uniform interior surface patches (excluding specular hotspots and cast shadows). +3. **Write a `<= 25`-Line Form Brief & Named Parameter Block `P` (`<= 40` Named Dimensions)**: + - Before writing Blender `bmesh` code, write a concise **Form Brief** and define a named parameter dictionary `P = dict(...)` (`<= 40` named dimensions in `mm` / `m` and `deg` with provenance comments) rather than hard-coding hundreds of magic coordinate tuples: + - **Named primary surfaces & how they meet**: side silhouette facets/angles, plan-view taper, crown cross-section, negative space / open daylight gaps between parts, and flush vs. stepped junctions. + - **Left/right (`+Y` vs. `-Y`) and front/back (`+X` vs. `-X`) asymmetry**: explicitly note which levers, clips, buttons, labels, or ports appear on each side. + - **Material regions & parting lines**: e.g., two-shot overmold where rigid ABS forms the inner core and exposed flush rims while matte TPE forms the outer grip skin, or recessed branding pockets. + - **Mechanisms & travel**: moving sub-parts (hinged lids, sliders, clips, blades, buttons, knobs) with true physical pivot/axis and travel in `m` or `rad`. + +--- + +## 2. Tool Reference & Target Renderer Rules + +### 2.1 Quick Helper API Reference (`blender_mesh_utils`, `asset_build_utils`, `render_showcase_shot`) + +- **`blender_mesh_utils as bmu`** *(inside headless Blender `"$BLENDER_BIN" -b -P`, from [`scripts/blender_mesh_utils.py`](scripts/blender_mesh_utils.py))*: + - `bmu.clear_scene() -> None` + - `bmu.assign_pbr_material(objects, name=None, *, base_color=None, base_color_srgb=(200, 200, 200), roughness=0.4, metallic=0.0, normal_bump_mm=0.0, bump_height_mm=0.0, bump_scale=250.0) -> bpy.types.Material` + - `bmu.skin_skeleton(name, nodes_xyzr, edges=None, *, subsurf_levels=2) -> obj` + - `bmu.metaball_sdf(name, elements, *, resolution=0.002) -> obj` + - `bmu.swept_tube(name, points_xyzr, *, bevel_resolution=6) -> obj` + - `bmu.voxel_smooth_union(name, objects, *, voxel_size=0.0015, smooth_iterations=6) -> obj` + - `bmu.apply_boolean_cutter(target_obj, cutter_obj, *, operation='DIFFERENCE', solver='MANIFOLD') -> obj` + - `bmu.smart_seam_unwrap(target_obj, *, angle_limit_deg=66.0, margin=0.005) -> obj` + - `bmu.smart_uv_project(objects, *, angle_limit_deg=66.0, island_margin=0.01, margin=None) -> list[obj]` + - `bmu.pack_shared_uv_atlas(objs, *, margin=0.005, rotate=True, align_minimal_bbox=True, match_3d_area=True) -> None` + - `bmu.finalize_and_export_obj(target_obj, out_obj_path, *, crease_deg=None, world_pos=None, body_pos=None, ensure_uvs=True) -> {'verts', 'quads', 'tris', 'earclipped_ngons'}` + - `bmu.export_convex_hull_col(source_obj_or_points, out_obj_path, *, clip_bounds_world_m=None, clip_bounds_m=None, max_verts=64, name=None, world_pos=(0,0,0), body_pos=None) -> col_obj` + - `bmu.bake_pbr_maps(out_dir, *, material_groups=None, resolution=1024, samples=8) -> {key: {'basecolor', 'roughness', 'metallic', 'normal'}}` +- **`asset_build_utils as abu`** *(inside `uv run` scripts, from [`scripts/asset_build_utils.py`](scripts/asset_build_utils.py))*: + - `abu.build_ref_contact_and_detail_sheets(ref_paths, detail_crops, out_contact_png, out_details_png, *, raw_crops_dir=None, rgb_sample_boxes=None, cols=3, cell_size=440, include_shadow_lift=False) -> dict` + - `abu.fetch_ambientcg_maps(asset_id, *, cache_dir=None, resolution='1K') -> {'color', 'roughness', 'normal_gl', 'metallic', 'ao', 'opacity', ...}` + - `abu.rasterize_uv_world_fields(obj_paths, canvas_size=1024, *, part_offsets=None) -> dict` + - `abu.dilate_uv_gutters(arr, valid_mask, *, max_dist_px=12) -> np.ndarray` + - `abu.triplanar_project_map(map_2d, xyz, world_normal, *, texels_per_meter=4000.0, sharpness=4.0) -> np.ndarray` + - `abu.height_to_normal_rgb(height_map, strength=3.5, *, smooth_sigma=0.0, valid_mask=None) -> (H,W,3) uint8` + - `abu.normal_rgb_from_3d_height_fn(height_fn, uv_world_fields, *, step_mm=0.15, strength=1.0) -> (H,W,3) uint8` + - `abu.fbm_noise_3d(xyz, *, base_freq=25.0, wavelength_mm=None, octaves=4, persistence=0.5, seed=42) -> (...,) float32` + - `abu.compute_volume_weighted_hull_masses(mesh_dir, col_names, total_mass_kg, *, density_weights=None) -> {col_name: mass_kg}` + - `abu.render_blender_diagnostic_sheet(blend_path, out_png, *, xml_path=None, part_pivots=None, panel_size=420) -> {'out_png', 'has_backfaces', 'backface_pixels_per_view'}` + - `abu.build_variant_bundles(base_asset_dir, parent_assets_dir, base_name, variants, render_variant_textures_fn) -> list[str]` +- **`render_showcase_shot`** *(inside `uv run` scripts, from [`../mujoco-showcase-shot/scripts/render_showcase_shot.py`](../mujoco-showcase-shot/scripts/render_showcase_shot.py))*: + - `render_side_by_side_comparison(asset_path, ref_specs, out_png, *, detail_crops_out_png=None, six_view_out_png=None, six_view_panel_size=420, six_view_qpos=None, fovy=35.0, white_bg=True, clay_only=False) -> {'comparison_png', 'detail_crops_png', 'six_view_png'}` + - `render_filament_still(asset_path, views, *, width=800, height=800, fovy=None, white_bg=False, show_plinth=False) -> list[np.ndarray]` + - `render_6view_inspection_sheet(asset_path, out_png, *, panel_size=420, qpos=None) -> out_png` + - `render_wireframe_and_uv_sheet(asset_path, out_png, *, panel_size=440) -> out_png` + - `render_showcase_shot_video(asset_path, output_mp4, width=960, height=720, fps=30, duration=8.0, articulation_cycles=2.0) -> dict` + +--- + +### 2.2 Target Renderer: Optimize for MuJoCo Filament (Not Standalone Cycles) + +1. **Get into MuJoCo Filament Early & Render Intermediate Diagnostics**: + - Do **not** build an entire asset blind and only render at the very end. After blocking out primary 3D geometry in Blender (saving `/scratch/.blend` and exporting `.obj` meshes), immediately run **intermediate diagnostic renders**: + - `abu.render_blender_diagnostic_sheet(blend_path, out_png=..., xml_path=...)` to inspect 6-view clay/wireframe shading, backface orientation (`has_backfaces == False`), and joint pivots. + - `render_showcase_shot.render_side_by_side_comparison(..., clay_only=True)` to compare your untextured 3D form directly against the reference photos at matched camera angles before spending time on textures and decals. +2. **MuJoCo Filament Normal Handling (`model_resources.cc`) — Smooth Curves vs. Crisp Creases**: + - In MuJoCo's Filament backend (`FillMeshBuffer`), if the angle between a triangle's geometric `face_normal` and its exported vertex normal `mesh_normal` exceeds $\sim 36.87^\circ$ ($\cos\theta < 0.8$), Filament may fall back to the flat `face_normal` (`UseFaceNormal`). + - **For smooth curved surfaces, bevels & domes**: + 1. Always call `bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])` on every closed mesh before setting smooth shading or exporting `.obj`. + 2. Set `f.smooth = True` on smoothly curved/beveled faces and keep adjacent bevel/fillet step angles $\le 15^\circ\text{–}22^\circ$ so `dot(face_normal, vertex_normal) > 0.8`. + - **For crisp industrial-design creases, chamfers & faceted parts**: + 1. Do **not** blindly set `f.smooth = True` across sharp ridges, flat-topped prismatic facets, or distinct chamfer bevels. + 2. Use `bmu.finalize_and_export_obj(obj, out_obj_path, crease_deg=35.0, body_pos=...)` (which marks crease edges above `crease_deg` sharp and applies `WEIGHTED_NORMAL(keep_sharp=True)`) or keep flat facets `f.smooth = False` so Filament preserves crisp specular transitions. + +--- + +## 3. Pure-Blender Geometry Authoring, Modular `bmu` Helpers & Topology Rules + +### 3.1 Freedom of Geometry & Modular `blender_mesh_utils` (`bmu`) Builders + +You have full freedom in Python (`bpy` / `bmesh` / `mathutils` / modifiers) plus the zero-magic builders in [`scripts/blender_mesh_utils.py`](scripts/blender_mesh_utils.py) (`bmu`) to construct whatever geometry faithfully captures each component: + +- **Profile Lofting, Extrusion, Bevels & Boolean Split Shells (`bmesh` + `bmu.apply_boolean_cutter`)**: + - For faceted or contoured industrial housings (e.g., an ergonomic tool housing with shoulder chamfers, plan-view taper, and two-shot elastomer/ABS overmold parting lines), drive cross-sections from your named parameter dictionary `P`. + - Use `bmu.apply_boolean_cutter(target_obj, cutter_obj, operation='DIFFERENCE' | 'INTERSECT' | 'UNION')` (which safely runs Blender's `MANIFOLD` boolean solver with an automatic welded `EXACT` fallback) to carve recessed pockets, moat grooves, actuator slots, and flush two-shot material splits from a shared outer envelope. +- **Declarative Organic & Tubular Builders (`bmu`)**: + - `bmu.skin_skeleton(name, nodes_xyzr, edges=None, *, subsurf_levels=2)`: branching organic limbs, frames, or handles from `(x, y, z, r)` or `(x, y, z, (rx, ry))` skeleton graphs. + - `bmu.metaball_sdf(name, elements, *, resolution=0.002)`: analytical implicit SDF blends (`BALL`, `CAPSULE`, `ELLIPSOID`, `CUBE`, with `use_negative=True` for ergonomic thumb indents or cavities). + - `bmu.swept_tube(name, points_xyzr, *, bevel_resolution=6)`: 3D `NURBS` tubes, cords, straps, wire loops, or bent rods with per-point radius and end caps. + - `bmu.voxel_smooth_union(name, objects, *, voxel_size=0.0015, smooth_iterations=6)`: watertight voxel-remeshed fillets across intersecting sub-parts. + +### 3.2 Kinematic Root Selection & Mesh Splitting by Link / Material Role + +1. **Kinematic Root Body Selection**: + - Choose the **root ``** to be the **primary stationary base or primary grasped housing** during normal operation, and make components that move relative to that housing the child `` elements. +2. **Split into Separate Meshes by Articulation Link & Material Role**: + - Export separate `.obj` files in `meshes/` for each articulated `` (link) and each distinct `` within a body. + +### 3.3 Sensible Polycount Budgets & `bmesh` Topology Rules + +- **Polycount Budgets**: + - Simple flat/beveled component: $100\text{–}1,500\text{ tris}$. + - Contoured housing with rounded corners, fillets & cutouts: $1,500\text{–}6,500\text{ tris}$. + - Complete multi-part prop/appliance: **$5,000\text{–}20,000\text{ tris}$ total** across all visual meshes. +- **`bmesh` Topology Rules**: + 1. **Subdivide straight edges before carving localized edge features** and add an inner rim loop so cutouts stay confined cleanly to the outer lip. + 2. **Keep planar hole loops strictly inside the outer perimeter ($\ge 2\text{ mm}$ clearance)** before calling `bmesh.ops.triangle_fill`. + 3. **Prevent coplanar Z-fighting between layered parts**: separate layered surfaces by $\ge 0.2\text{ mm}$ or cut an interior pocket. + 4. **Uniform metric edge offsets**: inset perimeter bevels by a constant metric distance $d$ (in meters) along $X$ and $Y$ rather than radial fractions on elongated parts, and never pinch top/bottom rings into a zero-thickness knife-edge equator. + 5. **Watertight thickness + `inertia="shell"` on thin visual meshes**: extrude thin plaques, labels, blades, and lenses to $\ge 1.5\text{–}3\text{ mm}$ watertight thickness and declare `` so `mjCMesh::Compile` never fails with `mesh volume is too small`. + +--- + +## 4. Canonical MuJoCo Coordinate Frame, Camera Angles & `model.xml` + +1. **World Coordinate Frame (`UP_POSZ_FORWARD_POSX_RIGHT_NEGY`, `1 unit = 1.0 m`)**: + - **`+Z`** Up (resting base at $z = 0.000\text{ m}$), **`+X`** Front, **`-X`** Back, **`+Y`** Left, **`-Y`** Right. + - Looking at **`+X` Front** toward `-X`, viewer-left is **`-Y`** and viewer-right is **`+Y`**. Looking at **`-Y` Right** toward `+Y`, viewer-left is **`-X`** and viewer-right is **`+X`**. +2. **MuJoCo `mjvCamera` Azimuth & Elevation Convention**: + - **`azimuth = 180°`**: Views **`Front (+X)`** | **`azimuth = 0°`**: Views **`Back (-X)`** | **`azimuth = 90°`**: Views **`Right (-Y)`** | **`azimuth = 270°`**: Views **`Left (+Y)`**. + - **`elevation < 0°`**: Camera above looking downward (`-25°..-45°` = tabletop 3/4 view; `-88°` = overhead `Top (+Z)` view). +3. **Articulated Child Bodies & Non-Destructive Identity-Axis Export (`bmu.finalize_and_export_obj`)**: + - Keep scene objects at their assembled world poses in `.blend`, and pass `body_pos=(px, py, pz)` to `bmu.finalize_and_export_obj(obj, out_obj_path, crease_deg=..., body_pos=(px, py, pz))` so `.obj` vertices export around each child body's local joint origin `(0, 0, 0)` with `forward_axis='Y', up_axis='Z', export_materials=False` without mutating live `.blend` positions. +4. **Canonical `model.xml` Skeleton** (`/model.xml`, no `scene.xml`, no `