Repository navigation
Adds rigid object collections for Newton - #4853
kellyguo11 merged 23 commits into
Conversation
Greptile SummaryThis PR adds a Newton physics backend implementation of Key additions and changes:
Confidence Score: 2/5
Important Files Changed
Class Diagram%%{init: {'theme': 'neutral'}}%%
classDiagram
class BaseRigidObjectCollection {
<<abstract>>
+reset()
+write_data_to_sim()
+update()
}
class RigidObjectCollection {
+cfg: RigidObjectCollectionCfg
+__backend_name__: str = "newton"
+data: RigidObjectCollectionData
+num_instances: int
+num_bodies: int
+body_names: list[str]
+root_view: ArticulationView
+instantaneous_wrench_composer: WrenchComposer
+permanent_wrench_composer: WrenchComposer
+reset(env_ids, object_ids, env_mask, object_mask)
+write_data_to_sim()
+update(dt)
+find_bodies(name_keys)
+write_body_pose_to_sim_index()
+write_body_pose_to_sim_mask()
+write_body_link_pose_to_sim_index()
+write_body_com_pose_to_sim_index()
+write_body_com_velocity_to_sim_index()
+write_body_link_velocity_to_sim_index()
+set_masses_index() / set_masses_mask()
+set_coms_index() / set_coms_mask()
+set_inertias_index() / set_inertias_mask()
-_initialize_impl()
-_create_buffers()
-_process_cfg()
-_build_combined_pattern(exprs) $
-_resolve_env_ids() / _resolve_body_ids()
-_resolve_env_mask() / _resolve_body_mask()
}
class RigidObjectCollectionData {
+__backend_name__: str = "newton"
+num_instances: int
+num_bodies: int
+body_names: list[str]
+body_link_pose_w: wp.array
+body_com_pose_w: wp.array
+body_com_vel_w: wp.array
+body_com_acc_w: wp.array
+body_com_pos_b: wp.array
+body_mass: wp.array
+body_inertia: wp.array
+projected_gravity_b: wp.array
+heading_w: wp.array
+default_body_pose: wp.array
+default_body_vel: wp.array
+update(dt)
-_create_simulation_bindings()
-_sim_bind_body_link_pose_w
-_sim_bind_body_com_vel_w
-_sim_bind_body_com_pos_b
-_sim_bind_body_mass
-_body_inertia [clone - not sim binding!]
}
class ArticulationView {
<<newton>>
+count: int
+get_root_transforms(state)
+get_root_velocities(state)
+get_attribute(name, model)
}
class NewtonManager {
<<singleton>>
+get_model()$
+get_state_0()$
+get_dt()$
+add_model_change(flags)$
+register_callback(fn, event, name)$
}
class WrenchComposer {
+active: bool
+composed_force: wp.array
+composed_torque: wp.array
+reset(env_ids)
}
BaseRigidObjectCollection <|-- RigidObjectCollection
RigidObjectCollection *-- RigidObjectCollectionData
RigidObjectCollection *-- WrenchComposer : instantaneous + permanent
RigidObjectCollection --> NewtonManager : uses
RigidObjectCollectionData --> ArticulationView : weakref proxy
RigidObjectCollectionData --> NewtonManager : reads model/state
Last reviewed commit: 955bd4e |
| # -- Body inertia: (num_envs, num_bodies, 1) mat33f → squeeze, clone to contiguous, convert to float32 | ||
| inertia_mat33 = self._root_view.get_attribute("body_inertia", model)[:, :, 0] | ||
| self._body_inertia = wp.clone(inertia_mat33).view(wp.float32).reshape((self.num_instances, self.num_bodies, 9)) |
There was a problem hiding this comment.
Inertia binding is a disconnected clone, not a sim binding
_body_inertia is created via wp.clone(), which allocates a new array copied from Newton's model memory — it is not a direct binding. This is inconsistent with how RigidObjectData handles the same attribute:
# rigid_object_data.py (_create_simulation_bindings)
_inertia_mat33 = self._root_view.get_attribute("body_inertia", SimulationManager.get_model())[:, 0]
self._sim_bind_body_inertia = _inertia_mat33.view(wp.float32).reshape(...) # direct binding, no cloneBecause _body_inertia is a clone, calling set_inertias_index or set_inertias_mask (which write to self.data._body_inertia) does not update Newton's simulation model. The comment on line ~1009 that says "writes go directly to Newton's state via the 2D binding" is therefore incorrect for the inertia case.
If wp.clone() is required here because the 2D slice [:, :, 0] yields non-contiguous memory (preventing .view()), the write methods must copy data back to the original binding (e.g., via wp.copy(inertia_mat33, self._body_inertia.view(wp.mat33f))), or Newton's model will never receive the updated inertia values.
| # container for data access | ||
| self._data = RigidObjectCollectionData(self._root_view, self.num_bodies, self.device) | ||
|
|
||
| # create buffers | ||
| self._create_buffers() | ||
| # process configuration | ||
| self._process_cfg() | ||
| # update the rigid body data | ||
| self.update(0.0) | ||
| # Let the rigid object collection data know that it is fully instantiated and ready to use. | ||
| self.data.is_primed = True |
There was a problem hiding this comment.
Missing PHYSICS_READY rebind callback after sim reset
Articulation._initialize_impl registers a PHYSICS_READY callback to re-run _data._create_simulation_bindings() when Newton recreates the model/state after sim.reset():
# From articulation.py
self._physics_ready_handle = SimulationManager.register_callback(
lambda _: self._data._create_simulation_bindings(),
PhysicsEvent.PHYSICS_READY,
name=f"articulation_rebind_{self.cfg.prim_path}",
)RigidObjectCollection._initialize_impl has no equivalent, so _sim_bind_body_link_pose_w, _sim_bind_body_com_vel_w, _sim_bind_body_com_pos_b, _sim_bind_body_external_wrench, _sim_bind_body_mass, and _body_inertia will all point to stale warp arrays after the first full sim reset — causing silent data corruption or crashes.
The CHANGELOG lists this rebind fix as already applied to both ArticulationData and RigidObjectData, so the new collection class should receive the same treatment at initialization.
| def reset( | ||
| self, | ||
| env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, | ||
| object_ids: slice | torch.Tensor | None = None, | ||
| env_mask: wp.array | None = None, | ||
| object_mask: wp.array | None = None, | ||
| ) -> None: | ||
| """Resets all internal buffers of selected environments and objects. | ||
|
|
||
| Args: | ||
| env_ids: Environment indices. If None, then all indices are used. | ||
| object_ids: Object indices. If None, then all indices are used. | ||
| env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). | ||
| object_mask: Object mask. Not used currently. | ||
| """ | ||
| # resolve all indices | ||
| if env_ids is None: | ||
| env_ids = self._ALL_ENV_INDICES | ||
| if object_ids is None: | ||
| object_ids = self._ALL_BODY_INDICES | ||
| # reset external wrench | ||
| self._instantaneous_wrench_composer.reset(env_ids) | ||
| self._permanent_wrench_composer.reset(env_ids) |
There was a problem hiding this comment.
object_ids parameter resolved but never consumed
object_ids is resolved to self._ALL_BODY_INDICES when None, but is never passed to either _instantaneous_wrench_composer.reset() or _permanent_wrench_composer.reset(). The docstring says "Object indices. If None, then all indices are used" — suggesting per-object reset should be supported, but the parameter has no effect.
Either the parameter should be removed/marked as reserved, or the wrench composers should be updated to accept a body/object subset. If intentionally unused, the docstring should say "Not used currently" (as done for object_mask).
| @staticmethod | ||
| def _build_combined_pattern(prim_path_exprs: list[str]) -> str: | ||
| """Build a single fnmatch pattern that matches all body types. | ||
|
|
||
| Compares path segments across all expressions and wildcards the segments that differ. | ||
| For example, given:: | ||
|
|
||
| ["/World/Env_*/DexCube/Cube", "/World/Env_*/DexSphere/Sphere"] | ||
|
|
||
| produces ``"/World/Env_*/*/*"``. | ||
|
|
||
| Args: | ||
| prim_path_exprs: List of prim path expressions, one per body type. | ||
|
|
||
| Returns: | ||
| A single fnmatch pattern string. | ||
|
|
||
| Raises: | ||
| ValueError: If the expressions have different numbers of path segments. | ||
| """ | ||
| if len(prim_path_exprs) == 1: | ||
| return prim_path_exprs[0] | ||
|
|
||
| split_paths = [p.split("/") for p in prim_path_exprs] | ||
| lengths = {len(s) for s in split_paths} | ||
| if len(lengths) != 1: | ||
| raise ValueError( | ||
| f"Cannot build combined pattern: path expressions have different segment counts: {prim_path_exprs}" | ||
| ) | ||
|
|
||
| combined_segments = [] | ||
| for segments in zip(*split_paths): | ||
| unique = set(segments) | ||
| if len(unique) == 1: | ||
| combined_segments.append(segments[0]) | ||
| else: | ||
| combined_segments.append("*") | ||
| return "/".join(combined_segments) |
There was a problem hiding this comment.
_build_combined_pattern could produce overly broad glob patterns
The method wildcards every path segment where the inputs differ, which can easily create patterns that match unintended USD prims. For example:
/World/Env_*/ObjectA/Bodyand/World/Env_*/ObjectB/Lid
→ combined:/World/Env_*/*/*
This would match any prim two levels below /World/Env_*/, not just the two intended rigid bodies. If the USD stage contains other prims at that depth (e.g., geometry, lights, sensors), ArticulationView would pick them up, silently breaking the num_bodies count and index mapping.
Consider adding a post-construction check that self._root_view.count == expected_total_count (i.e., num_envs * num_bodies) to detect over-matching early, or log a warning when the combined pattern contains segments that were wildcarded.
Signed-off-by: Kelly Guo <[email protected]>
Description
Adds rigid object collections for Newton. Builds ontop of #4818
Type of change
Checklist
pre-commitchecks with./isaaclab.sh --formatconfig/extension.tomlfileCONTRIBUTORS.mdor my name already exists there