Repository navigation
[Fix] Create ContactSensor PhysX views per body so nested-hierarchy assets initialize - #6378
Conversation
The PhysX rigid-body and contact views were created from a single parent-level name alternation built from the first matched body's parent. Bodies nested under other bodies (URDF importer output in Isaac Sim 6.0+) do not share a parent, so sensor initialization failed on such assets. Create the views from one path expression per body, reusing the per-body destination expressions that prim resolution already returns. With a pattern list the views order bodies pattern-major (body_id * num_envs + env_id), so the copy kernels and the debug visualization switch from env-major to body-major indexing.
CI on the previous commit surfaced three issues with the per-body pattern lists: - body_names sliced the first num_sensors view paths, which under body-major ordering repeats the first body across envs; stride by num_envs instead to pick one path per body. - create_rigid_contact_view requires filter_patterns as one list per sensor pattern when given a pattern list; replicate the filter list accordingly. - The Newton visualizer contact-arrow fallback reshaped raw view transforms env-major; reshape body-major and transpose. Also run the nested-hierarchy test scene with replicate_physics disabled (the chain is hand-authored USD, not a clonable referenced asset) and include body counts in the initialization error message.
The nested-hierarchy regression test previously spawned its hand-authored chain through InteractiveScene, but scene cloning materializes environment copies backend-side from the env_0 prototype, which does not cover a hand-authored AssetBaseCfg asset; at multiple envs the views saw only env_0's bodies. Author the kinematic chain directly under each environment prim and create the ContactSensor standalone: the code paths under test (prim resolution, per-body view creation, body-major data kernels) only depend on the prims existing on the stage. Validate per-body world positions per env, which pins the (env, body) cell mapping exactly.
| self._contact_view = self._physics_sim_view.create_rigid_contact_view( | ||
| body_names_glob, | ||
| filter_patterns=filter_prim_paths_glob, | ||
| body_path_globs, | ||
| filter_patterns=[filter_prim_paths_glob] * len(body_path_globs), | ||
| max_contact_data_count=self.cfg.max_contact_data_count_per_prim * len(body_names) * self._num_envs, |
There was a problem hiding this comment.
filter_patterns structure changes shape when no filter paths are configured
When cfg.filter_prim_paths_expr is empty, filter_prim_paths_glob is [], so filter_patterns becomes [[], [], ...] (one empty list per body) instead of the previous [] (a single flat empty list). If create_rigid_contact_view distinguishes between these two forms when processing a list-based pattern argument, sensors without any contact filter paths could behave differently than before. It's worth confirming the PhysX binding accepts a list of empty sub-lists as "no filter for each body" equivalently to a top-level empty list, or alternatively guard the construction: filter_patterns=[filter_prim_paths_glob] * len(body_path_globs) if filter_prim_paths_glob else [].
With no configured filters, replicating the empty list per sensor pattern produced a list of empty lists where the API default is a flat empty list. Both forms work, but the flat form matches the documented default and avoids relying on tolerance of empty inner lists.
AntoineRichard
left a comment
There was a problem hiding this comment.
I don't see why we make some changes to the kernels to adress the nested hierarchy. I feel like this should only be a change on the regex side? Then if we want to process flat arrays that's a different story. But I don't see why that'd be necessary.
| @@ -389,7 +397,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None): | |||
| net_forces_flat, | |||
| force_matrix_flat, | |||
| env_mask, | |||
| self._num_sensors, | |||
| self._num_envs, | |||
| self._num_filter_shapes, | |||
| self._history_length, | |||
| self.cfg.force_threshold, | |||
| @@ -411,12 +419,12 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None): | |||
|
|
|||
| # -- Pose -- | |||
| if self.cfg.track_pose: | |||
| # PhysX returns (N*B, 7) float32 -> (N*B,) transformf | |||
| # PhysX returns (B*N, 7) float32 -> (B*N,) transformf, body-major | |||
| poses_flat = self.body_physx_view.get_transforms().view(wp.transformf) | |||
| wp.launch( | |||
| split_flat_pose_to_pos_quat, | |||
| dim=(self._num_envs, self._num_sensors), | |||
| inputs=[poses_flat, env_mask, self._num_sensors], | |||
| inputs=[poses_flat, env_mask, self._num_envs], | |||
| outputs=[self._data._pos_w, self._data._quat_w], | |||
| device=self.device, | |||
| ) | |||
| @@ -436,7 +444,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None): | |||
| buffer_count, | |||
| buffer_start_indices, | |||
| env_mask, | |||
| self._num_sensors, | |||
| self._num_envs, | |||
| True, | |||
| float("nan"), | |||
| ], | |||
| @@ -458,7 +466,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None): | |||
| buffer_count, | |||
| buffer_start_indices, | |||
| env_mask, | |||
| self._num_sensors, | |||
| self._num_envs, | |||
| False, | |||
| 0.0, | |||
| ], | |||
| @@ -493,9 +501,9 @@ def _debug_vis_callback(self, event): | |||
| if self.cfg.track_pose: | |||
| frame_origins = self._data.pos_w.torch # (N, B, 3) | |||
| else: | |||
| pose = self.body_physx_view.get_transforms() # (N*B, 7) float32 | |||
| pose = self.body_physx_view.get_transforms() # (B*N, 7) float32, body-major | |||
| pose_torch = wp.to_torch(pose) | |||
| frame_origins = pose_torch.view(-1, self._num_sensors, 7)[:, :, :3] | |||
| frame_origins = pose_torch.view(self._num_sensors, -1, 7).transpose(0, 1)[:, :, :3] | |||
| # visualize | |||
| self.contact_visualizer.visualize(frame_origins.reshape(-1, 3), marker_indices=marker_indices.reshape(-1)) | |||
|
|
|||
There was a problem hiding this comment.
These changes seem unrelated?
There was a problem hiding this comment.
the main reason is that the shape/order of the array is changed if we call the API, create_rigid_contact_view, with array instead of a string. I tried to avoid it, let me confirm again.
| @@ -32,7 +35,7 @@ def split_flat_pose_to_pos_quat( | |||
| if not mask[env]: | |||
| return | |||
|
|
|||
| src_idx = env * num_bodies + sensor | |||
| src_idx = sensor * num_envs + env | |||
| dst_pos[env, sensor] = wp.transform_get_translation(src[src_idx]) | |||
| dst_quat[env, sensor] = wp.transform_get_rotation(src[src_idx]) | |||
|
|
|||
| @@ -46,7 +49,7 @@ def unpack_contact_buffer_data( | |||
| buffer_count: wp.array2d(dtype=wp.uint32), | |||
| buffer_start_indices: wp.array2d(dtype=wp.uint32), | |||
| mask: wp.array(dtype=wp.bool), | |||
| num_bodies: wp.int32, | |||
| num_envs: wp.int32, | |||
| avg: bool, | |||
| default_val: wp.float32, | |||
| dst: wp.array3d(dtype=wp.vec3f), | |||
| @@ -55,14 +58,15 @@ def unpack_contact_buffer_data( | |||
|
|
|||
| Each thread handles one (body, filter) pair for one environment. It reads | |||
| `count` contact entries starting at `start_index` and either averages or | |||
| sums them. | |||
| sums them. The flat buffer dimension is body-major (view created from one | |||
| pattern per body): ``flat_idx = body_id * num_envs + env_id``. | |||
|
|
|||
| Args: | |||
| contact_data: Flat buffer of contact data. Shape is (total_contacts,) vec3f. | |||
| buffer_count: Count of contacts per (env*body, filter). Shape is (N*B, M) uint32. | |||
| buffer_start_indices: Start indices per (env*body, filter). Shape is (N*B, M) uint32. | |||
| buffer_count: Count of contacts per (body*env, filter). Shape is (B*N, M) uint32. | |||
| buffer_start_indices: Start indices per (body*env, filter). Shape is (B*N, M) uint32. | |||
| mask: Boolean mask for which environments to update. Shape is (N,). | |||
| num_bodies: Number of bodies per environment. | |||
| num_envs: Number of environments. | |||
| avg: If True, average the data; if False, sum it. | |||
| default_val: Default value for groups with zero contacts (e.g. NaN or 0.0). | |||
| dst: Destination buffer. Shape is (N, B, M). | |||
| @@ -72,7 +76,7 @@ def unpack_contact_buffer_data( | |||
| if not mask[env]: | |||
| return | |||
|
|
|||
| flat_idx = env * num_bodies + sensor | |||
| flat_idx = sensor * num_envs + env | |||
| count = wp.int32(buffer_count[flat_idx, contact]) | |||
| start = wp.int32(buffer_start_indices[flat_idx, contact]) | |||
|
|
|||
| @@ -192,7 +196,7 @@ def update_net_forces_kernel( | |||
| net_forces_flat: wp.array(dtype=wp.vec3f), | |||
| net_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), | |||
| mask: wp.array(dtype=wp.bool), | |||
| num_sensors: int, | |||
| num_envs: int, | |||
| num_filter_shapes: int, | |||
| history_length: int, | |||
| contact_force_threshold: wp.float32, | |||
| @@ -210,13 +214,14 @@ def update_net_forces_kernel( | |||
| ): | |||
| """Update the net forces, force matrix and air/contact time for each (env, sensor) pair. | |||
|
|
|||
| Launch with dim=(num_envs, num_sensors). | |||
| Launch with dim=(num_envs, num_sensors). The flat arrays are body-major (view created | |||
| from one pattern per body): ``src_idx = sensor_id * num_envs + env_id``. | |||
|
|
|||
| Args: | |||
| net_forces_flat: Flat net forces. Shape is (num_envs*num_sensors,). | |||
| net_forces_matrix_flat: Flat force matrix. Shape is (num_envs*num_sensors, num_filter_shapes). | |||
| net_forces_flat: Flat net forces. Shape is (num_sensors*num_envs,). | |||
| net_forces_matrix_flat: Flat force matrix. Shape is (num_sensors*num_envs, num_filter_shapes). | |||
| mask: Mask array. Shape is (num_envs,). | |||
| num_sensors: Number of sensors per environment. | |||
| num_envs: Number of environments. | |||
| num_filter_shapes: Number of filter shapes. | |||
| history_length: Length of history. | |||
| contact_force_threshold: Threshold for the contact force. | |||
| @@ -243,7 +248,7 @@ def update_net_forces_kernel( | |||
| if timestamp[env] == 0.0: | |||
| return | |||
|
|
|||
| src_idx = env * num_sensors + sensor | |||
| src_idx = sensor * num_envs + env | |||
|
|
|||
| # Update net forces | |||
| net_forces_w[env, sensor] = net_forces_flat[src_idx] | |||
There was a problem hiding this comment.
I don't see why we need to change these kernels?
…ensor-nested-view # Conflicts: # source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py
…-hierarchy assets initialize (#6384) # Description The OVPhysX `ContactSensor` fails to initialize on assets whose rigid bodies are nested (child link prims authored under their parent link prim, as produced by the URDF importer in Isaac Sim 6.0 and later). The contact-binding sensor patterns were built from the first matched body's parent plus leaf names: ``` bodies found (USD side): .../Robot/pelvis .../Robot/pelvis/left_hip .../Robot/pelvis/left_hip/left_knee patterns built: .../Robot/pelvis ← exists .../Robot/left_hip ← names a prim that does not exist .../Robot/left_knee ← names a prim that does not exist ``` Nested bodies do not share a parent, so the binding bound only the first-level links and initialization raised `Failed to initialize contact binding for specified bodies` (`sensor_count` not a multiple of the resolved body count). This is the OVPhysX counterpart of #6378 (PhysX, fixes #5126); verified by reproducing the pattern construction against a nested stage: 1/3 patterns name an existing prim before the fix, 3/3 after. ## Changes - Build each sensor pattern from that body's own resolved path expression (the per-body destination expressions `resolve_matching_prims_from_source` already returns) instead of a shared parent plus leaf names. - Unlike the PhysX fix, **no data-ordering changes are needed**: the binding already received one pattern per body (pattern-major ordering documented and tested in `test_multi_body_per_sensor_indexing`), and `body_names` is stored from resolution rather than derived from view paths. The single-body pose pattern reuses `sensor_patterns[0]`. - Include the constructed patterns in the initialization error message. - Regression test: kinematic chains with URDF-importer-style nested link prims authored directly under each environment prim, standalone sensor, asserting initialization succeeds (pre-fix: deterministic `RuntimeError`), exact body resolution and order, and data shape — at 1 and 3 environments on CPU and GPU. ## Verification status - **Root cause reproduced locally before fixing** (construction level): on a nested stage, the shipped pattern construction yields 1/3 patterns naming existing prims; the fixed construction yields 3/3. - **Both failure modes derived from the binding validation arithmetic**: a loud init `RuntimeError` when the body count does not divide the bound sensor count, and a silent env-count misinference (corrupted data shapes) when it does. The regression test is parametrized to catch both (1 and 3 envs). - **The `isaaclab_ovphysx` test suite does not execute on fork PRs** (`USE_OVPHYSX_WHEELHOUSE` is gated to same-repo branches), so the regression test in this PR runs on the first `develop` CI after merge and in the nightly compatibility workflow. A maintainer can run it pre-merge by pushing the branch to the upstream repo. Related to #5126 and #6378. ## Type of change - Bug fix (non-breaking change which fixes an issue) ## Checklist - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `./isaaclab.sh --format` - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package (do **not** edit `CHANGELOG.rst` or bump `extension.toml` — CI handles that) - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there
…-hierarchy assets initialize (isaac-sim#6384) # Description The OVPhysX `ContactSensor` fails to initialize on assets whose rigid bodies are nested (child link prims authored under their parent link prim, as produced by the URDF importer in Isaac Sim 6.0 and later). The contact-binding sensor patterns were built from the first matched body's parent plus leaf names: ``` bodies found (USD side): .../Robot/pelvis .../Robot/pelvis/left_hip .../Robot/pelvis/left_hip/left_knee patterns built: .../Robot/pelvis ← exists .../Robot/left_hip ← names a prim that does not exist .../Robot/left_knee ← names a prim that does not exist ``` Nested bodies do not share a parent, so the binding bound only the first-level links and initialization raised `Failed to initialize contact binding for specified bodies` (`sensor_count` not a multiple of the resolved body count). This is the OVPhysX counterpart of isaac-sim#6378 (PhysX, fixes isaac-sim#5126); verified by reproducing the pattern construction against a nested stage: 1/3 patterns name an existing prim before the fix, 3/3 after. ## Changes - Build each sensor pattern from that body's own resolved path expression (the per-body destination expressions `resolve_matching_prims_from_source` already returns) instead of a shared parent plus leaf names. - Unlike the PhysX fix, **no data-ordering changes are needed**: the binding already received one pattern per body (pattern-major ordering documented and tested in `test_multi_body_per_sensor_indexing`), and `body_names` is stored from resolution rather than derived from view paths. The single-body pose pattern reuses `sensor_patterns[0]`. - Include the constructed patterns in the initialization error message. - Regression test: kinematic chains with URDF-importer-style nested link prims authored directly under each environment prim, standalone sensor, asserting initialization succeeds (pre-fix: deterministic `RuntimeError`), exact body resolution and order, and data shape — at 1 and 3 environments on CPU and GPU. ## Verification status - **Root cause reproduced locally before fixing** (construction level): on a nested stage, the shipped pattern construction yields 1/3 patterns naming existing prims; the fixed construction yields 3/3. - **Both failure modes derived from the binding validation arithmetic**: a loud init `RuntimeError` when the body count does not divide the bound sensor count, and a silent env-count misinference (corrupted data shapes) when it does. The regression test is parametrized to catch both (1 and 3 envs). - **The `isaaclab_ovphysx` test suite does not execute on fork PRs** (`USE_OVPHYSX_WHEELHOUSE` is gated to same-repo branches), so the regression test in this PR runs on the first `develop` CI after merge and in the nightly compatibility workflow. A maintainer can run it pre-merge by pushing the branch to the upstream repo. Related to isaac-sim#5126 and isaac-sim#6378. ## Type of change - Bug fix (non-breaking change which fixes an issue) ## Checklist - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `./isaaclab.sh --format` - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package (do **not** edit `CHANGELOG.rst` or bump `extension.toml` — CI handles that) - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there
…ssets initialize (isaac-sim#6378) # Description `ContactSensor` initialization fails on assets whose rigid bodies are nested (child link prims authored under their parent link prim, as produced by the URDF importer in Isaac Sim 6.0 and later). The PhysX views were created from a single parent-level name alternation derived from the first matched body's parent: ``` bodies found (USD side): .../Robot/pelvis .../Robot/pelvis/left_hip .../Robot/pelvis/left_hip/left_knee pattern built (view side): .../Robot/(pelvis|left_hip|left_knee) ← assumes one shared parent ``` Nested bodies do not share a parent, so the pattern matched only the first-level links and initialization raised `Failed to initialize contact reporter for specified bodies`. ## Changes The fix is two coupled changes — the second is a forced consequence of the first, not an independent choice: 1. **Create the views from one path expression per body** (`create_rigid_body_view` / `create_rigid_contact_view` take a pattern list), reusing the per-body destination expressions that `resolve_matching_prims_from_source` already returns — the same approach as the ray caster and `RigidObjectCollection`. A single pattern cannot express nested bodies at all, so the list form is the only representation the view API offers for them. The list overload also requires `filter_patterns` as one filter list per sensor pattern; the sensor replicates its uniform filter list accordingly (per-body filter semantics are unchanged, `filter_count` stays the per-body count). 2. **Adapt all raw-view consumers to the resulting body-major row order.** With a pattern list, the view enumerates matches grouped by pattern (`row = body_id * num_envs + env_id`) — the ordering is defined by the API's enumeration contract and is not selectable. The alternatives to adapting (permuting the flat arrays back to env-major on every simulation step, or expanding num_envs × num_bodies concrete paths to reconstruct env-major) add recurring hot-path or view-creation cost for no benefit, so the sensor adopts the same body-major convention `RigidObjectCollection` already documents. Every consumer of the raw flat data is updated: the three copy kernels, the `body_names` property (strides one path per body instead of slicing the first N), the debug-visualization pose fallback, and the raw-buffer indexing in the `_test_friction_forces` helper. **Data buffers and the public `data` API keep their `(num_envs, num_bodies, ...)` layout — no user-facing change.** Also: the initialization error message now includes the actual view body counts to make future pattern mismatches diagnosable from logs. ## Regression test Authors a chain of kinematic rigid bodies with URDF-importer-style nested link prims directly under each environment prim (no scene/cloner — the code under test only needs the prims on the stage), creates a standalone `ContactSensor` over them, and asserts: initialization succeeds (pre-fix: deterministic `RuntimeError`), all bodies resolve with exact `body_names` order, and each `(env, body)` cell of `data.pos_w` matches that body's authored world position — pinning the row-to-cell mapping end-to-end. Parametrized over 1 and 6 environments on CPU and GPU. Existing multi-env coverage (`test_cube_stack_contact_filtering` with 6 and 24 envs, and the task suites) exercises the ordering change on flat assets. Fixes isaac-sim#5126 ## Type of change - Bug fix (non-breaking change which fixes an issue) ## Checklist - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `./isaaclab.sh --format` - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package (do **not** edit `CHANGELOG.rst` or bump `extension.toml` — CI handles that) - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there
Description
ContactSensorinitialization fails on assets whose rigid bodies are nested (child link prims authored under their parent link prim, as produced by the URDF importer in Isaac Sim 6.0 and later). The PhysX views were created from a single parent-level name alternation derived from the first matched body's parent:Nested bodies do not share a parent, so the pattern matched only the first-level links and initialization raised
Failed to initialize contact reporter for specified bodies.Changes
The fix is two coupled changes — the second is a forced consequence of the first, not an independent choice:
create_rigid_body_view/create_rigid_contact_viewtake a pattern list), reusing the per-body destination expressions thatresolve_matching_prims_from_sourcealready returns — the same approach as the ray caster andRigidObjectCollection. A single pattern cannot express nested bodies at all, so the list form is the only representation the view API offers for them. The list overload also requiresfilter_patternsas one filter list per sensor pattern; the sensor replicates its uniform filter list accordingly (per-body filter semantics are unchanged,filter_countstays the per-body count).row = body_id * num_envs + env_id) — the ordering is defined by the API's enumeration contract and is not selectable. The alternatives to adapting (permuting the flat arrays back to env-major on every simulation step, or expanding num_envs × num_bodies concrete paths to reconstruct env-major) add recurring hot-path or view-creation cost for no benefit, so the sensor adopts the same body-major conventionRigidObjectCollectionalready documents. Every consumer of the raw flat data is updated: the three copy kernels, thebody_namesproperty (strides one path per body instead of slicing the first N), the debug-visualization pose fallback, and the raw-buffer indexing in the_test_friction_forceshelper. Data buffers and the publicdataAPI keep their(num_envs, num_bodies, ...)layout — no user-facing change.Also: the initialization error message now includes the actual view body counts to make future pattern mismatches diagnosable from logs.
Regression test
Authors a chain of kinematic rigid bodies with URDF-importer-style nested link prims directly under each environment prim (no scene/cloner — the code under test only needs the prims on the stage), creates a standalone
ContactSensorover them, and asserts: initialization succeeds (pre-fix: deterministicRuntimeError), all bodies resolve with exactbody_namesorder, and each(env, body)cell ofdata.pos_wmatches that body's authored world position — pinning the row-to-cell mapping end-to-end. Parametrized over 1 and 6 environments on CPU and GPU.Existing multi-env coverage (
test_cube_stack_contact_filteringwith 6 and 24 envs, and the task suites) exercises the ordering change on flat assets.Fixes #5126
Type of change
Checklist
pre-commitchecks with./isaaclab.sh --formatsource/<pkg>/changelog.d/for every touched package (do not editCHANGELOG.rstor bumpextension.toml— CI handles that)CONTRIBUTORS.mdor my name already exists there