From 256d3227e1337b3fb5dbe92dd0eba02044d2d06d Mon Sep 17 00:00:00 2001 From: AntoineRichard Date: Wed, 2 Dec 2026 18:02:23 +0100 Subject: [PATCH] Add native actuator registration and lifecycle hooks --- docs/source/api/lab/isaaclab.actuators.rst | 11 ++ docs/source/api/lab/isaaclab.sim.schemas.rst | 17 ++ docs/source/concepts/actuators.rst | 82 +++++++- .../native-actuator-registration.added.rst | 2 + .../native-actuator-registration.minor | 0 .../isaaclab/actuators/actuator_collection.py | 20 +- .../isaaclab/actuators/actuator_control.py | 3 + .../isaaclab/actuators/newton/__init__.py | 4 + .../isaaclab/actuators/newton/adapter.py | 36 +++- .../isaaclab/actuators/newton/hooks.py | 166 ++++++++++++++++ .../actuators/newton/physx_runtime.py | 28 ++- .../isaaclab/sim/schemas/__init__.pyi | 8 + .../isaaclab/sim/schemas/schemas_actuators.py | 116 +++++++++-- .../actuators/test_actuator_collection.py | 58 ++++++ .../test/actuators/test_newton_adapter.py | 184 ++++++++++++++++++ .../native-actuator-registration.added.rst | 1 + .../assets/articulation/actuator_control.py | 5 + .../native-actuator-registration.added.rst | 2 + .../assets/articulation/actuator_control.py | 24 +++ .../isaaclab_newton/physics/newton_backend.py | 3 + .../test/physics/test_newton_manager.py | 81 ++++++++ .../native-actuator-registration.added.rst | 1 + .../assets/articulation/actuator_control.py | 6 + 23 files changed, 825 insertions(+), 33 deletions(-) create mode 100644 source/isaaclab/changelog.d/native-actuator-registration.added.rst create mode 100644 source/isaaclab/changelog.d/native-actuator-registration.minor create mode 100644 source/isaaclab/isaaclab/actuators/newton/hooks.py create mode 100644 source/isaaclab_isaacsim/changelog.d/native-actuator-registration.added.rst create mode 100644 source/isaaclab_newton/changelog.d/native-actuator-registration.added.rst create mode 100644 source/isaaclab_ov/changelog.d/native-actuator-registration.added.rst diff --git a/docs/source/api/lab/isaaclab.actuators.rst b/docs/source/api/lab/isaaclab.actuators.rst index af7887c4b456..93e1bd657d6d 100644 --- a/docs/source/api/lab/isaaclab.actuators.rst +++ b/docs/source/api/lab/isaaclab.actuators.rst @@ -212,3 +212,14 @@ Newton Actuator Access .. autofunction:: isaaclab.actuators.newton.read_group_parameter .. autofunction:: isaaclab.actuators.newton.write_group_parameter + +.. autoclass:: isaaclab.actuators.newton.NativeActuatorHooks + :members: + +.. autoclass:: isaaclab.actuators.newton.NativeActuatorContext + :members: + :exclude-members: __init__ + +.. autoclass:: isaaclab.actuators.newton.NativeActuatorBinding + :members: + :exclude-members: __init__ diff --git a/docs/source/api/lab/isaaclab.sim.schemas.rst b/docs/source/api/lab/isaaclab.sim.schemas.rst index 6c9afd1292ad..0c80c41996ef 100644 --- a/docs/source/api/lab/isaaclab.sim.schemas.rst +++ b/docs/source/api/lab/isaaclab.sim.schemas.rst @@ -96,6 +96,23 @@ isaaclab.sim.schemas define_deformable_curve_properties modify_deformable_body_properties +Native Actuator Registration +---------------------------- + +.. autofunction:: register_native_actuator + +.. autoclass:: ActuatorField + :members: + :exclude-members: __init__ + +.. autoclass:: ActuatorLayout + :members: + :exclude-members: __init__ + +.. autoclass:: NativeActuatorAuthoringContext + :members: + :exclude-members: __init__ + Schema Fragments ---------------- diff --git a/docs/source/concepts/actuators.rst b/docs/source/concepts/actuators.rst index 20e0c4db14fd..5789a601839f 100644 --- a/docs/source/concepts/actuators.rst +++ b/docs/source/concepts/actuators.rst @@ -817,7 +817,8 @@ produces no torque. A warning names the replaced joints. The With the default ``use_newton_actuators=True``, every explicit actuator config must be supported. An unsupported config raises an error before native authoring. Disable - ``use_newton_actuators`` to use the Isaac Lab execution path, or select a supported config. + ``use_newton_actuators`` to use the Isaac Lab execution path, select a supported config, or + register a custom implementation as described below. .. note:: @@ -836,6 +837,85 @@ produces no torque. A warning names the replaced joints. The starting buffer so its history advances across graph replays. +.. _actuators-native-custom: + +Custom native actuators +^^^^^^^^^^^^^^^^^^^^^^^ + +Use :func:`~isaaclab.sim.schemas.register_native_actuator` to declare how a custom Lab config +maps to a Newton implementation. Register before spawning assets, on every backend that uses +the config. Newton itself is unchanged: register the drive or component with its existing +``newton.actuators.register_actuator_component`` API and arrange any USD schema plugin discovery +before USD initializes its schema registry. + +For example, given project-owned ``MyActuator``, ``MyActuatorCfg`` and ``MyNewtonDrive`` classes: + +.. code-block:: python + + from newton.actuators import ComponentKind, register_actuator_component + + from isaaclab.actuators.newton import NativeActuatorHooks + from isaaclab.sim.schemas import ActuatorField, ActuatorLayout, register_native_actuator + + class MyHooks(NativeActuatorHooks): + def prepare(self, context): + # A custom drive may need an environment stride before it allocates state. + for binding in context.bindings: + drive = binding.actuator.drive + drive.env_dof_stride = len(binding.actuator.indices) // context.articulation.num_instances + + register_actuator_component("MyDriveAPI", MyNewtonDrive, ComponentKind.DRIVE) + register_native_actuator( + MyActuatorCfg, + ActuatorLayout( + MyActuator, + "MyDriveAPI", + ( + ActuatorField("stiffness", "MyDriveAPI", "newton:kp"), + ActuatorField("current_limit", "MyDriveAPI", "newton:currentLimit", required=True), + ), + ), + hooks_type=MyHooks, + ) + +``MyActuatorCfg.class_type`` must resolve to exactly ``MyActuator``. Config subclasses inherit the +closest registration; changing ``class_type`` requires a matching registration. Native execution +runs ``MyNewtonDrive``, not ``MyActuator.compute()``. Duplicate config registrations raise an error. +Registration does not make a drive's solver-specific features portable to other backends. + +A layout declares the drive and component schemas that its config models. Matching asset prims +using registered schemas are retained, and fields left unset keep their asset values. Components +outside the selected layout are removed according to the usual override rules. Use a field's +``source`` callback for non-scalar values, and ``default`` or ``required`` for components the +config adds to a prim. + +An optional ``author(context)`` callback runs after regular USD authoring for each group, before +cloning and model import. Its :class:`~isaaclab.sim.schemas.NativeActuatorAuthoringContext` +contains the config, group name, stage, articulation path, and joint/actuator prim dictionaries +keyed by joint name. Use it for additional joint attributes or other USD data outside the actuator prim. + +Register a :class:`~isaaclab.actuators.newton.NativeActuatorHooks` subclass for Lab-specific runtime work. +Each group in each articulation gets a separate no-argument instance, with callbacks in this order: + +* ``prepare(context)``: parsed actuators exist, before component-state allocation. +* ``finalize(context)``: group properties and adapter buffers are bound; sample startup parameters here. +* ``solver_init(context)``: component states and solver resources are ready, before graph capture. +* ``reset(context, env_ids, env_mask)``: after normal component-state reset; a mask takes precedence. + +On Newton, state allocation waits until all articulations prepare, at solver initialization. +``finalize`` must not assume those states exist yet. On PhysX and OVPhysX, ``solver_init`` runs +immediately after finalization. The :class:`~isaaclab.actuators.newton.NativeActuatorContext` +provides the public articulation, collection, backend name, public joint indices, owned actuator +bindings and native control object. Its ``adapter`` becomes available at finalization; ``model`` +and ``solver`` are Newton-only resources, with ``solver`` available at solver initialization. + +Newton can merge groups or articulations into one actuator. A binding's ``slots`` are positions +in that actuator's arrays across all environments that belong to this group. Restrict writes to +those slots; shared settings need explicit agreement and idempotent initialization. Prefer Newton +component state/reset APIs for ordinary drive state. Hooks are recreated on model rebuild and +must not register callbacks that outlive the backend. There are no new per-step Python callbacks. + + .. _actuators-bam: BAM servo model diff --git a/source/isaaclab/changelog.d/native-actuator-registration.added.rst b/source/isaaclab/changelog.d/native-actuator-registration.added.rst new file mode 100644 index 000000000000..75de05625786 --- /dev/null +++ b/source/isaaclab/changelog.d/native-actuator-registration.added.rst @@ -0,0 +1,2 @@ +* Added public native actuator layout registration, USD authoring callbacks and per-group runtime hooks + so external actuator implementations can use Newton execution without modifying Isaac Lab. diff --git a/source/isaaclab/changelog.d/native-actuator-registration.minor b/source/isaaclab/changelog.d/native-actuator-registration.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/actuators/actuator_collection.py b/source/isaaclab/isaaclab/actuators/actuator_collection.py index e2810985dcad..52fee4b69180 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_collection.py +++ b/source/isaaclab/isaaclab/actuators/actuator_collection.py @@ -85,6 +85,14 @@ def __init__( resolved_cfgs = {name: clone(cfg) for name, cfg in actuator_cfgs.items()} resolved_group_joints = self._resolve_group_joints(resolved_cfgs) + for name, (joint_ids, joint_names) in resolved_group_joints.items(): + self._group_joint_names[name] = joint_names + if len(joint_names) == self.num_joints: + self._group_joint_indices[name] = slice(None) + elif isinstance(joint_ids, ProxyArray): + self._group_joint_indices[name] = joint_ids.torch + else: + self._group_joint_indices[name] = torch.tensor(joint_ids, device=self.device, dtype=torch.int32) self._allocate_buffers() self._target_command = ActuatorTargetCommand(self) self._output_command = ActuatorOutputCommand(self) @@ -108,6 +116,7 @@ def __init__( self._groups[actuator_name] = self._resolve_newton_group_actuators(actuator_name) self._validate_coverage() self._build_execution_plan() + self._control.finalize_native_actuator_hooks() if self._debug_value_resolution: self._print_value_resolution_table() if not self._control.native_actuator_path_active: @@ -320,15 +329,8 @@ def _build_groups( """ construction_records: list[tuple[dict[str, torch.Tensor], torch.Tensor | slice, bool, bool]] = [] for actuator_name, actuator_cfg in actuator_cfgs.items(): - joint_ids, joint_names = resolved_group_joints[actuator_name] - if len(joint_names) == self.num_joints: - actuator_joint_ids: slice | torch.Tensor = slice(None) - elif isinstance(joint_ids, ProxyArray): - actuator_joint_ids = joint_ids.torch - else: - actuator_joint_ids = torch.tensor(joint_ids, device=self.device, dtype=torch.int32) - self._group_joint_names[actuator_name] = joint_names - self._group_joint_indices[actuator_name] = actuator_joint_ids + _, joint_names = resolved_group_joints[actuator_name] + actuator_joint_ids = self._group_joint_indices[actuator_name] joint_defaults = self._control.get_default_joint_properties(actuator_joint_ids) implicit = _is_implicit_actuator_cfg(actuator_cfg) diff --git a/source/isaaclab/isaaclab/actuators/actuator_control.py b/source/isaaclab/isaaclab/actuators/actuator_control.py index 87034466a118..255a1ec1eb5f 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_control.py +++ b/source/isaaclab/isaaclab/actuators/actuator_control.py @@ -286,6 +286,9 @@ def finalize_native_actuators(self, collection: ActuatorCollection) -> NewtonAct """ return None + def finalize_native_actuator_hooks(self) -> None: + """Run extension startup hooks after collection membership and parameter access are ready.""" + def compute_native_actuators(self, collection: ActuatorCollection, dt: float) -> bool: """Compute backend-native actuator outputs. diff --git a/source/isaaclab/isaaclab/actuators/newton/__init__.py b/source/isaaclab/isaaclab/actuators/newton/__init__.py index 01560a03afd7..024d654cdf12 100644 --- a/source/isaaclab/isaaclab/actuators/newton/__init__.py +++ b/source/isaaclab/isaaclab/actuators/newton/__init__.py @@ -31,9 +31,13 @@ from .adapter import NewtonActuatorAdapter, read_group_parameter, write_group_parameter from .kernels import build_implicit_dof_mask +from .hooks import NativeActuatorBinding, NativeActuatorContext, NativeActuatorHooks from .physx_wrapper import PhysxActuatorWrapper __all__ = [ + "NativeActuatorBinding", + "NativeActuatorContext", + "NativeActuatorHooks", "NewtonActuatorAdapter", "PhysxActuatorWrapper", "build_implicit_dof_mask", diff --git a/source/isaaclab/isaaclab/actuators/newton/adapter.py b/source/isaaclab/isaaclab/actuators/newton/adapter.py index 4904d4c7780c..331e12441d19 100644 --- a/source/isaaclab/isaaclab/actuators/newton/adapter.py +++ b/source/isaaclab/isaaclab/actuators/newton/adapter.py @@ -79,6 +79,8 @@ def __init__( num_joints: int, dof_offset: int, device: str, + *, + defer_state_initialization: bool = False, ): self.actuators = actuators self.num_joints = num_joints @@ -104,13 +106,10 @@ def __init__( else: self.joint_indices = torch.tensor(sorted(managed), dtype=torch.int32, device=device) - self._states_a = [act.state() for act in actuators] - self._states_b = [act.state() for act in actuators] - # per-DOF reset masks of the stateful actuators, rewritten by every partial reset so a reset does not allocate - self._reset_dof_masks = [ - None if state is None else wp.zeros(act.indices.shape[0], dtype=wp.bool, device=device) - for act, state in zip(actuators, self._states_a) - ] + self._states_initialized = False + self._states_a = [] + self._states_b = [] + self._reset_dof_masks = [] # Pre-clamp computed effort buffer. Each Newton actuator scatter-adds # its raw drive output to ``sim_control.joint_computed_f`` when @@ -126,6 +125,25 @@ def __init__( self.computed_effort_2d = self._computed_effort.reshape((num_envs, num_joints)) for act in actuators: act.control_computed_output_attr = "joint_computed_f" + if not defer_state_initialization: + self.initialize_states() + + def initialize_states(self) -> None: + """Allocate component states once, after all registered preparation hooks. + + Construction is eager by default. Lab's Newton backend defers this until solver + initialization because its adapter is shared by all articulations. Call before step/reset + when constructing with ``defer_state_initialization=True``. + """ + if self._states_initialized: + return + self._states_a = [act.state() for act in self.actuators] + self._states_b = [act.state() for act in self.actuators] + self._reset_dof_masks = [ + None if state is None else wp.zeros(act.indices.shape[0], dtype=wp.bool, device=self._device) + for act, state in zip(self.actuators, self._states_a) + ] + self._states_initialized = True def finalize(self, sim_control: Any) -> None: """Bind the pre-clamp computed-effort buffer onto ``sim_control``. @@ -156,6 +174,8 @@ def step(self, sim_state: Any, sim_control: Any, dt: float, *, swap_state: bool of an odd-length graph to copy the output back into the input buffers instead, keeping their addresses stable across replays. """ + if not self._states_initialized: + raise RuntimeError("Native actuator states must be initialized before stepping.") # Zero before scatter-add (actuators accumulate into this buffer). self._computed_effort.zero_() for act in self.actuators: @@ -197,6 +217,8 @@ def reset( etc.). We therefore build a per-actuator per-DOF mask from the env mask before delegating to each state. """ + if not self._states_initialized: + raise RuntimeError("Native actuator states must be initialized before reset.") if env_mask is not None: self._reset_states(env_mask) return diff --git a/source/isaaclab/isaaclab/actuators/newton/hooks.py b/source/isaaclab/isaaclab/actuators/newton/hooks.py new file mode 100644 index 000000000000..d0d3a7c024d7 --- /dev/null +++ b/source/isaaclab/isaaclab/actuators/newton/hooks.py @@ -0,0 +1,166 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Lab lifecycle extensions for registered Newton actuator implementations.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import numpy as np + +if TYPE_CHECKING: + import warp as wp + from newton.actuators import Actuator + + from ..actuator_base_cfg import ActuatorBaseCfg + from ..actuator_collection import ActuatorCollection + from .adapter import NewtonActuatorAdapter + + +@dataclass(frozen=True) +class NativeActuatorBinding: + """A group's ownership within a possibly shared Newton actuator.""" + + actuator: Actuator + slots: tuple[int, ...] + """Positions in the actuator's arrays belonging to this group, across all environments. + + Several groups or articulations can share an actuator. Modify only these slots unless + deliberately configuring shared state; validate shared settings and initialize them idempotently. + """ + + +@dataclass +class NativeActuatorContext: + """One runtime group's resources, valid for the lifetime of its articulation. + + Preparation provides parsed actuators before component-state allocation. Finalization adds + the adapter. Solver initialization adds the Newton solver; host backends have no Newton + model or solver. Resources are recreated when the simulation model is rebuilt. + """ + + cfg: ActuatorBaseCfg + group_name: str + articulation: Any + collection: ActuatorCollection + backend: str + """``"newton"``, ``"physx"`` or ``"ov"``.""" + joint_names: tuple[str, ...] + joint_indices: tuple[int, ...] + """Joint indices in the articulation's public order.""" + bindings: tuple[NativeActuatorBinding, ...] + control: Any + """Newton Control or the host PhysxActuatorWrapper.""" + model: Any = None + adapter: NewtonActuatorAdapter | None = None + solver: Any = None + + +class NativeActuatorHooks: + """Optional Lab-specific callbacks; register the class, not a shared instance. + + The class must accept no constructor arguments. Each articulation group gets its own instance. + Use Newton component state/reset for ordinary drive state. These callbacks supplement that + lifecycle; they never execute on each physics step. Do not retain resources across model rebuilds + or install callbacks with lifetimes beyond the owning simulation backend. + """ + + def prepare(self, context: NativeActuatorContext) -> None: + """Configure parsed actuators before their component states are allocated.""" + + def finalize(self, context: NativeActuatorContext) -> None: + """Bind Lab resources or sample startup parameters after the adapter is bound. + + On Newton, component states are allocated later, before solver-init callbacks. + """ + + def solver_init(self, context: NativeActuatorContext) -> None: + """Bind solver-dependent resources after initialization, before graph capture. + + On host backends this runs after finalization with model/solver set to None; + use the public articulation interface for backend-specific operations. + """ + + def reset(self, context: NativeActuatorContext, env_ids: Sequence[int] | slice, env_mask: wp.array | None) -> None: + """Reset extra Lab state after component reset; env_mask takes precedence over env_ids.""" + + +class _NativeActuatorLifecycle: + """Own per-group hook instances and dispatch setup/reset outside the physics hot path.""" + + def __init__( + self, + articulation: Any, + collection: ActuatorCollection, + actuator_cfgs: dict[str, ActuatorBaseCfg], + actuators: list[Actuator], + *, + backend: str, + control: Any, + model: Any = None, + dof_offset: int = 0, + joint_user_to_backend: tuple[int, ...] | None = None, + ): + from ...sim.schemas.schemas_actuators import _native_actuator_registration # noqa: PLC0415 + from ..actuator_base_cfg import _is_implicit_actuator_cfg # noqa: PLC0415 + + self._groups: list[tuple[NativeActuatorHooks, NativeActuatorContext]] = [] + stride = model.joint_dof_count // articulation.num_instances if model is not None else articulation.num_joints + for name, cfg in actuator_cfgs.items(): + registration = _native_actuator_registration(cfg) + if _is_implicit_actuator_cfg(cfg) or registration is None or registration.hooks_type is None: + continue + indices = collection._group_joint_indices[name] + indices = ( + tuple(range(articulation.num_joints)[indices]) + if isinstance(indices, slice) + else tuple(indices.tolist()) + ) + columns = [ + dof_offset + (joint_user_to_backend[i] if joint_user_to_backend is not None else i) for i in indices + ] + bindings = [] + for actuator in actuators: + slots = tuple(np.flatnonzero(np.isin(actuator.indices.numpy() % stride, columns)).tolist()) + if slots: + bindings.append(NativeActuatorBinding(actuator, slots)) + context = NativeActuatorContext( + cfg, + name, + articulation, + collection, + backend, + tuple(collection._group_joint_names[name]), + indices, + tuple(bindings), + control, + model, + ) + self._groups.append((registration.hooks_type(), context)) + self._dispatch("prepare") + + def _dispatch(self, phase: str, *args) -> None: + for hooks, context in self._groups: + try: + getattr(hooks, phase)(context, *args) + except Exception as error: + error.add_note(f"Native actuator group '{context.group_name}', {phase} hook ({context.backend}).") + raise + + def finalize(self, adapter: NewtonActuatorAdapter) -> None: + for _, context in self._groups: + context.adapter = adapter + self._dispatch("finalize") + + def solver_init(self, solver: Any = None) -> None: + for _, context in self._groups: + context.solver = solver + self._dispatch("solver_init") + + def reset(self, env_ids: Sequence[int] | slice, env_mask: wp.array | None) -> None: + self._dispatch("reset", env_ids, env_mask) diff --git a/source/isaaclab/isaaclab/actuators/newton/physx_runtime.py b/source/isaaclab/isaaclab/actuators/newton/physx_runtime.py index e8e97da50878..618ff7bd7947 100644 --- a/source/isaaclab/isaaclab/actuators/newton/physx_runtime.py +++ b/source/isaaclab/isaaclab/actuators/newton/physx_runtime.py @@ -13,11 +13,13 @@ import warp as wp -from .adapter import NewtonActuatorAdapter, build_implicit_dof_mask +from .adapter import NewtonActuatorAdapter, _create_actuators_from_usd, build_implicit_dof_mask +from .hooks import _NativeActuatorLifecycle from .physx_wrapper import PhysxActuatorWrapper if TYPE_CHECKING: from .. import ActuatorCollection + from ..actuator_base_cfg import ActuatorBaseCfg class PhysxActuatorRuntime: @@ -39,6 +41,7 @@ def __init__(self, articulation: Any, *, logger: logging.Logger): self.binding: NewtonActuatorAdapter.ArticulationBinding | None = None self.native_actuator_graphs: tuple[wp.Graph, wp.Graph] | None = None self._native_actuator_graph_index = 0 + self._native_hooks: _NativeActuatorLifecycle | None = None def prepare( self, @@ -47,6 +50,8 @@ def prepare( stage: Any, articulation_prim_path: str | None, adapt_usd_actuators: bool = True, + actuator_cfgs: dict[str, ActuatorBaseCfg] | None = None, + backend: str = "physx", ) -> None: """Create and bind the adapter and its pointer-stable host wrapper. @@ -57,6 +62,8 @@ def prepare( adapt_usd_actuators: Whether to adapt authored ``NewtonActuator`` prims. Implicit-only articulations author none: the solver applies their drives, and the wrapper alone backs the telemetry fast path. + actuator_cfgs: Optional registered groups whose Lab hooks participate in the lifecycle. + backend: Host backend name supplied to hooks: ``"physx"`` or ``"ov"``. """ articulation = self._articulation self.wrapper = PhysxActuatorWrapper.create( @@ -73,14 +80,21 @@ def prepare( self.wrapper.joint_act = collection.target_command.effort.warp.reshape(-1) if not adapt_usd_actuators: return - self.adapter = NewtonActuatorAdapter.from_usd( + actuators = _create_actuators_from_usd( stage=stage, joint_names=articulation.joint_names, num_envs=articulation.num_instances, - num_joints=articulation.num_joints, + num_total_joints=articulation.num_joints, device=articulation.device, articulation_prim_path=articulation_prim_path, ) + if actuator_cfgs: + self._native_hooks = _NativeActuatorLifecycle( + articulation, collection, actuator_cfgs, actuators, backend=backend, control=self.wrapper + ) + self.adapter = NewtonActuatorAdapter( + actuators, articulation.num_instances, articulation.num_joints, 0, articulation.device + ) self.adapter.finalize(self.wrapper) def finalize(self, collection: ActuatorCollection) -> None: @@ -106,6 +120,12 @@ def finalize(self, collection: ActuatorCollection) -> None: articulation._implicit_dof_mask_owner = self.binding.implicit_dof_mask_owner articulation._data._sim_bind_joint_computed_effort = self.binding.computed_effort_view + def finalize_hooks(self) -> None: + """Run startup hooks once the collection has bound its native groups and parameter selection.""" + if self._native_hooks is not None: + self._native_hooks.finalize(self.adapter) + self._native_hooks.solver_init() + def compute(self, collection: ActuatorCollection, dt: float) -> None: """Compute native efforts and synchronize telemetry for one physics step.""" if self.adapter is not None: @@ -135,6 +155,8 @@ def reset(self, env_ids: Sequence[int] | slice, env_mask: wp.array | None = None """ if self.adapter is not None: self.adapter.reset(env_ids, env_mask) + if self._native_hooks is not None: + self._native_hooks.reset(env_ids, env_mask) def _run_native_actuator_kernels(self, collection: ActuatorCollection, dt: float) -> None: from . import kernels as actuator_kernels # noqa: PLC0415 diff --git a/source/isaaclab/isaaclab/sim/schemas/__init__.pyi b/source/isaaclab/isaaclab/sim/schemas/__init__.pyi index c2464c956ea4..74b4b77e523f 100644 --- a/source/isaaclab/isaaclab/sim/schemas/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/schemas/__init__.pyi @@ -4,6 +4,10 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "ActuatorField", + "ActuatorLayout", + "NativeActuatorAuthoringContext", + "register_native_actuator", "MESH_APPROXIMATION_TOKENS", "PHYSX_MESH_COLLISION_CFGS", "USD_MESH_COLLISION_CFGS", @@ -111,6 +115,10 @@ from .schemas import ( modify_spatial_tendon_properties, ) from .schemas_actuators import ( + ActuatorField, + ActuatorLayout, + NativeActuatorAuthoringContext, + register_native_actuator, define_actuator_properties, ) from .schemas_cfg import ( diff --git a/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py b/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py index 35ef1c3df9e1..7f4278211d15 100644 --- a/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py +++ b/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py @@ -27,7 +27,7 @@ from collections.abc import Callable from dataclasses import dataclass from operator import attrgetter -from typing import Any +from typing import TYPE_CHECKING, Any import torch @@ -60,6 +60,9 @@ from ..utils.stage import get_current_stage from .schemas import drive_instance_name +if TYPE_CHECKING: + from ...actuators.newton.hooks import NativeActuatorHooks + logger = logging.getLogger(__name__) _JOINT_TYPES = frozenset({"PhysicsRevoluteJoint", "PhysicsPrismaticJoint"}) @@ -305,6 +308,77 @@ class ActuatorLayout: """Attributes the config type can author; their schemas and the drive are all it keeps.""" +@dataclass(frozen=True) +class NativeActuatorAuthoringContext: + """One group's USD authoring resources, available before cloning and model import.""" + + cfg: ActuatorBaseCfg + group_name: str + stage: Usd.Stage + articulation_prim_path: str + joints: dict[str, Usd.Prim] + """Selected joints keyed by name.""" + actuator_prims: dict[str, Usd.Prim] + """Authored actuator prim for each selected joint.""" + + +@dataclass(frozen=True) +class _NativeActuatorRegistration: + layout: ActuatorLayout + hooks_type: type[NativeActuatorHooks] | None = None + author: Callable[[NativeActuatorAuthoringContext], None] | None = None + + +def register_native_actuator( + cfg_type: type[ActuatorBaseCfg], + layout: ActuatorLayout, + *, + hooks_type: type[NativeActuatorHooks] | None = None, + author: Callable[[NativeActuatorAuthoringContext], None] | None = None, +) -> None: + """Register a custom config's Newton authoring layout and optional lifecycle hooks. + + Call before spawning assets. Newton component registration and USD schema discovery are + separate prerequisites. Native execution runs the Newton implementation, not the Lab + actuator class's ``compute`` method. Config subclasses inherit this registration, but + their ``class_type`` must still resolve to exactly :attr:`ActuatorLayout.actuator_class`. + + Args: + cfg_type: Config type to register; existing registrations cannot be replaced. + layout: Newton drive and component attributes authored by the config. + hooks_type: Optional no-argument hook class, instantiated separately for each runtime group. + author: Optional callback after authoring each group's actuator prims, before model import. + + Raises: + TypeError: If a config, layout, hook type or callback is invalid. + ValueError: If the config is already registered or the layout contains invalid fields. + """ + global _DRIVE_APIS, _COMPONENT_APIS, _KNOWN_ACTUATOR_APIS + if not isinstance(cfg_type, type) or not issubclass(cfg_type, ActuatorBaseCfg): + raise TypeError("cfg_type must derive from ActuatorBaseCfg.") + if cfg_type in _ACTUATOR_REGISTRATIONS: + raise ValueError(f"{cfg_type.__name__} is already registered for native actuator execution.") + if not isinstance(layout, ActuatorLayout): + raise TypeError("layout must be an ActuatorLayout.") + if layout.actuator_class is not None: + _resolve_actuator_class(layout.actuator_class) + if not layout.drive or any(not field.schema or not field.name or not field.attr for field in layout.fields): + raise ValueError("Actuator layout drive, field names, schemas and attributes must be nonempty.") + if len({field.attr for field in layout.fields}) != len(layout.fields): + raise ValueError("Actuator layout fields must have unique USD attribute names.") + if hooks_type is not None: + from ...actuators.newton.hooks import NativeActuatorHooks # noqa: PLC0415 + + if not isinstance(hooks_type, type) or not issubclass(hooks_type, NativeActuatorHooks): + raise TypeError("hooks_type must derive from NativeActuatorHooks.") + if author is not None and not callable(author): + raise TypeError("author must be callable.") + _ACTUATOR_REGISTRATIONS[cfg_type] = _NativeActuatorRegistration(layout, hooks_type, author) + _DRIVE_APIS = _DRIVE_APIS | {layout.drive} + _COMPONENT_APIS = _COMPONENT_APIS | {layout.drive, *(field.schema for field in layout.fields)} + _KNOWN_ACTUATOR_APIS = _KNOWN_ACTUATOR_APIS | _COMPONENT_APIS + + def _author_group( stage: Usd.Stage, articulation_prim_path: str, @@ -318,7 +392,9 @@ def _author_group( A value the config sets is authored. An unset value keeps the prim's opinion when the prim keeps that value's schema; otherwise it takes the field's default. """ - layout = _actuator_layout(cfg) + registration = _native_actuator_registration(cfg) + layout = registration.layout + authored = {} configured = {field.attr: field.configured(cfg, list(joints)) for field in layout.fields} allowed = {layout.drive, *(field.schema for field in layout.fields)} for joint_name, joint_prim in joints.items(): @@ -370,8 +446,8 @@ def _author_group( if remove: removed_attrs = { field.attr - for known_layout in _ACTUATOR_LAYOUTS.values() - for field in known_layout.fields + for known_registration in _ACTUATOR_REGISTRATIONS.values() + for field in known_registration.layout.fields if field.schema in remove } # Shared attributes, such as BAM's maxEffort, still belong to a retained component. @@ -391,6 +467,11 @@ def _author_group( if layout.drive == BAM_DRIVE_API: # Allocate the joint friction constraint; BAM overwrites this seed before each solve. joint_prim.CreateAttribute("newton:friction", _FLOAT).Set(1.0) + authored[joint_name] = prim + if registration.author is not None: + registration.author( + NativeActuatorAuthoringContext(cfg, group_name, stage, articulation_prim_path, joints, authored) + ) def _override_target(prims: list[Usd.Prim], drive: str) -> tuple[Usd.Prim | None, str | None]: @@ -588,21 +669,30 @@ def _bam_effort_limits(cfg: BamActuatorCfg, joint_names: list[str]) -> dict[str, ), ) -_ACTUATOR_LAYOUTS: dict[type, ActuatorLayout] = { - IdealPDActuatorCfg: ActuatorLayout(IdealPDActuator, _PD_API, (*_PD_GAINS, _MAX_EFFORT)), - DelayedPDActuatorCfg: ActuatorLayout(DelayedPDActuator, _PD_API, (*_PD_GAINS, _MAX_EFFORT, _DELAY)), - RemotizedPDActuatorCfg: ActuatorLayout(RemotizedPDActuator, _PD_API, (*_PD_GAINS, *_POSITION_BASED, _DELAY)), - DCMotorCfg: ActuatorLayout(DCMotor, _PD_API, (*_PD_GAINS, *_DC_MOTOR)), - ActuatorNetMLPCfg: ActuatorLayout(ActuatorNetMLP, _NEURAL_API, (_NEURAL_MODEL, *_DC_MOTOR)), - ActuatorNetLSTMCfg: ActuatorLayout(ActuatorNetLSTM, _NEURAL_API, (_NEURAL_MODEL, *_DC_MOTOR)), - BamActuatorCfg: ActuatorLayout(None, BAM_DRIVE_API, _BAM_FIELDS), +_ACTUATOR_REGISTRATIONS: dict[type, _NativeActuatorRegistration] = { + cfg_type: _NativeActuatorRegistration(layout) + for cfg_type, layout in { + IdealPDActuatorCfg: ActuatorLayout(IdealPDActuator, _PD_API, (*_PD_GAINS, _MAX_EFFORT)), + DelayedPDActuatorCfg: ActuatorLayout(DelayedPDActuator, _PD_API, (*_PD_GAINS, _MAX_EFFORT, _DELAY)), + RemotizedPDActuatorCfg: ActuatorLayout(RemotizedPDActuator, _PD_API, (*_PD_GAINS, *_POSITION_BASED, _DELAY)), + DCMotorCfg: ActuatorLayout(DCMotor, _PD_API, (*_PD_GAINS, *_DC_MOTOR)), + ActuatorNetMLPCfg: ActuatorLayout(ActuatorNetMLP, _NEURAL_API, (_NEURAL_MODEL, *_DC_MOTOR)), + ActuatorNetLSTMCfg: ActuatorLayout(ActuatorNetLSTM, _NEURAL_API, (_NEURAL_MODEL, *_DC_MOTOR)), + BamActuatorCfg: ActuatorLayout(None, BAM_DRIVE_API, _BAM_FIELDS), + }.items() } """Newton actuator layout of each supported config type; subclasses use their closest base's layout.""" def _actuator_layout(cfg: ActuatorBaseCfg) -> ActuatorLayout | None: """Return the Newton actuator layout of *cfg*'s type, or None if Newton cannot author it.""" - return next((_ACTUATOR_LAYOUTS[cls] for cls in type(cfg).__mro__ if cls in _ACTUATOR_LAYOUTS), None) + registration = _native_actuator_registration(cfg) + return registration.layout if registration is not None else None + + +def _native_actuator_registration(cfg: ActuatorBaseCfg) -> _NativeActuatorRegistration | None: + """Resolve the closest registered config base for authoring and runtime setup.""" + return next((_ACTUATOR_REGISTRATIONS[cls] for cls in type(cfg).__mro__ if cls in _ACTUATOR_REGISTRATIONS), None) def resave_checkpoint_with_metadata(original_path: str, metadata: dict[str, Any]) -> str: diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 2ab078d58581..62d7a9b5e651 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -518,6 +518,64 @@ def test_articulation_control_projects_warp_joint_property_selectors(): torch.testing.assert_close(defaults["armature"], expected) +def test_native_finalize_hooks_can_sample_through_the_public_collection(monkeypatch): + """Startup hooks must see bound native groups and public parameter access during collection construction.""" + backend_control = pytest.importorskip("isaaclab_isaacsim.assets.articulation.actuator_control") + + from pxr import Usd, UsdPhysics + + from isaaclab.actuators import IdealPDActuator + from isaaclab.actuators.newton import NativeActuatorHooks + from isaaclab.sim.schemas import schemas_actuators as schemas + + monkeypatch.setattr(schemas, "_ACTUATOR_REGISTRATIONS", dict(schemas._ACTUATOR_REGISTRATIONS)) + for name in ("_DRIVE_APIS", "_COMPONENT_APIS", "_KNOWN_ACTUATOR_APIS"): + monkeypatch.setattr(schemas, name, getattr(schemas, name)) + + class CustomCfg(IdealPDActuatorCfg): + pass + + phases = [] + + class Hooks(NativeActuatorHooks): + def finalize(self, context): + assert context.collection[context.group_name] is context.bindings[0].actuator + write_group_parameter(context.collection, context.group_name, "drive", "kp", torch.full((2, 3), 7.0)) + phases.append("finalize") + + def solver_init(self, context): + torch.testing.assert_close( + read_group_parameter(context.collection, context.group_name, "drive", "kp"), torch.full((2, 3), 7.0) + ) + phases.append("solver_init") + + schemas.register_native_actuator( + CustomCfg, + schemas.ActuatorLayout( + IdealPDActuator, + "NewtonPDControlAPI", + (schemas.ActuatorField("stiffness", "NewtonPDControlAPI", "newton:kp"),), + ), + hooks_type=Hooks, + ) + stage = Usd.Stage.CreateInMemory() + robot = stage.DefinePrim("/Robot", "Xform") + for i in range(3): + UsdPhysics.RevoluteJoint.Define(stage, f"/Robot/joint_{i}") + cfgs = {"custom": CustomCfg(joint_names_expr=[".*"], stiffness=2.0, damping=0.0)} + schemas.author_actuator_prims(stage, "/Robot", cfgs) + articulation = FakeArticulation() + articulation._data = articulation.data + articulation.joint_names = ["joint_0", "joint_1", "joint_2"] + articulation._sim_cfg = SimpleNamespace(use_newton_actuators=True) + articulation.cfg = SimpleNamespace(prim_path="/Robot") + monkeypatch.setattr(backend_control, "get_current_stage", lambda: stage) + monkeypatch.setattr(backend_control, "find_first_matching_prim", lambda path: robot) + collection = ActuatorCollection(cfgs, backend_control.PhysxActuatorControl(articulation)) + assert phases == ["finalize", "solver_init"] + torch.testing.assert_close(read_group_parameter(collection, "custom", "drive", "kp"), torch.full((2, 3), 7.0)) + + def test_native_explicit_groups_zero_solver_drives_and_build_no_lab_model(monkeypatch): """Zero the solver drives of a native explicit group and expose the Newton actuator.""" from isaaclab.actuators.newton.adapter import LightArticulationView, NewtonActuatorSelection diff --git a/source/isaaclab/test/actuators/test_newton_adapter.py b/source/isaaclab/test/actuators/test_newton_adapter.py index 4caaaa102787..b3426baaa102 100644 --- a/source/isaaclab/test/actuators/test_newton_adapter.py +++ b/source/isaaclab/test/actuators/test_newton_adapter.py @@ -555,6 +555,190 @@ def test_define_actuator_properties_authors_every_spawned_articulation(monkeypat # --------------------------------------------------------------------------- +@pytest.mark.kitless +def test_registered_native_config_preserves_custom_schemas_and_authors_joint_data(monkeypatch): + """External layouts retain asset values, author joint data and execute a registered custom drive.""" + from newton._src.actuators import usd_parser + from newton.actuators import ComponentKind, register_actuator_component + + from isaaclab.actuators import IdealPDActuator + from isaaclab.actuators.newton import PhysxActuatorWrapper + from isaaclab.sim.schemas import schemas_actuators as schemas + + register = schemas.register_native_actuator + monkeypatch.setattr(schemas, "_ACTUATOR_REGISTRATIONS", dict(schemas._ACTUATOR_REGISTRATIONS)) + for name in ("_DRIVE_APIS", "_COMPONENT_APIS", "_KNOWN_ACTUATOR_APIS"): + monkeypatch.setattr(schemas, name, getattr(schemas, name)) + monkeypatch.setattr(usd_parser, "_SCHEMA_REGISTRY", dict(usd_parser._SCHEMA_REGISTRY)) + + class CustomDrive(DrivePD): + @classmethod + def resolve_arguments(cls, args): + values = super().resolve_arguments(args) + values["kp"] *= 2 + return values + + class CustomClamp(ClampingMaxEffort): + @classmethod + def resolve_arguments(cls, args): + values = super().resolve_arguments(args) + values["max_effort"] *= 0.5 + return values + + register_actuator_component("TestCustomDriveAPI", CustomDrive, ComponentKind.DRIVE) + register_actuator_component("TestCustomClampAPI", CustomClamp, ComponentKind.CLAMPING) + + class CustomActuator(IdealPDActuator): + pass + + class CustomCfg(ActuatorBaseCfg): + pass + + def author(context): + context.joints["pd_a"].CreateAttribute("custom:setup", Sdf.ValueTypeNames.Float).Set(3.0) + assert context.actuator_prims["pd_a"].GetPath() == Sdf.Path("/World/Robot/asset_actuator") + + layout = schemas.ActuatorLayout( + CustomActuator, + "TestCustomDriveAPI", + ( + schemas.ActuatorField("stiffness", "TestCustomDriveAPI", "newton:kp"), + schemas.ActuatorField("actuator_effort_limit", "TestCustomClampAPI", "newton:maxEffort"), + ), + ) + register(CustomCfg, layout, author=author) + with pytest.raises(ValueError, match="already registered"): + register(CustomCfg, layout) + + class DerivedCfg(CustomCfg): + pass + + stage = _make_robot_stage() + prim = stage.DefinePrim("/World/Robot/asset_actuator", "NewtonActuator") + prim.CreateRelationship("newton:targets").SetTargets(["/World/Robot/pd_a"]) + prim.AddAppliedSchema("TestCustomDriveAPI") + prim.AddAppliedSchema("TestCustomClampAPI") + prim.CreateAttribute("newton:kp", Sdf.ValueTypeNames.Float).Set(17.0) + prim.CreateAttribute("newton:maxEffort", Sdf.ValueTypeNames.Float).Set(30.0) + cfg = DerivedCfg(class_type=CustomActuator, joint_names_expr=["pd_a"], stiffness=None, damping=None) + author_actuator_prims(stage, "/World/Robot", {"custom": cfg}) + assert prim.IsActive() + assert prim.GetAttribute("newton:kp").Get() == 17.0 + assert prim.GetAttribute("newton:maxEffort").Get() == 30.0 + assert stage.GetPrimAtPath("/World/Robot/pd_a").GetAttribute("custom:setup").Get() == 3.0 + adapter = NewtonActuatorAdapter.from_usd(stage, ["pd_a"], 2, 1, "cpu", "/World/Robot") + wrapper = PhysxActuatorWrapper.create(2, 1, "cpu") + wrapper.joint_q = wp.zeros(2, device="cpu") + wrapper.joint_qd = wp.zeros(2, device="cpu") + wrapper.joint_target_pos = wp.array([0.25, 1.0], dtype=wp.float32, device="cpu") + wrapper.joint_target_vel = wp.zeros(2, device="cpu") + wrapper.joint_act = wp.zeros(2, device="cpu") + adapter.finalize(wrapper) + adapter.step(wrapper, wrapper, 0.01) + np.testing.assert_allclose(wrapper.joint_f.numpy(), [8.5, 15.0]) + + class UnregisteredActuator(CustomActuator): + pass + + before = stage.GetRootLayer().ExportToString() + with pytest.raises(ValueError, match="does not support"): + author_actuator_prims(stage, "/World/Robot", {"custom": cfg.replace(class_type=UnregisteredActuator)}) + assert stage.GetRootLayer().ExportToString() == before + + +@pytest.mark.kitless +def test_native_hooks_prepare_before_state_and_isolate_merged_groups(monkeypatch): + """Host lifecycle hooks see owned slots, independent instances and partial reset selections.""" + from newton.actuators import Actuator + + from isaaclab.actuators import IdealPDActuator + from isaaclab.actuators.newton.hooks import NativeActuatorHooks + from isaaclab.sim.schemas import schemas_actuators as schemas + + monkeypatch.setattr(schemas, "_ACTUATOR_REGISTRATIONS", dict(schemas._ACTUATOR_REGISTRATIONS)) + for name in ("_DRIVE_APIS", "_COMPONENT_APIS", "_KNOWN_ACTUATOR_APIS"): + monkeypatch.setattr(schemas, name, getattr(schemas, name)) + + class CustomCfg(IdealPDActuatorCfg): + pass + + events, instances = [], [] + + class Hooks(NativeActuatorHooks): + def prepare(self, context): + events.append(("prepare", context.group_name)) + instances.append((self, context)) + self.extra = torch.ones(2) + + def finalize(self, context): + events.append(("finalize", context.group_name)) + assert context.adapter is not None + + def solver_init(self, context): + events.append(("solver_init", context.group_name)) + assert context.backend == "physx" + assert context.model is None and context.solver is None + + def reset(self, context, env_ids, env_mask): + self.extra[wp.to_torch(env_mask) if env_mask is not None else env_ids] = 0 + + schemas.register_native_actuator( + CustomCfg, + schemas.ActuatorLayout( + IdealPDActuator, + "NewtonPDControlAPI", + (schemas.ActuatorField("stiffness", "NewtonPDControlAPI", "newton:kp"),), + ), + hooks_type=Hooks, + ) + cfgs = {name: CustomCfg(joint_names_expr=[name], stiffness=2.0, damping=0.0) for name in ("pd_a", "pd_b")} + stage = _make_robot_stage() + author_actuator_prims(stage, "/World/Robot", cfgs) + state = Actuator.state + + def record_state(actuator): + events.append(("state", None)) + return state(actuator) + + monkeypatch.setattr(Actuator, "state", record_state) + + def buffer(): + return SimpleNamespace(warp=wp.zeros((2, 2), device="cpu")) + + articulation = SimpleNamespace( + device="cpu", + num_instances=2, + num_joints=2, + joint_names=["pd_a", "pd_b"], + _data=SimpleNamespace(joint_pos=buffer(), joint_vel=buffer()), + ) + collection = SimpleNamespace( + target_command=SimpleNamespace(position=buffer(), velocity=buffer(), effort=buffer()), + _group_joint_names={name: [name] for name in cfgs}, + _group_joint_indices={"pd_a": torch.tensor([0]), "pd_b": torch.tensor([1])}, + _implicit_group_joint_indices=lambda: [], + ) + runtime = PhysxActuatorRuntime(articulation, logger=logging.getLogger(__name__)) + runtime.prepare(collection, stage=stage, articulation_prim_path="/World/Robot", actuator_cfgs=cfgs) + runtime.finalize(collection) + runtime.finalize_hooks() + + assert events[:2] == [("prepare", "pd_a"), ("prepare", "pd_b")] + assert events[2:4] == [("state", None), ("state", None)] + assert events[4:] == [("finalize", "pd_a"), ("finalize", "pd_b"), ("solver_init", "pd_a"), ("solver_init", "pd_b")] + assert instances[0][0] is not instances[1][0] + first, second = (context.bindings[0] for _, context in instances) + assert first.actuator is second.actuator + assert first.slots == (0, 2) and second.slots == (1, 3) + runtime.reset([1]) + for hook, _ in instances: + torch.testing.assert_close(hook.extra, torch.tensor([1.0, 0.0])) + mask = wp.array([True, False], dtype=wp.bool, device="cpu") + runtime.reset([1], mask) + for hook, _ in instances: + torch.testing.assert_close(hook.extra, torch.zeros(2)) + + def _runtime() -> PhysxActuatorRuntime: """Create a runtime for a CUDA articulation with a mocked logger.""" return PhysxActuatorRuntime(SimpleNamespace(device="cuda:0"), logger=Mock()) diff --git a/source/isaaclab_isaacsim/changelog.d/native-actuator-registration.added.rst b/source/isaaclab_isaacsim/changelog.d/native-actuator-registration.added.rst new file mode 100644 index 000000000000..871b6df84573 --- /dev/null +++ b/source/isaaclab_isaacsim/changelog.d/native-actuator-registration.added.rst @@ -0,0 +1 @@ +* Enabled registered native actuator lifecycle hooks through the shared host runtime. diff --git a/source/isaaclab_isaacsim/isaaclab_isaacsim/assets/articulation/actuator_control.py b/source/isaaclab_isaacsim/isaaclab_isaacsim/assets/articulation/actuator_control.py index 13f0d39ef883..2e3c1e8a7b78 100644 --- a/source/isaaclab_isaacsim/isaaclab_isaacsim/assets/articulation/actuator_control.py +++ b/source/isaaclab_isaacsim/isaaclab_isaacsim/assets/articulation/actuator_control.py @@ -81,6 +81,7 @@ def prepare_native_actuators(self, collection: ActuatorCollection, actuator_cfgs stage=get_current_stage(), articulation_prim_path=art_prim_path, adapt_usd_actuators=bool(native_group_names), + actuator_cfgs=actuator_cfgs, ) articulation._physx_actuator_wrapper = self._actuator_runtime.wrapper articulation.newton_actuator_adapter = self._actuator_runtime.adapter @@ -100,6 +101,10 @@ def finalize_native_actuators(self, collection: ActuatorCollection) -> NewtonAct actuators=adapter.actuators, ) + def finalize_native_actuator_hooks(self) -> None: + if self._native_actuator_path_active and self._actuator_runtime is not None: + self._actuator_runtime.finalize_hooks() + def compute_native_actuators(self, collection: ActuatorCollection, dt: float) -> bool: if not self._native_actuator_path_active or self._actuator_runtime is None: return False diff --git a/source/isaaclab_newton/changelog.d/native-actuator-registration.added.rst b/source/isaaclab_newton/changelog.d/native-actuator-registration.added.rst new file mode 100644 index 000000000000..2774e037f100 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/native-actuator-registration.added.rst @@ -0,0 +1,2 @@ +* Added registered actuator setup, reset and solver initialization hooks, with component-state allocation + deferred until all articulations have prepared. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/actuator_control.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/actuator_control.py index 4006164b82a1..f3fce864b402 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/actuator_control.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/actuator_control.py @@ -23,6 +23,7 @@ from isaaclab.actuators.newton import build_implicit_dof_mask from isaaclab.actuators.newton import kernels as actuator_kernels from isaaclab.actuators.newton.adapter import NewtonActuatorSelection +from isaaclab.actuators.newton.hooks import _NativeActuatorLifecycle from isaaclab.assets.articulation import ordering_kernels from isaaclab.sim.schemas.schemas_actuators import validate_newton_native_actuator_cfgs @@ -48,6 +49,7 @@ def __init__(self, articulation: Articulation): super().__init__(articulation) self._bam_cfgs: dict[str, BamActuatorCfg] = {} self._bam_group_dofs: dict[str, set[int]] = {} + self._native_hooks: _NativeActuatorLifecycle | None = None def prepare_native_actuators(self, collection: ActuatorCollection, actuator_cfgs: dict) -> set[str]: articulation = self._articulation @@ -78,6 +80,19 @@ def prepare_native_actuators(self, collection: ActuatorCollection, actuator_cfgs for actuator in model_actuators: if isinstance(actuator.drive, DriveBam): actuator.drive.env_dof_stride = len(actuator.indices) // self.num_instances + backend = self._articulation._backend_manager.backend + ordering = articulation.data.joint_ordering + self._native_hooks = _NativeActuatorLifecycle( + articulation, + collection, + actuator_cfgs, + model_actuators, + backend="newton", + control=backend.control, + model=backend.model, + dof_offset=self._joint_dof_offset(), + joint_user_to_backend=ordering.user_to_backend_indices if ordering is not None else None, + ) self._articulation._backend_manager.activate_newton_actuator_path() return native_group_names @@ -177,6 +192,13 @@ def _post_actuator() -> None: ), ) + def finalize_native_actuator_hooks(self) -> None: + if self._native_hooks is not None: + self._native_hooks.finalize(self._articulation.newton_actuator_adapter) + self._articulation._backend_manager.register_solver_init_callback( + lambda: self._native_hooks.solver_init(self._articulation._backend_manager.backend.solver) + ) + def compute_native_actuators(self, collection: ActuatorCollection, dt: float) -> bool: return self._native_actuator_path_active @@ -242,6 +264,8 @@ def submit_commands(self, collection: ActuatorCollection) -> None: def reset_native_actuators(self, env_ids: Sequence[int] | slice, env_mask: wp.array | None = None) -> None: if self._native_actuator_path_active and self._articulation._backend_manager.backend.actuators is not None: self._articulation._backend_manager.backend.actuators.reset(env_ids, env_mask) + if self._native_hooks is not None: + self._native_hooks.reset(env_ids, env_mask) def _bam_actuators(self) -> list[tuple[Actuator, list[str]]]: """Return the Newton BAM actuators that drive this articulation, each with the BAM groups it drives. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index c5b6ffe67314..7f7f6e5e7a50 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -668,8 +668,11 @@ def activate_actuators(self) -> None: num_joints=model.joint_dof_count // num_envs, dof_offset=0, device=str(self.device), + defer_state_initialization=True, ) self.actuators.finalize(self.control) + # All articulations prepare before solver initialization; allocate before their solver-ready hooks. + self.solver_init_callbacks.insert(0, self.actuators.initialize_states) self.invalidate_graph() def add_contact_sensor( diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index e50dc0a95ca6..fba2fd290380 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -518,6 +518,87 @@ def check_step(self, captured, debug): # ----- Solver initialization and contacts ---------------------------------------------------- +@pytest.mark.kitless +def test_native_state_allocation_waits_for_all_articulations(monkeypatch): + """The first activation must not allocate another articulation's actuator state before its prepare hook.""" + from newton.actuators import Actuator, DrivePD + + from isaaclab.actuators import IdealPDActuator, IdealPDActuatorCfg + from isaaclab.actuators.newton.hooks import NativeActuatorHooks, _NativeActuatorLifecycle + from isaaclab.sim.schemas import schemas_actuators as schemas + + monkeypatch.setattr(schemas, "_ACTUATOR_REGISTRATIONS", dict(schemas._ACTUATOR_REGISTRATIONS)) + for name in ("_DRIVE_APIS", "_COMPONENT_APIS", "_KNOWN_ACTUATOR_APIS"): + monkeypatch.setattr(schemas, name, getattr(schemas, name)) + events = [] + backend = _recording_backend(events) + + class CustomCfg(IdealPDActuatorCfg): + pass + + class Hooks(NativeActuatorHooks): + def prepare(self, context): + events.append(("prepare", context.group_name)) + assert context.bindings[0].slots == ((1,) if context.group_name == "first" else (0,)) + + def solver_init(self, context): + assert context.solver is backend.solver + events.append(("ready", context.group_name)) + + schemas.register_native_actuator( + CustomCfg, schemas.ActuatorLayout(IdealPDActuator, "NewtonPDControlAPI", ()), hooks_type=Hooks + ) + actuators = [ + Actuator( + indices=wp.array(columns, dtype=wp.uint32, device="cpu"), + drive=DrivePD(kp=wp.ones(len(columns), device="cpu"), kd=wp.zeros(len(columns), device="cpu")), + ) + for columns in ([0, 1], [2]) + ] + backend.model = SimpleNamespace(actuators=actuators, world_count=1, joint_dof_count=3) + backend.control = SimpleNamespace() + original_state = Actuator.state + + def state(actuator): + assert events[:2] == [("prepare", "first"), ("prepare", "second")] + events.append(("state", None)) + return original_state(actuator) + + monkeypatch.setattr(Actuator, "state", state) + lifecycles = [] + for offset, name in ((0, "first"), (2, "second")): + collection = SimpleNamespace( + _group_joint_names={name: ["joint"]}, _group_joint_indices={name: torch.tensor([0])} + ) + lifecycle = _NativeActuatorLifecycle( + SimpleNamespace(num_instances=1, num_joints=2 if name == "first" else 1), + collection, + {name: CustomCfg(joint_names_expr=["joint"], stiffness=1.0, damping=0.0)}, + actuators, + backend="newton", + model=backend.model, + control=backend.control, + dof_offset=offset, + joint_user_to_backend=(1, 0) if name == "first" else None, + ) + lifecycles.append(lifecycle) + backend.activate_actuators() + assert events == [("prepare", "first"), ("prepare", "second")] + for lifecycle in lifecycles: + lifecycle.finalize(backend.actuators) + backend.solver_init_callbacks.append(lambda lifecycle=lifecycle: lifecycle.solver_init(backend.solver)) + backend.init_solver() + backend.actuators.initialize_states() + assert [event for event in events if event[0] in {"state", "ready"}] == [ + ("state", None), + ("state", None), + ("state", None), + ("state", None), + ("ready", "first"), + ("ready", "second"), + ] + + @pytest.mark.parametrize( "solver_cfg", [KaminoPADMMSolverCfg(), MPMSolverCfg(), MJWarpSolverCfg()], ids=["kamino", "mpm", "mjwarp"] ) diff --git a/source/isaaclab_ov/changelog.d/native-actuator-registration.added.rst b/source/isaaclab_ov/changelog.d/native-actuator-registration.added.rst new file mode 100644 index 000000000000..871b6df84573 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/native-actuator-registration.added.rst @@ -0,0 +1 @@ +* Enabled registered native actuator lifecycle hooks through the shared host runtime. diff --git a/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py b/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py index 74add9260ef8..9dc486555f22 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py @@ -70,6 +70,8 @@ def prepare_native_actuators(self, collection: ActuatorCollection, actuator_cfgs stage=get_current_stage(), articulation_prim_path=articulation_prim_path, adapt_usd_actuators=bool(native_group_names), + actuator_cfgs=actuator_cfgs, + backend="ov", ) articulation._physx_actuator_wrapper = self._actuator_runtime.wrapper articulation.newton_actuator_adapter = self._actuator_runtime.adapter @@ -88,6 +90,10 @@ def finalize_native_actuators(self, collection: ActuatorCollection) -> NewtonAct actuators=adapter.actuators, ) + def finalize_native_actuator_hooks(self) -> None: + if self._native_actuator_path_active and self._actuator_runtime is not None: + self._actuator_runtime.finalize_hooks() + def compute_native_actuators(self, collection: ActuatorCollection, dt: float) -> bool: if not self._native_actuator_path_active or self._actuator_runtime is None: return False