Architecture & porting playbook

This is the source of truth for how roqsim is built and how to rework existing MuJoCo code into it. It documents both what exists today and designs that are planned / not yet implemented (so marked). A large external MuJoCo codebase is expected to be reworked into this structure — the Porting playbook (section 6) is the section to read for that.

Status legend: [planned] means designed but not yet built. Everything else is implemented.

1. Overview & goals

roqsim is a lightweight, plugin-driven MuJoCo simulator for mobile robots, robot arms, and mobile manipulators (plus extras like conveyor belts). A MuJoCo step loop plus plugins that hook into well-defined lifecycle points, all loaded and configured from a single YAML file.

Two ways to run, one engine:

  • Standalone driver (runner.py) — owns the loop; windowed by default, headless for containers; real-time / factor / as-fast-as-possible pacing; can record world state over time.

  • scenario-execution driver (scenario_adapter.py) — a SimulationInterface subclass; scenario-execution owns the loop and calls dt/setup/reset/step/shutdown. It also publishes context, the seam an in-process scenario action reads (§12, Reaching a plugin from outside).

Both wrap the same Engine, so behaviour is identical across the two.

Tick pipeline (one step()):

external threads ──post(cmd)──▶ [command queue]
                                     │ (drained on physics thread)
physics thread:  drain ─▶ pre_step(all) ─▶ mj_step ─▶ post_step(all) ─▶ snapshot
                         (write ctrl)      (physics)   (read/publish)   (cross-thread reads)

Non-goals: roqsim is not a general game engine or a physics fork; it orchestrates MuJoCo. It does not recompile the model at runtime (see anti-patterns).

2. Lifecycle reference

A plugin (roqsim.plugin.Plugin) implements any subset of seven hooks. The engine only calls hooks a plugin actually overrides (an un-overridden hook costs nothing and is absent from the timing table).

Hook

When

May touch

Typical use

build(spec, ctx)

once, pre-compile

spec only (model/data are None)

add bodies/geoms/sensors/assets

build_late(spec, ctx)

once, after every build, pre-compile

spec only

link its own model to another plugin’s (an equality between two entities), wherever the world lists them

configure(ctx)

once, post-compile

model, data, ids

resolve body/site ids, open resources, advertise services, register RobotHandle/Entity

on_reset(ctx)

every reset, after mj_resetData

model, data

re-home arm, respawn objects

pre_step(ctx)

each tick, before mj_step

data (write ctrl, forces)

apply commands

post_step(ctx)

each tick, after mj_step

data (read)

publish, record

shutdown(ctx)

once, teardown (reverse order)

—

close nodes, flush files

Full-run sequence:

setup():   build(p0)…build(pN)  →  spec.compile()  →  MjData  →  configure(p0)…configure(pN) → mj_forward
reset():   drain →  mj_resetData → mj_forward → on_reset(p0)…on_reset(pN) → mj_forward → interpenetration check → gates.reset()
step():    drain → pre_step(p0…pN) → mj_step → post_step(p0…pN) → publish_snapshot   (refused until a reset() since setup())
shutdown(): shutdown(pN)…shutdown(p0)   (best-effort; a failure is logged, others still run)

After setup() the data describes the initial state. Its closing mj_forward computes body, geom, site and camera poses, sensor data and contacts from what the model and every configure put in data, so a world inspected before its first reset – a geometry check, an export, a test – does not read MjData’s zeros, which put every part at the origin. No time passes (data.time stays 0) and reset() starts from mj_resetData, so the pass changes no trial. configure runs before it: a plugin that reads a pose there runs its own forward pass. What on_reset writes – an arm’s home, a re-seated base, a walker’s first frame – comes with reset(), so the pose setup() leaves is the one reset() gives wherever no on_reset writes one.

A trial starts at reset(). step() raises a RuntimeError naming reset() on an engine that has not completed one since setup(): the posed data is for inspection, and a trial stepped from it would start before any on_reset placed its initial state – a state no driver runs. A reset() that raises leaves the engine in the same position until one completes. idle() advances no time and runs no hook, so it needs no reset.

A configure that raises ends setup() with the plugins configured before it, and the failing one, shut down in reverse order: they hold what configure opens, and the driver never receives an engine to shut down. shutdown() on such an engine is then a no-op, as is a second shutdown().

A driver holds the engine in a with block, which runs setup() on entry and shutdown() on every way out – a return, an exception from reset or a step, an interrupt:

engine = Engine(cfg)
engine.ctx.seed = resolve_seed(...)   # before setup: configure may read it
with engine:
    engine.reset()
    ...

Where a window, a recorder or a renderer must also close, the driver puts them on one contextlib.ExitStack with the engine. A function that hands a set-up engine to its caller (roqsim.render.build_target, the scene builder’s load_engine) enters it on an ExitStack and calls pop_all() once nothing more can fail, so a failure before the hand-over still shuts it down; the caller then owns the shutdown. The scenario adapter is the one driver that keeps an engine across calls – scenario-execution calls its setup and shutdown – so it shuts the engine down in _teardown_engine rather than in a block.

Ordering rule: within a hook, plugins run in YAML order; shutdown runs in reverse. Cross-plugin dependencies are expressed by ordering + the blackboard, never by importing another plugin. A plugin whose build edits what another plugin built – contact_pair_override on the entities it pairs, flex_material on the flex a spawned model brings in – is declared after that plugin, and refuses at build time, naming the fix, when what it edits is not there yet.

The start state is checked for interpenetration. After the closing mj_forward of reset(), data.contact describes the state the trial starts from — keyframes and home poses applied, props re-seated — and roqsim.interpenetration.interpenetrations() reads every contact MuJoCo acts on (efc_address >= 0) whose penetration -dist exceeds that contact’s tolerance: the largest of 5 mm, its solimp width, and the depth at which its solref spring asks for one standard gravity (so a softer contact may sit deeper). Contacts between the same two sides fold into one finding; a side is a geom or, for a flex contact (contact.geom == -1), the flex named from contact.flex; each side carries the entity that owns its body (the entity with a root body, body or one of bodies, at or above it). The findings are kept in Engine.interpenetrations and logged as one WARNING naming the deepest three pairs and what to change (an arm’s home, a spawn pose). Nothing is refused: the overlap would otherwise be resolved on the first steps with contact forces that fling the bodies apart, and the run would fail later in a way that looks like a controller or protocol fault, so the finding is written where that run’s log keeps it. A pair MuJoCo does not collide (contype/conaffinity, <exclude>, parent-child filtering) exerts no force and is not reported, which is also how an intended overlap is declared. A geom that passes all the way through a thin one can get no contact from MuJoCo at all; the solver then does not act on it either, and it is not reported. roqsim check resets the world and reports the same findings as warnings, and so does roqsim scenes describe --entities.

Lights the renderer leaves dark are named when the world compiles. MuJoCo’s OpenGL renderer draws eight lights per frame, the headlight among them when it is active, taking the model’s active lights in index order; every further light compiles and is never drawn. setup() logs one WARNING naming those lights (roqsim.lights.undrawn_lights()). Nothing is refused.

Reference implementation: roqsim/src/roqsim/engine.py.

3. API contracts

Plugin (plugin.py)

  • __init__(self, config: dict | None, *, name: str | None, entity: str | None, label: str | None) — receives its YAML config: section; entity is the address of the entry it is nested under and label its own. A subclass that overrides __init__ passes all four through.

  • validate_config(self, config) -> list[str] — return error strings (empty = valid).

  • expand(cls, spec, world, base_dir) -> list[PluginSpec] (classmethod, optional) — extra specs to splice in right after this one at config load; used by spawn plugins to pull in a model’s manifest (see §4). What it returns is expanded in turn. A plugin lists the config keys expand reads in expansion_keys, so a too-late override of one is refused. Default: none.

  • Hooks as in §2. parallel_safe: bool marks a read-only post_step for the future parallel executor. transport_only: bool marks a plugin that builds no geometry and holds no state (BridgeBase and its subclasses), so a preview engine (Engine(preview=True), which every scene-only consumer — roqsim render, the review window, the exporters — builds) leaves it out and can therefore build a *_ros world without its middleware installed; roqsim sim keeps it unless asked for --no-communication, which warns that the run then publishes and receives nothing (see Available plugins › Transport plugins).

  • rebuild_cost: str | None marks a sensor whose outputs are a function of the restored state, the seed and the sim time alone, and says what one capture costs ("render", "raycast"). Such a plugin implements capture(ctx) – produce the outputs now, past its own rate and subscriber gates – and roqsim.rebuild drives it on a recording’s restored samples, so a run need not produce or keep those streams; output_cost(endpoint) says it per endpoint (a camera’s camera_info is cheap), and roqsim check --json reports both per endpoint. A rebuilt frame is the render of the state at its stamp. Live, post_step runs after mj_step, whose body poses are still those from before the step’s integration, so a live frame of a moving body shows it one physics step earlier than its stamp; a rebuilt frame equals the live sensor’s capture after mj_forward at the same state, pixel for pixel, noise included.

SimContext (context.py)

Passed to every hook. Key members:

  • spec (build phase), model, data, dt, sim_time.

  • config — the full parsed YAML dict.

  • blackboard: Blackboard — set/get/require/__contains__; typed cross-plugin store.

  • entities: EntityRegistry — add/remove/get/names/all of Entity(name, kind, body, bodies, meta, present, listed) (names/all take present_only and listed_only); backs simulation_interfaces discovery. body is the root body, whose pose is the entity’s; bodies are the other roots it owns, each with its subtree, for an entity that is not one kinematic tree (a walker’s limbs are mocap bodies of the world, not children of its pelvis). Everything that resolves an entity to its geometry takes it whole, through roqsim.presence.entity_bodies / entity_geoms (and roqsim.flex.entity_flexes): presence, the contact plugins (contact_monitor, contact_impulse, contact_location, bumper), clearance_monitor on both sides, model_override’s entity:, segmentation_camera’s entities:, the interpenetration check, the navigator’s caution probe and its ignore, a recording’s <entity>/** tracks, GetEntities’ bounds and the framing of --focus and a preview.

  • render — the RenderService every image comes through (set at setup; see §8).

  • events: EventLog — emit(source, event, **fields) on the physics thread records what a plugin decided, stamped with sim_time and run (roqsim.events); a recording carries each one on its events channel from the moment it starts, and Recording.events reads them back.

  • conditions: list[dict] — how the world loaded where a result should say it (roqsim.conditions): a plugin that loads the world weaker than asked, rather than stopping it, calls raise_condition(ctx, source=..., code=..., message=..., fix=...) in build/build_late (baked lighting whose bake is missing raises bake_missing). The engine writes the list into the compiled model (the text element roqsim:conditions, read back by conditions.of_model), and from there it reaches a recording’s provenance (conditions), roqsim render’s JSON record, roqsim check’s warnings (check: condition) and roqsim_conditions.json in the run’s RUN_OUTPUT_DIR (else OUTPUT_DIR), which a campaign collects with the run’s other artifacts. A log line alone does not survive the run; a condition is what lets a result made from a weaker world be told apart afterwards.

  • post(cmd) / drain_commands() — the thread-safe command queue (§7).

  • publish_snapshot(d) / read_snapshot() — immutable snapshot for cross-thread readers.

  • register_gate(name, role) / gates() — step-gate API for synchronous mode (§10); the engine does not wait on gates.

RobotHandle (context.py)

RobotHandle(name, drive(vx,vy,w), read_odom()->(x,y,yaw,vx,vy,w), kinematics), where kinematics is unicycle (default), holonomic or ackermann and tells a consumer which commands the base can follow. A controller plugin puts one on the blackboard (key convention robot:<name>); a bridge looks it up. Both callables run on the physics thread.

Registry (registry.py)

resolve_plugin(ref, base_dir) -> type[Plugin]. See §4.

Config (config.py)

load_config(path) / load_config_from_dict(raw, base_dir) → SimConfig. instantiate_plugins(cfg) -> list[Plugin] resolves classes, expands manifests (Plugin.expand; see §4), constructs, and runs aggregated validation.

4. Config & registry

Single world YAML, two sections; components order = execution order:

sim:
  timestep: 0.004        # optional; else from the model
  pacing: realtime       # realtime | {factor: 4.0} | asap
  world: empty_room      # built-in name OR a path to an MJCF file; default empty_room (see below)
  integrator: auto       # auto (default) | euler | rk4 | implicit | implicitfast | discrete
  noslip_iterations: 10  # solver effort; see "Solver options" below
  sync: {enabled: false} # foreseen lockstep mode (§10); inert

components:
  - floorplan:                   # (1) entry-point short name -- the ref *is* the key
      mesh: envs/x.stl
      collision: true
    name: ground                 # optional instance name (reserved sibling key)
  - "my_pkg.mod:MyPlugin": { ... } # (2) importable module:Class (PYTHONPATH)
  - "./plugins/x.py:Foo": { ... }  # (3) file path:Class (relative to this YAML)

Each entry is a mapping with exactly one plugin-ref key (its value is the config map) plus an optional reserved name: sibling, defaulting to the ref. name: or components: found inside the config map is refused (parse_plugin_entry), because no plugin reads either from its config.

Those two sections, extends/disable (inheritance) and version are the whole top level (roqsim.config.WORLD_KEYS), and any other key there is refused. A world declares no parameters and substitutes nothing into itself: a value that varies per run is written as its ordinary literal and changed by an override, which addresses the key in place. An override rooted anywhere but sim or components is refused for the same reason: accepted, it would merge into the document where nothing reads it, and the run would report success against the unchanged world.

Three plugin-ref resolution forms (resolve_plugin):

  1. Short name → roqsim.plugins entry-point group.

  2. ``module.path:Class`` → importlib.import_module (any package on PYTHONPATH).

  3. ``path/to/file.py:Class`` → importlib.util.spec_from_file_location (relative to the config dir).

Forms 2 and 3 contain a colon, and the ref is the entry’s key, so quote it (- "my_pkg.mod:MyPlugin": {...}) — unquoted it parses only while no space follows the colon, so a stray key: value space would silently truncate the ref. Short names have no colon and need no quotes.

Order: no : → must be an entry-point (else error). Has : → file if the left side ends in .py or exists on disk, else module. Every failure raises PluginError naming the attempted form. A plugin file is executed once per process and reused until it changes on disk, so every resolution of one ref returns the same class.

Validation is delegated to each plugin (validate_config); instantiate_plugins aggregates all errors across all plugins and raises once, namespaced [name (ref)] message. A plugin is constructed before its config is validated, so a constructor that raises on a value of the wrong type is reported in the same list, as could not be constructed, beside what validate_config says of the same config.

World definition (sim.world)

The static environment the robots/props stand in — ground + lighting — is a world definition, chosen with the sim.world key (roqsim/world.py). It is separate from robot-family scene plugins so a fixed cell (an arm, a conveyor) never has to depend on the mobile package for a floor. Semantics:

  • sim.world is either a built-in world name or a path to an MJCF file. The only built-in is empty_room (a checker ground plane named floor, a ceiling light, and four perimeter walls — a bounded, lit room); unset ⇒ empty_room. A value that ends in .xml/.mjcf or contains a path separator is loaded as the base scene (MjSpec.from_file, resolved relative to the world YAML) — e.g. a baked scene like depot/depot.xml (see roqsim_scenes). Anything that is neither the built-in nor a resolvable file is a fail-fast error.

  • The engine builds/loads the world into the MjSpec before any plugin build, so plugins attach onto it.

  • A scene plugin that builds its own ground+lighting sets the class attribute provides_world = True (the mobile floorplan, which also adds lidar walls). When such a plugin is present the engine skips the world definition; a world that also sets sim.world, or carries two such plugins, is refused with a PluginError naming both (Engine._check_one_world). So floorplan is the mobile scene, sim.world is the fixed-cell default, and they never double up the floor.

Policy specs (roqsim.policy)

A policy-driven robot needs its observation assembled in exactly the layout its checkpoint was trained on, and getting that wrong does not raise – the robot twitches. Three plugins (g1_locomotion, oli_locomotion, spot_locomotion) each hand-assemble that vector, against two mutually incompatible config schemas (g1.yaml flat, oli/walk_param.yaml nested), so a fourth policy would mean a third bespoke reader.

roqsim.policy makes the layout data: a PolicySpec YAML beside the checkpoint lists the observation terms in order, the actuated joints, the joints that are observed but not commanded, the control gains, and the envelope the policy was trained for. PolicySpec.build_observation then assembles the observation; g1_locomotion’s policy: key runs a policy this way.

It sits in core rather than a robot-family package because every family needs it, and it costs core nothing: it describes checkpoints and never loads them, so it imports only numpy and yaml. Checkpoint loading stays in the family plugins, which is where torch/onnxruntime belong.

Generality is measured, not asserted. The format is tested against the two policies that already ship – the G1’s 47-dim walk observation (with its gait phase) and Spot’s 48-dim Isaac observation (with base linear velocity, which the humanoids do not use) – by rebuilding each from a spec and comparing element-wise with the plugin’s own builder. The bundled G1 walk, Oli and Spot policies keep their own builders: they work and are covered, and swapping a live observation builder would risk a silent regression for no present gain.

Those tests also show that Unitree’s get_gravity_orientation and Isaac Lab’s quat_rotate_inverse(q, [0,0,-1]) are bit-identical (max difference 0 over 500 random quaternions), so one projected_gravity term serves a humanoid and a quadruped alike.

Solver options (sim.solver and friends)

sim carries five optional passthroughs to MuJoCo’s <option>: solver (newton/cg/pgs), iterations, ls_iterations, noslip_iterations and impratio. Each is left at MuJoCo’s default unless a world sets it, because the right value is a property of the experiment, not of the framework: a navigation world wants the cheapest solve that keeps wheels stable, a manipulation world needs contacts that hold.

The values the engine writes onto <option>, and pacing, are checked when the world loads, before anything builds: an unknown solver, integrator or cone name, a gravity or wind that is not three numbers, an iteration count that is not a whole number, a negative impratio, density or viscosity, a timestep that is not positive and a pacing factor that is not a positive number are refused naming the key.

The integrator is sim.integrator. Its default, auto, resolves after every plugin’s build and before compile: to discrete for a model with a flex that has elasticity or passive contact, which MuJoCo refuses to compile under implicit/implicitfast, and to implicitfast for any other model – the one the velocity-servo wheel drives need for stability. The choice and the flex that decided it are logged, recorded in the run’s provenance (world_model.sim.integrator) and printed by roqsim check. A stated integrator is applied at the same point, so neither a plugin nor the world MJCF can set it; a stated sim.timestep likewise wins over theirs.

A flex also constrains the rest of this block, and roqsim refuses the combinations before compile, naming the key to change: a stated implicit/implicitfast (or, for passive contact, any integrator but discrete) with such a flex; solver: pgs or noslip_iterations above 0 with one under discrete (MuJoCo supports neither there – use newton or cg); and a flex declared in a mocap body, which is carried rigidly and never deforms. The rules, and the MuJoCo version they were measured on, are in roqsim.flex. How a flex is written, what else roqsim does for one, and what MuJoCo does with it – numerical damping, contact softness, soft friction – are the Deformable bodies topic of Available plugins.

A grasping world must set ``noslip_iterations``. MuJoCo defaults it to 0, which leaves friction contacts a residual tangential drift. Measured on the G1/Dex1 pick: a 0.5 kg parcel gripped at 20 N between two pads crept out of the jaws at 0.119 m/s and was dropped within two seconds; with noslip_iterations: 10 the creep is 0.0009 m/s and the lift holds indefinitely — a 137× reduction. iterations and ls_iterations alone changed nothing measurable, because this is the solver’s dedicated slip-removal pass rather than general convergence. The failure mode is worth knowing because it presents as insufficient friction and is not: sweeping the sliding coefficient from 0.4 to 3.0 moved the creep rate by 17%, while halving the payload moved it by 80×.

Contact overrides (sim.contact_override, sim.cone, sim.gravity)

Three more <option> passthroughs, added for contact-rich worlds where the contact is the measurement rather than an incidental.

Note

sim.density, sim.viscosity and sim.wind join these passthroughs, added for aerial worlds. MuJoCo defaults the first two to 0 – a vacuum – which is right for a ground robot and wrong for anything that flies: a quadrotor still hovers there, but nothing damps it, so a lateral step rings forever and reads as badly tuned gains rather than as missing air. As world keys they leave an aerial model no reason to pin <option> itself, which would reconfigure every world it was spawned into. wind is inert without a medium, since MuJoCo feeds it into the drag terms.

A multirotor MJCF has no stabiliser either: it exposes thrust and body moments, and nothing holds it level, so an uncommanded drone does not stand still – it falls. Its manifest therefore pulls in whatever stabilises it inside the simulator (crazyflie_2 pulls in quadrotor_controller); an airframe whose stabiliser is an external flight stack pulls in only its motor model (x500 pulls in multirotor_motors) and falls until that stack, a scenario or a publisher drives it.

sim.contact_override sets MuJoCo’s global o_solref / o_solimp / o_friction, which replace every contact’s own parameters:

sim:
  cone: elliptic                # pyramidal (MuJoCo's default) | elliptic
  gravity: [0.0, 0.0, 0.0]
  contact_override:
    solref: [0.02, 1.0]                    # (timeconst, dampratio)
    solimp: [0.9, 0.95, 0.001, 0.5, 2.0]   # (dmin, dmax, width, midpoint, power)
    friction: [0.3, 0.005, 0.0001]         # (slide1, slide2, spin, roll1, roll2)

Which cone. Pyramidal stays the default: it is MuJoCo’s, it is cheaper, and for a base rolling over a floor the direction of the tangential force is incidental. It stops being incidental where that force decides the outcome – a grasp that holds or slips, a pushed part that turns, a package a belt carries, an insertion that reads F_x/F_y – because the pyramid quantises the direction to its facets. Such a world says cone: elliptic; roqsim check warns (friction-cone) when a world with an arm or an object entity leaves the default, and a sweep over the two is an ordinary factor.

They are here for fidelity first. A published model that enables MuJoCo’s global override has to be reproducible as published, and these three are the values such a model states – and often the ones it randomizes, since the flag makes them the only contact parameters in play; without the flag the three have no effect at all. That a sweep over them is then an ordinary experiment factor – needing no bespoke plugin and no hand-edited MJCF per cell, the same reason spawn_model’s mass/friction exist – is the second reason rather than the first.

Global, and before compile; both halves are load-bearing. Per-geom solref/solimp stay in the model. A change aimed at named geoms, during a run, is the model_override plugin (§9.2): this key cannot be aimed – it replaces every contact’s parameters, including the ones a model tuned – and cannot move once the model is built.

Setting any of the three enables MuJoCo’s override flag, and that coupling is why they are one key rather than three. Without the flag MuJoCo ignores all three silently: the model compiles, runs, and quietly uses the untouched defaults, so a world that sets o_solref and observes no effect reads as a solver that does not respond to tuning. Nothing in the resulting model shows the missing flag.

A short vector is padded from MuJoCo’s current value rather than zero-filled, so {solref: [0.05]} varies the contact time constant and leaves the damping ratio alone – which is what sweeping one element means. Unknown keys and over-long vectors are rejected at config load, not at compile: a typo here is otherwise invisible.

The contact time constant has a floor, and the integrator decides where it is. With refsafe on (MuJoCo’s default) MuJoCo raises a stiffer solref to the floor and reports nothing, so a world asking for less gets the floor while its own configuration still reads the tighter value. A time constant below the floor is therefore refused, naming the floor and the rule that applies, because tightening a fit is exactly the reason to reach for this key and a silent clamp turns the attempt into a wrong conclusion about the solver. MuJoCo imposes it in two ways, measured on 4.0:

  • Under euler, rk4, implicit and implicitfast the time constant itself is raised to 2 * sim.timestep. At a 2 ms step a world asking for 0.5 ms, 1 ms or 2 ms gets 4 ms and a contact bit-identical in all three.

  • Under discrete – which sim.integrator: auto picks for a world with an elastic flex – the time constant is left alone and the contact’s stiffness is capped at what the step can resolve, damping ratio kept. As a time constant that is timestep * sqrt(I) / (solimp[1] * dampratio), with I the impedance at the contact’s depth, which runs from solimp[0] to solimp[1]; the floor judged here takes the larger, so a value at or above it runs as stated at every depth. At the default solimp and a damping ratio of 1 that is timestep / sqrt(0.95), about 1.03 steps, and it halves when the damping ratio doubles.

The check runs after every plugin has built and the integrator is resolved, just before compile, and judges the o_solref the override puts in force against the o_solimp it puts in force – stated or kept from the model. roqsim check warns about a flex’s solref below the same floor (flex-solref), and the interpenetration tolerance raises a contact’s time constant to it; all three read roqsim.solref.solref_floor(). To go tighter, lower sim.timestep: the floor scales with it, and halving it roughly doubles the wall time. Only the standard form is a time constant – a negative solref is MuJoCo’s direct (-stiffness, -damping) parameterisation, to which no floor applies, and with refsafe disabled there is none at all.

Worth knowing before tuning for penetration: the floor is not usually what limits a fit. A 5 kg mass resting on a plate at the shipped defaults penetrates on the order of nanometres, four orders below the 0.1 mm a tight assembly cares about. Where a peg sits proud of its bore, measure before reaching for the solver – an arm’s own contact stiffness, and the servo behind it, are the more likely cause.

sim.cone selects the friction cone. Pyramidal is MuJoCo’s default and cheaper; elliptic is the physically correct one and matters when the tangential force is the measurement – an insertion benchmark reads F_x/F_y directly, and a pyramidal cone quantises their direction to the pyramid’s facets.

sim.gravity is a world key rather than a model property because a fixed-base contact experiment often runs at zero g deliberately: a simulated force-torque sensor is not tared, so with gravity on every wrench sample carries a constant tool-weight bias that a force-energy metric is dominated by.

Who ends a run (ctx.request_stop and the scenario)

Under scenario-execution the scenario owns when a run ends: it ends it with emit end after a condition it watches or a sim-time bound, and roqsim never ends a scenario run. A trial plugin that knows it is finished – the goal was reached, the run failed – therefore publishes that as observable state (an endpoint, a blackboard value, an entity that moves) for the scenario to condition on, and holds the robot idle until the scenario ends the run.

For an endpoint, osc.roqsim’s entity_monitor keeps a scenario variable equal to it: the plugin registers its outcome as an out endpoint on the entity it concerns (force_limit’s tripped, a trial plugin’s own resolved), the monitor writes it into the variable every tick, and the scenario waits on the variable, then ends the run, with a timeout as the bound on the trial:

scenario trial:
    timeout(120s)
    var tripped: bool = false
    do parallel:
        entity_monitor(entity: 'ur5e', value: 'force_limit.tripped', target_variable: tripped)
        serial:
            wait tripped == true
            emit end

The report is addressed as the world names it – the entity and the endpoint – and read from the endpoint itself in a stepped run and over the control socket (§13), so one scenario ends the same way on either transport.

The standalone driver, roqsim sim, has no scenario, so a trial run by hand says it is finished with ctx.request_stop(reason): the driver polls ctx.stop_requested and leaves its loop cleanly, so shutdown still runs and files still flush, instead of the world being padded out to a wall-clock --seconds guessed high enough for the slowest cell. The engine itself does not act on the request beyond withdrawing it at reset(), since it belongs to the trial that made it, and the scenario adapter does not read it. Physics-thread only, like every other write on SimContext; the first reason wins.

Actuator overrides (actuators:)

A model ships one set of actuator gains, and they are that model’s own sizing — the ur5e’s servo is softer than the ur10e’s because it is a 5 kg-payload arm. An experiment reproducing a published controller needs its gains, which are a property of the experiment rather than of the robot. Saying so by editing the shared MJCF would leak: every other world that spawns the model silently inherits the edit, and the value that ran is recorded nowhere. actuators: on a spawn plugin (spawn_arm, spawn_robot) states the law and the gains instead, and roqsim/actuators.py rewrites the model’s own actuators to match.

The vocabulary is the robot’s, not MuJoCo’s: control names a ros2_control command interface and the gains are the ones a real controller’s yaml carries, because a port transcribing a paper reads its numbers out of a controller config and a key it has to translate is a key it can get wrong. effort_limit is URDF’s <limit effort=>, which export_urdf already emits from what the joint’s drives can deliver: each actuator’s forcerange times gear, bounded by the joint’s actuatorfrcrange where it has one (roqsim.actuators.joint_force_range). A one-sided range exports its larger bound, since URDF’s effort is a magnitude.

- spawn_arm:
    model: ur5e
    actuators:
      control: impedance       # applies to every actuator this model declares
      stiffness: 2.0           # N*m/rad
      damping: 0.02            # N*m*s/rad
      each:                    # per-actuator, on top of the shared keys
        wrist_3: {control: position, p: 2000, d: 500}

Four laws:

control

commands

gains

compiles to

position

joint position

p, d

gaintype fixed, biastype affine, gainprm [p], biasprm [0, -p, -d]

velocity

joint velocity

d

gaintype fixed, biastype affine, biasprm [0, 0, -d]

effort

joint torque

—

gaintype fixed, biastype none

impedance

joint position

stiffness, damping

the affine form above, its gains named as a compliance controller states them

impedance is not a second spelling of position: it states the joint the way a compliance controller is specified (Franka’s joint_impedance, a UR in force mode), so a paper that gives a stiffness is transcribed without first converting it into somebody’s servo gain.

A modelled drive carries its own weight. A position or impedance joint names hardware whose own loop supplies whatever torque the mass below it demands — a UR5e commanded to a pose holds it — so the bodies it holds up get body_gravcomp. The gain then says how hard the joint resists a disturbance, which is what a gain means on real hardware, rather than doubling as a load rating. Without it the servo trades position error for holding torque and the arm settles below where it was sent: measured on the ur5e at its shipped 2000 N·m/rad, 9 mm at the flange, and metres of arc at a compliance gain. Nothing reports that — the pose is wrong, the model compiles, the run succeeds — which is why it is the default rather than an option.

Which bodies, and why not all of them. A body is compensated when the chain from the world down to it passes such a joint — everything whose weight a drive is holding up. That deliberately excludes the load path to the ground: a mobile base hangs off nothing, and its wheels are driven by velocity, so neither is compensated. The arm bolted to that base is compensated, which is what makes spawn_arm and spawn_robot give the same Panda arm the same physics. velocity is excluded for that reason alone: it is how a wheel is driven, and no bundled arm ships it.

The compensation is a joint torque, so the weight stays on the ground. MuJoCo’s body_gravcomp is an external force, -m·g at each body’s centre of mass, projected onto every degree of freedom above the body — a mobile base’s free joint included. There it is a skyhook: the floor carries the base alone, and wheel loads, traction and tipping come out wrong (on frankie the floor would carry 637 of its 802 N). A real drive holding a link pushes on its mount instead, so the weight reaches the ground through the base. Two mechanisms make roqsim’s compensation that:

  • The drive supplies the term. apply_gravity_compensation sets actuatorgravcomp on every hinge or slide a holding actuator drives. MuJoCo then adds that joint’s rows of qfrc_gravcomp to qfrc_actuator — after the actuator’s own forcerange has clamped actuator_force — and clamps the sum by the joint’s actuatorfrcrange, so a joint without one gets its drive’s (forcerange times gear). A drive too weak for its load sags or stalls, as the hardware does. Either range is therefore the drive’s whole capability, holding torque included, and a model states the rated value rather than one net of gravity (§6.2). A symmetric rating can go on either; a one-sided one (a single-acting cylinder) goes on the joint’s actuatorfrcrange, with the actuator’s forcerange at least as wide, because the actuator’s range clamps the servo before the gravity term is added, so a floor of 0 there cancels the carriage’s weight and it never lowers.

  • The reaction goes into the mount. roqsim.actuators.GravityReaction finds every compensated mechanism that hangs from a moving, uncompensated body (the root) and, between mj_step1 and mj_step2, subtracts the mechanism’s weight at its centre of mass, applied to the root, from qfrc_gravcomp and qfrc_passive. That removes exactly the rows above the root and leaves every row inside the mechanism as MuJoCo computed it. It touches no global (mjcb_passive is one slot per process) and not qfrc_applied. mj_step2 integrates RK4 as Euler, so a world that needs the reaction refuses sim.integrator: rk4. An entity made absent is compensated whole by presence, root included; the reaction then leaves it alone, so it stays frozen.

On a fixed base nothing lies above the mechanism: the engine steps with one mj_step as before, and moving the term from qfrc_passive to qfrc_actuator changes the motion by rounding only, unless a drive’s force limit is below its load.

effort is the other exception: a torque-commanded joint applies the torque it is handed, and supplying the gravity term is the controller’s job — frequently the very thing an experiment is comparing. A drive that really has no gravity term (a hobby servo, a backdrivable joint) is a real machine too; spawn_arm’s gravity_compensation: states either case explicitly, and true there means the whole mechanism, for a controller handed its own gravity term. spawn_robot takes gravity_compensation: false for the same machine; it has no whole-mechanism form, which would compensate the base and lift the robot off its wheels.

A compensated joint still reports its torque. qfrc_actuator carries the holding term of a joint whose drive supplies it; where MuJoCo applies it passively instead — a finger held through a tendon, a model that declares gravcomp itself — roqsim.actuators.joint_effort adds qfrc_gravcomp back. arm_controller’s effort report is that sum, which is what the joint physically carries and what a real drive’s torque sensor reads — it matches an uncompensated arm’s reading in the same pose. In a world at zero gravity every one of these coincides, and a reader should not conclude the mode did nothing.

A gripper’s finger servo is the one non-joint actuator a world can restate. Every bundled gripper drives its fingers with a position servo: on a joint (the Interbotix arms, TIAGo Pro, the AgiBot G2), which each: restates like any other, or on a tendon (the Franka Hand of panda and frankie, the Robotiq 2F-85 and the gen3 it is part of, the Robotiq Hand-E, the Schunk PG70, the G1’s Dex1), which each: restates with p and d alone: the tendon has no joint law, and its command and force ranges are the gripper’s interface, which arm_controller maps commands onto. p is the servo’s stiffness on the tendon’s length (N/m over slide joints) and d its damping; both must be positive. A servo whose command is scaled (the Franka Hand’s and the Robotiq’s 0..255) keeps its scale, so gainprm is rescaled with p and a command still closes the fingers to the same width; the table records the stiffness, not that gain. The shared keys never fall on a tendon, and a block that states them without naming the finger servo is refused, naming the entry to write. A gripper welded on with end_effector: is a model of its own, so its servo is named under end_effector.actuators – the same block, resolved on the gripper’s spec before the graft – and its rows join the arm’s in the table.

Where each half is applied, and why they differ. The actuator rewrite runs on the child MjSpec right after apply_assets and before an end effector is grafted on: actuators: names the actuators this model declares, and the graft puts a gripper’s tendon actuator into the same spec, so a shared control: resolved after it would fall on a tendon — which has no joint stiffness — and refuse a block whose gains were only ever about the arm. The gravity-compensation half runs after the graft, for the opposite reason: body_gravcomp is per body and does not cascade, so an arm compensated before its tool was attached would sag by exactly the tool’s weight. Compensating the tool is also the right physics — a real controller is told its payload and holds that too. Both run before spec.attach, so the whole thing is pre-compile and the file on disk is never touched; a world that declares nothing compiles a byte-identical model.

The block is declared once, as roqsim.actuators.ACTUATORS, and both spawn plugins put it in their CONFIG_SCHEMA: the shared keys are a block of fixed keys, and each: is a mapping from actuator names to blocks of the same keys (Field(dict, values=...)), so roqsim plugins describe publishes it and the schema check refuses an unknown key by its full path (actuators.each.wrist_3.stifness). Refusals name their replacement: MuJoCo’s own spellings (kp, kv, kd, forcerange) and its actuator types (motor, pd) are unknown keys and values like any other, refused in one error that carries the replacement as the declaration’s hint, and never read. Keys under each: are actuator names; a joint name is refused naming the actuator that drives it, rather than resolved silently, so a reader of someone else’s world can tell what a key is without opening the MJCF. roqsim catalog model <model> lists the names.

A shape error (an unknown key, a gain the chosen law does not read) is found by the schema check and validate_config at roqsim check’s config stage, before anything is compiled. Anything needing the model — an unknown actuator, a joint name, a tendon, a finger servo’s key or non-positive gain, a missing ctrlrange — is raised in build() and lands at the build stage. That split is a contract rather than a detail: an external validator that checks a world before spending compute on it does so by compiling — roqsim scenes describe --entities is that call — so both kinds of mistake reach its author rather than a trial. ctrlrange is required only when the command unit changes (rad ↔ rad/s ↔ N·m); position → impedance keeps the unit, so the model’s own ctrlrange stays correct and is not refused.

The resolved table — every actuator, its final law and gains, and whether each value came from the model or the world — is published on SimContext.actuator_tables at configure and written into the run’s provenance beside world_model (capture.py). It carries every actuator rather than only the changed ones, because “what did this joint run under” is a question about the run and not about the diff. A block writes what it changes and nothing more: a control other than the model’s writes the whole law, a gain under the model’s control only the terms it governs, and an entry that restates the model’s own values (each: {fingers: {}}, control: position on a position servo, limits equal to the model’s) changes nothing — the actuator is left as the model has it, whatever form its law takes, and its row says source: model. An each: entry is credited only for what it changes beyond the shared keys; one restating them is recorded as shared, and as the model’s when neither changes anything. The addition needs no FORMAT_VERSION bump: Recording reads world_model by name and ignores keys it does not know.

Not part of this: spawn_arm’s rail: {kp, damping}. That parameterises a carriage drive roqsim synthesises, where actuators: overrides actuators a model declares.

Asset de-duplication (sim.dedup_assets)

spec.attach deep-copies a child model’s meshes, textures, and materials under a unique prefix, with no sharing — so a world that spawns N copies of one prop carries N copies of its assets, and spec.compile() parses every OBJ, decodes every PNG, and builds a convex hull for each. Between the build loop and compile the engine runs a de-duplication pass (roqsim/assets.py, on by default; sim.dedup_assets: false opts out) that merges byte-identical file-backed meshes and materials and drops the textures left unreferenced. It keys on the resolved absolute file path (sound because apply_assets already absolutized every ref) plus the attributes that change compiled output, and retargets references onto the survivor. It rewrites only the name-string references (geom.meshname, .material on geoms/sites/meshes/skins) that survive attach — a material’s texture-role vector is immutable once attached, so identical materials are merged rather than repointing textures directly. Builtin/procedural assets and non-2D textures (skyboxes, cube maps) are never touched. On a world spawning 240 identical trays this takes compile from ~2.5 s to ~0.15 s and texture RAM from ~930 MB to ~60 MB; the --profile load report shows it as the dedup_assets phase.

Model plugin manifests (expand)

A model bundles the plugins intrinsic to it (a mobile base → diff_drive + lidar; an arm → arm_controller) in a <model>.manifest.yaml manifest next to its MJCF, so a world only spawns the model instead of re-declaring them. Mechanism:

  • Before instantiation, expand_document (config.py) resolves each plugin class and calls its expand(spec, world, base_dir) classmethod, splicing the returned specs in immediately after the plugin that produced them (so a spawn’s controller/sensors land before a later ros2_bridge that reads their endpoints). world is every spec declared or injected so far; core does no dedupe of its own.

  • Expansion is recursive and depth-first. Each returned spec is expanded in turn, so a robot manifest can mount a device model (spawn_sensor) whose own manifest brings its capture plugin. Build order stays the document’s shape: robot, its first component, the mounted device, the device’s components, the robot’s next component.

    • An injected spec whose owner has not been placed yet waits for that owner and follows it. This happens when a robot manifest nests an override under a device the world declares itself. A carrier therefore always builds before what it carries.

    • A chain that reaches the same model file twice is refused, naming the chain. So is one that nests deeper than eight expansions.

    • Ownership is the full address. An injected spec’s entity is its producer’s address (robot.scan_front), so _as_tree, overrides (components.robot.scan_front.lidar.rays), enabled cascades and the run record all work at any depth. Two robots each mounting a scan_front never collide.

    • A late override of an expansion input is refused. A component a manifest injected is first addressable after it has expanded. An override of a key its expand reads (the plugin’s expansion_keys: model, prefix, frame_id, …) would leave what it brought in built from the old value, so it is refused. Declaring that component in the world, nested under its carrier, lands the value before expansion.

  • Expansion runs while the document loads, not inside the engine, so SimConfig.plugins is the effective component list – what the document declares plus what its models’ manifests contribute – in build order. SimConfig.declared keeps the entries a reader actually wrote. That is what lets a consumer see what will run: roqsim scenes describe can name a sensor the document never declared, and world_sources sees a manifest-supplied component’s files – a prop_trajectory’s CSV among them, resolved against the world’s directory rather than the caller’s.

  • A run records the components that ran, and a recording is rebuilt by reading them. The provenance carries the resolved tree and the sim block beside the recipe (the world reference and the override document, which stay because they are what a reader needs to see how the run was asked for, and what an external consumer uses as world identity). Replay does not re-run the load path, so no later change to how an override resolves can make a recording rebuild a different world while looking correct. format_version is read: a record of any other version is refused by name rather than partly understood.

  • Loading stays tolerant; running does not. A ref that will not import is recorded on SimConfig.unresolved and its entry is kept, unexpanded, so a scene-only consumer (roqsim render, the exporters, describe) still gets a world whose transport is not installed. instantiate_plugins is where that is refused, with the full unresolved-plugin report – including the case that says a world failed solely on its bridges and names the two ways on. Dropping the transport prunes the matching deferred failures, or a consumer would remove the bridge it cannot import and be refused for it anyway.

  • Spawn plugins implement expand in one line via the shared roqsim.manifest.expand_manifest(spec, world, *, base_dir=None, substitutions=None) (substitutions fills a device manifest’s {frame_id}/{parent_frame}). It resolves the model (see Model discovery below), reads the <model>.manifest.yaml beside the resolved file, and injects each entry as a component of the spawn. There is no per-family wiring key: an entry belongs to the entity whose entry it sits under, so a mobile spawn and an arm spawn wire their components identically. Distinct entities (two arms) never collide.

  • A manifest entry that itself provides an entity (a spawn_sensor in a robot manifest) gets the spawn’s prefix as attach_prefix rather than prefix, and derives its own from that. Its nested components: are kept, owned by its address and merged by label like everything else. Precedence is nearer-wins all the way down: the world’s value, then the robot manifest’s, then the device manifest’s.

    • A mounted device’s prefix defaults to <carrier prefix><label>_, and its namespace to the carrier’s.

    • A device model’s mount body is the frame its vendor macro’s origin places: the link the macro attaches to its parent. A mount’s pose is that origin, so a pose copied from a robot description’s call of the macro places the device where robot_state_publisher would, and the manifest’s frames: chain starts at that frame.

    • A device manifest may use {frame_id}, {device_name} and {parent_frame} placeholders, and no others.

    • {device_name} is the mount’s device_name, else the manifest’s top-level device_name: (the vendor macro’s default name parameter, which prefixes every link it creates; roqsim.manifest.manifest_device_name).

    • {frame_id} is the mount’s frame_id, else the manifest’s top-level frame_id: (the vendor’s default scan-frame name, roqsim.manifest.manifest_frame_id), which may itself carry {device_name}. A device whose vendor names none declares none, and a mount of it without a frame_id is refused rather than given a made-up name.

    • Two mounts on one carrier that would publish any one frame name – the scan frame or any link of the chain – are refused, since they share its namespace; each names its own device_name or frame_id. A carrier mount of a device that declares no frames: is refused, naming the device: it has no vendor frame to hang from.

    • Vendor fixed links a model flattened are a frames: block (roqsim.frames): {name, parent, pose}, the pose an offset from parent read by roqsim.pose.parse_pose with relative=True (omitted components are zero). It is built as sites and published as static transforms. Unlike components, it is not inherited through extends:: frames describe a model’s geometry.

    • A carrier’s devices hang from its frames: a nested spawn_sensor names as its parent_frame the link the vendor description attaches it to – a body of the carrier or an entry of its frames: – and its pose is that joint’s origin, an offset from the frame, which is how a world or an override moves a device. roqsim.manifest.resolve_parent_frame refuses, while the document expands, a parent_frame the carrier does not have (with a did-you-mean and its frames listed), a frame whose parent is neither a body nor a frame declared before it, and two frames of one name. The spawn_sensor and spawn_robot docstrings (docs/plugins.rst) have the details.

  • When the owner already declares a component with the same label (its name:, else its plugin ref), the manifest default is not injected — the world’s entry is the one that runs — but the manifest’s config is merged underneath it: per key, the world’s value wins and missing keys are filled from the manifest. This is what makes a partial override work (a nested diff_drive: {test_cmd: [...]} adds a scripted command and keeps the model’s wheel geometry and actuator names). Keying on the label rather than the ref is load-bearing: a model may ship two of a kind (tiago_pro’s front and rear lidars), and keying on the ref would collapse them onto one entry and silently lose a sensor. The merge is shallow on purpose: a nested value the world sets replaces the manifest’s whole mapping rather than being deep-merged. The world’s spec is mutated in place, which is safe because plugins are constructed only after expansion completes — so declaration order does not matter.

    Note

    Skipping the manifest entry whole instead of merging under it would make a partial override fall back to the plugin’s generic defaults for everything the world does not restate — a Husky’s diff_drive inheriting TurtleBot wheel radius and actuator names, then failing to resolve them against its own MJCF. If you rely on a world entry starting from the plugin’s defaults rather than the model’s, use default_plugins: false and declare it fully.

  • Opt out per spawn with default_plugins: false; a model with no manifest yields nothing.

Any new spawn plugin reuses this by returning expand_manifest(spec, world, base_dir=base_dir) from its expand; ownership comes from the spec’s address, so there is no key to pass.

Model discovery (roqsim.models)

A spawn plugin’s model: string is resolved by roqsim.models.resolve_model, which mirrors plugin resolution (roqsim.registry) so a model may live in any installed package — not just the spawn plugin’s own:

  • Short name (ur10e, turtlebot4, conveyor) — searched across every package that registers a provider in the roqsim.models entry-point group. The caller need not know which package ships it.

  • Package-qualified <package>:<model> (roqsim_manipulation_assets:ur10e) — resolved within that provider; use it to disambiguate a name shipped by two packages, or to self-document a dependency. A dotted module:name exposing MODELS_DIR also works for models outside the group.

  • Filesystem path (absolute, or relative to base_dir) — loaded directly.

resolve_model returns a ModelAsset(path, meshdirs, texturedirs). Crucially, the asset dirs follow the model to its own package (a provider exposes MODELS_DIR and optionally MESHES_DIR/TEXTUREDIR): a spawn plugin calls apply_assets to rewrite the child spec’s mesh/texture refs to absolute paths found across those dirs, so it does not force its own package’s meshdir onto a foreign model — which would make a cross-package model impossible. A model that reuses other packages’ meshes adds an assets: key to its <model>.manifest.yaml naming the provider(s) to borrow from — a single name or a list. Search order: the model’s own declared meshdir always comes first — its assets can never be shadowed by same-named files elsewhere (Menagerie-style link names recur across robots, e.g. the Oli and the G1 both ship a left_hip_yaw_link.STL) — then the borrowed providers in order, then the provider default and the model file’s dir. Since MuJoCo allows only one meshdir per model, resolving to absolute paths is what lets meshes from several packages coexist. A package registers its models with:

[project.entry-points."roqsim.models"]
roqsim_assets = "roqsim_assets.models"   # a module exposing MODELS_DIR

Example: a downstream package can ship only a custom arm variant — say ur10e_custom.xml + ur10e_custom.manifest.yaml, no mesh copies — whose manifest assets: [roqsim_manipulation_assets, roqsim_sensors] borrows the stock arm meshes from one package and a camera mesh from another. spawn_arm: {model: ur10e_custom} then places it even though spawn_arm lives in a third package, roqsim_manipulation — which ships no models at all.

5. Plugin-type catalog

Types are roles (which hooks you implement), not separate base classes:

  • Scene/init (build): floorplan/environment, spawn robot/arm, pedestrians, conveyor geometry.

  • Controller (pre_step): diff-drive (cmd_vel), arm trajectory, conveyor velocity, ped ORCA.

  • Sensor (post_step, maybe render): lidar (mj_multiRay, no GL), camera (RGB-D, GL), IMU.

  • Transport/bridge (configure+pre/post_step+shutdown): ROS 2 bridge, simulation_interfaces.

  • Recording/observability (post_step): metrics/CSV (a task plugin’s own series). Recording MuJoCo state is not a plugin — it is the driver’s --record (see Recording a run).

  • Render (future): viewer overlays, debug markers.

  • Perturbation: a sensor’s own noise config, switchable mid-run through its fault: block (§9.1), or model_override changing a named model value mid-run on an external trigger (§9.2). There is no shared error-model framework, on purpose (§9.1).

DummyPlugin (plugins/dummy.py) is a minimal end-to-end example implementing every hook.

Machines and scenarios

Two roles are easy to confuse, and a world that confuses them puts decisions where nobody looks for them. The line between them is the same in the code, the docs and the examples.

A machine is one entity’s own procedures. What the entity can do by itself – move its actuators, run its programs, be in its states – offered through its handle. A machine acts only on itself and on what it physically works on: the part in its tool, through that part’s handle. It decides nothing about other entities: it does not wait for a robot, it does not open because someone is near, it does not stop a belt.

A scenario is the scene. Which entities act when, who waits for whom, what a presence or an event leads to, the order of the work. It drives entities only through their handles, and is written either as OpenSCENARIO run by scenario-execution, or in Python.

machine

scenario

a press strokes with its guard door interlocked

✔

a robot loads the press, then starts it

✔

a door opens and closes, ramped, and gives up on an obstruction

✔

a door opens because a walker comes near

✔

a belt runs at a speed and stops

✔

a belt stops while a part is in a light barrier

✔

a part shows its hole when the ram reaches the bottom

✔ (through the part’s handle)

a worker grips a drawer’s handle and pulls it 0.3 m

✔ (the humanoid’s move)

a worker pulls the drawer because the robot reported the box full

✔

The test when in doubt: would the machine do it standing alone in an empty world? Then it is the machine’s. If it needs another entity’s state to decide, it is a scenario’s. A world places a machine and sets its parameters (rates, home – where it stands at the start, the only place that is stated –, sizes); it carries no machine programs, since a machine’s behaviour is its package’s code.

A machine subclasses roqsim.machine.MachinePlugin. It declares the position actuators it drives (ACTUATORS), plugin-owned quantities that ramp the same way (SETPOINTS, a belt’s speed), where they stand after a reset (HOME, a world’s home: over it), and its programs: generator methods marked @program, each yield one physics step on simulated time. A program moves an actuator at once or ramped at a stated speed in the joint’s unit per second – the ramp moves the target, the physics moves the joint – and waits until a condition holds, until actuators have reached their targets or stopped on them (what an interlock waits for), or for a time. Programs advance in post_step, ramps in pre_step.

Every machine has one handle, a MachineHandle under machine:<name> (a subclass of it, with a method per program, where the machine’s HANDLE_CLASS names one), and it is the contract for everything that starts something and is waited on:

  • start(program, **args) -> seq: checked at the call – an unknown program or argument, or a machine that is busy, raises naming the machine – stamped with the next sequence number, and applied on the physics thread at the next step. Safe from any thread: starts and cancels reach the physics thread in the order they were made, and a status never goes back to an older start.

  • status() -> MachineStatus(seq, program, finished, error): the last start. A caller knows its own start ended when seq is its number and finished is set; error is empty for done, else the failure, cancelled, or the exception. A larger seq means another start followed.

  • cancel(seq=..., token=...) -> seq: one start, pending or running, ends and the machine stops where it is – start seq, or the start given that token (start(program, token=...), a string of the caller’s own); 0 when that start has ended, is being cancelled already, or the machine has no such start. A caller cancels its own start, so a start another caller made is left alone: by its number once it has it, by its token before. cancel() with neither ends whatever is pending or runs. Cancels are posted in order with the starts, so a cancel by token sent right behind its start reaches it.

  • busy (a start pending or a program running), ready (not busy, and the machine’s own precondition), value(name) (an actuator’s or setpoint’s current target), goal(name) (where it is going: the end of its ramp, else its current target).

The navigator’s route handle (roqsim_nav.handle: send_goals, cancel, status) is the special case of it. A reset drops any program and puts the machine at home; sequence numbers keep counting, so a stale one never matches.

Every step is an event on ctx.events: program_start (program, seq, args), each step a program names, and program_end (with its error), so a recording carries each machine’s timeline. The handle’s start, status and cancel are also endpoints of the machine’s entity, so the control socket reaches them under <machine>/start and the same names.

Fail loudly. A program ends with self.fail(reason) when its own outcome is a failure (a door stalled on an obstruction): the error is in status() and the run goes on, for the caller to decide. So does a program that sends an actuator outside its range, and one whose joint has not arrived MOVE_TIMEOUT seconds (5 s unless the machine sets another; move, until_reached and until_stopped each take a timeout) after its target did. A program that raises anything else is a defect: by default (on_error: raise) the run stops naming the machine and the program; on_error: report puts it into status() instead. A program that ended in an error, or was cancelled, stops the machine where it is: each actuator is held where its joint stands, with the servo’s standing offset under its load kept, so an obstructed joint does not move on by itself once the obstacle is gone and a loaded one does not sink at each hold. A handle a machine needs (NEEDS) that nothing published is refused at reset, naming the key, and a NEEDS name the machine already has is refused when the world loads. An actuator a machine drives is a plain position servo – fixed gain, an affine bias whose stiffness matches it, a unit gear, no dynamics that integrate its control – so its control is the joint’s target; a motor, a velocity servo, an <intvelocity> or a geared servo is refused at configure.

How a package provides its machine. A machine that builds its model from its config is a plugin registered under roqsim.plugins, as door and conveyor are, and a world places it by name. A machine with an MJCF model of its own is placed by spawn_model, with its controller nested under that entry – a MachinePlugin with no build that sets registers_entity = False, so its ACTUATORS resolve under the spawned entity’s prefix and its handle is published under the spawned entity’s name:

- spawn_model: {model: my_press, prefix: press_1_}
  name: press_1
  components:
    - my_press_controller: {}

spawn_model does not read a model’s manifest, so the controller is written in the world (or in a world the cell extends), not in the model’s manifest.

What a machine works on has states of its own. part_state shows and hides an entity’s look_<name> bodies through roqsim.presence – a strip punched, bent, labelled; a machine’s own lamp on – each look with its own inertia where the model names one, through one handle (part_state), with an event per change. A press shows the hole at its stroke’s bottom through that handle: the part’s state is the part’s, and the machine only asks for it to change.

A humanoid’s moves are one entity’s procedures, as a machine’s programs are. approach, reach, press, grasp, release, pull, push, carry, place and plan (the way a carry would walk, planned and not walked) are what a humanoid does by itself: the humanoid plugin (roqsim_motion), nested under a walker with hands: true, is a MachinePlugin whose programs are its moves, so a move is started through the same handle (machine:<name>, and humanoid:<name> with a method per move), waited on by the same status and recorded as the same events. Which moves a worker makes, in which order and for what – swap a box when it is empty, press the button when the press is ready – is a scenario’s. A move never decides what comes next; one that cannot be done fails with the reason in its status, and the humanoid stands where it left off, a hold still held.

Presence is reported, never acted on. zone_trigger is a box in the world or riding on a body that reports the entities entering, dwelling for a time and leaving, filtered by name pattern: as events, on a handle (zone:<address>) and as an occupied endpoint. It decides nothing; a door that opens for whoever comes near is a scenario reading the zone and starting the door.

A Python scenario subclasses roqsim.scenario.ScenarioPlugin and writes program(), a generator on simulated time, one yield per physics step, advanced in post_step. It names the handles it drives in NEEDS ({"press": "machine:press_1"}), resolved at every reset and refused by name when missing; a world may rename them (needs:), so one scenario serves two cells. It owns no model and writes no actuator. Its helper: yield from self.run(handle, program, **args) starts a program and waits for that start, raising with the machine’s error; self.start(...) and self.spawn(gen) run tasks beside the program, join and first wait on them, and a start’s error reaches whoever joins it, where a try catches it as around run (one nobody joined stops the run when the scene ends, and the scene does not end before a task has, unless it was spawned as background); self.navigate(nav, poses) sends a mover through its navigator’s handle (nav:<name>:handle, a walker’s as a robot’s) and waits on its route’s number; until, wait and event do what they say, and set_entity_state puts an entity at a pose as a world file writes one (a missing z is the floor), refusing anything else by name. Tasks advance in the order they were created, so a scene is as deterministic as the machines it drives. A world declares a scenario after the machines it drives; a start it makes is applied at the next step whatever the order.

A program that raises stops the run with its own exception, and the scene never reports done. When program has returned and every task but a background one has ended, the scenario emits scenario_end and its done endpoint turns true, which an OpenSCENARIO entity_monitor can wait on; stop_at_end: true also ends a standalone roqsim sim run (ctx.request_stop). It never ends a scenario-execution run (§4, Who ends a run).

6. Porting playbook

The incoming codebase is monolithic MuJoCo scripts. Rework them into plugins as follows.

6.1 Decision tree — “code that does X → hook Y”

The old code…

→ hook

Notes

builds/edits the model XML, adds bodies, meshes, sensors

build(spec)

use MjSpec; runs before compile

looks up model.body(...)/site/actuator ids; opens files/sockets/nodes

configure

model exists here

sets data.ctrl, data.qfrc_applied, mocap poses each step

pre_step

the only place to write actuation

reads data.qpos/sensordata, renders, publishes, logs

post_step

read-only w.r.t. the sim

re-homes/reseeds state at run start

on_reset

after mj_resetData

closes resources

shutdown

reverse order

receives async input (ROS cb, socket, GUI)

wrap in ctx.post(cmd)

never touch data off-thread (§7)

6.2 Recipes

  • New robot / arm: a scene plugin whose build attaches the robot MJCF into spec (spec.attach / add body), registers an Entity(kind="robot") and a RobotHandle in configure.

    Its drives hold its weight, bounded by their force limits. Spawned through spawn_arm or spawn_robot, every body a position or impedance drive holds up is gravity-compensated with no config, and the term is a torque that drive supplies (§4, Actuator overrides): the floor carries a mobile robot’s whole weight, and a joint’s total torque, gravity included, is clamped by its actuatorfrcrange, else by its actuator’s forcerange times gear. That makes them the drive’s total limit: state the real motor or cylinder rating (URDF <limit effort=>, a datasheet’s rated torque or force), never a value net of the load’s weight. A range trimmed to leave room for a weight the drive was not carrying – -2000 23000 for a 25 kN cylinder under a 2 kN carriage – now takes that weight off twice. A symmetric range on the actuator is the common case; a single-acting cylinder’s one-sided 0 25000 goes on the joint’s actuatorfrcrange instead, with the actuator’s forcerange left at least as wide, since the actuator’s range clamps the servo before the gravity term is added and a floor of 0 there leaves the carriage weightless, unable to lower. The rating has to cover the mechanism’s own weight at full reach plus its rated payload; a placeholder too small for that makes the joint sag under its own links, and an unset one makes the drive infinitely strong. gravity_compensation: false on the spawn is for drives that supply no gravity term at all (a hobby servo, a backdrivable joint), not a fix for a sagging joint.

  • New sensor: a post_step plugin that reads data (or renders via ctx.render), optionally adds its own noise (§9), and hands the reading off (blackboard/bridge). Register a producer gate (§10) if it should participate in sync mode.

  • New controller: a pre_step plugin that consumes a target (from blackboard / ctx.post) and writes data.ctrl. Expose a RobotHandle so a bridge can command it. It must honour ctx.manual_control (§7): when set, the human owns data.ctrl for the run — return from pre_step without writing it, so the viewer’s control sliders drive the actuators. Writing ctrl once in on_reset stays right, and a controller should do it in every mode: a reset zeroes data.ctrl, so until the controller writes the commands that hold its pose, the state the engine’s closing mj_forward derives – and anything a sensor reads or tares before the first step – is the robot pulled toward zero. In manual mode the same write opens the sliders at the home pose; the rule is about the per-tick write. This is what the runner’s --manual-control switches, world-wide, for every controller at once — hence a run-level flag rather than per-plugin config.

  • Environment/floorplan loader: a build plugin that adds a mesh + collision geoms to spec.

  • External transport (ROS/other): a transport plugin — configure spins the client thread, callbacks ctx.post(...), post_step publishes from data, shutdown stops the client.

  • Moving part (conveyor): build adds an invisible belt body on a slide joint; pre_step forces its velocity and wraps position; a contact pair tunes belt↔object friction. Its speed is a machine’s setpoint (Machines and scenarios): the run(speed) and stop() programs ramp it, and stopping for a part is a scenario’s.

  • Injected fault (model_override): a plugin that in configure resolves a named selection of geoms/bodies/actuators, saves their current values and publishes a handle plus a std_srvs/SetBool service endpoint; set_active writes the target rows and on_reset writes them back. No pre_step at all – the change rides on the service’s override command, which runs on the physics thread, and post_step runs only on the step after a change, to check the fault actually landed (§9.2).

  • Articulated + commandable prop (door): the door plugin (roqsim_assets) is a machine (Machines and scenarios) — build hangs a leaf on a hinge joint with a force-limited position actuator; its programs open, close and move_to(openness) move the target, ramped at speed where a world states one, end when the leaf first comes within 0.02 of the openness (it may still settle by a few hundredths after that), and end with an error when the leaf stays blocked behind its target (a gentle automatic door that gives up), and an idle door held off its target gives way after stall_timeout; configure registers Entity(kind="door"), its machine:<name> handle and its openness reader machine:<name>:openness, and — when controllable — std_msgs/Float64 openness/openness_state endpoints plus a control_msgs/GripperCommand action openness_goal (reusing the generic 1-DOF handler via its state_key hint, machine:<name>:openness; its reach_tolerance hint, the 0.02 its programs end in, grades reached_goal, and on_timeout: abort aborts a goal still moving past the door’s own timeout, where a gripper’s comes back succeeded). The natural home for a door in a floorplan world is the opening the generator already cut (floorplan_to_world.py --doors-map).

6.3 Decomposition guidance

Split one big feature into cooperating plugins that talk through the blackboard/entity registry, not direct imports. Example: a monolithic “robot + lidar + ROS” script → spawn_robot (build) + diff_drive (control, publishes RobotHandle) + lidar (sensor) + ros2_bridge (transport, looks up the handle). Each is independently testable and reorderable in YAML.

6.4 Worked example [planned — filled when the first real feature is ported]

Will show a concrete before (monolithic script) → after (plugins + world YAML), step by step.

7. Concurrency & threading model

Who commands an arm. arm_controller is the only writer of an arm’s actuators, and that write is the hardware: it never stops, or the joints would fall. What switches is its trajectory role. A Cartesian controller does not write ctrl; it computes joint targets that the arm pulls once per step, stamped with the step it ran for, so whichever of the two reaches that point first does the work and declaration order cannot decide whether a command lands this step or the next. One command source per arm; a second is refused naming both.

roqsim.controllers holds the single source of truth for every controller’s name, type, lifecycle state and claims – transport-free, because those are facts about the robot. A plugin asks it whether it is active, the bridge serves controller_manager_msgs out of it, and a task plugin switches through it. Its scope is the robot: two arms may each have a controller of one name, as two real robots do, and claims are compared within a robot because joint names are unprefixed and identical across arms.

Single-writer rule: only the physics thread (the one calling engine.step()) ever touches model/data. This is non-negotiable — MjData is not thread-safe.

External input (ROS callbacks, simulation_interfaces services, GUI) must not mutate data directly. It enqueues a callable via ctx.post(cmd); the engine drains the queue at the start of ``pre_step``, so every mutation happens on the physics thread, in FIFO order, deterministically. A driver that is not stepping – roqsim sim paused or stopped – drains it in its idle loop instead (Engine.idle), and when a command ran, mj_forward brings body poses and sensor data in line with it; simulated time does not advance and no plugin hook runs. ctx.post is the substrate the ROS bridge and synchronous mode (§10) build on; ctx.submit is the same queue with a CommandFuture for a caller that needs the outcome, and the drain delivers a command’s exception to the caller waiting on it (one nobody waits on is logged). The queue is a collections.deque: posting and draining take no lock. After the commands the drain applies each inbound stream’s latest value (§13).

The control socket’s threads (§13) follow the same rule: its request threads never touch data – a read or a call is submitted to the physics thread and waited on – and what it publishes is read in post_step. Calls are submitted in the order their requests arrived, though several threads answer them. The runner resets its pacer on every idle loop, so the first step after a pause is paced from when it is taken and the pause is not counted as falling behind.

For readers on other threads, the engine publishes an immutable snapshot after each step (publish_snapshot/read_snapshot). The default path, though, is to read in post_step on the physics thread — no snapshot needed.

reset/shutdown drain/flush the queue so no command targets a half-rebuilt model.

Anti-patterns (do not do)

  • ❌ Mutating ctx.data from a ROS callback / worker thread. Use ctx.post.

  • ❌ Recompiling the model mid-run. Modify spec only in build; at runtime use mocap/qpos writes, roqsim.presence to make a compiled entity appear and disappear, or the model_override plugin to change a named model value (§9.2). Those three are not recompiles: they write fields the compiled model already has, and put back exactly what they found.

  • ❌ Blocking inside pre_step/post_step waiting on external I/O (except deliberately in sync mode).

  • ❌ Plugin importing another plugin. Cooperate via the blackboard/entity registry.

8. Rendering

Every image roqsim draws comes through one RenderService (roqsim.rendering), and every renderer stands behind one contract (roqsim.render_api). The user-facing side – choosing a renderer, its settings, the two modes – is Choosing a renderer; this is how it works.

  • Lidar uses mujoco.mj_multiRay — no GL, works headless everywhere (nav2 needs a LaserScan).

  • A renderer is an extension. It registers under the roqsim.renderers entry-point group, or is named module:Class / file.py:Class, resolved as plugins are (§12, roqsim.registry.resolve_renderer()); the core names none. MuJoCo’s own, MujocoRenderer, registers there as mujoco and is the default; FilamentRenderer registers as filament (below); SocketRenderer (socket) is the client of a renderer in another process, with TCP_NODELAY on both ends of a TCP connection, since a message is several writes. A package for one server subclasses it: it starts that server, sends the scene in the form the server reads (scene_blobs), and declares what it draws. A world chooses with sim.renderer, a camera may name its own with renderer:, --renderer is --set sim.renderer= as a flag, and a renderer’s settings are its block sim.renderers.<name>, validated by its validate_config at load.

  • The contract (Renderer): open(scene) once with a SceneDescription – the compiled model (read-only), which bodies move, the cameras it will be asked for, its settings; then render(snapshot, requests) per tick with a StateSnapshot (sim time, every body’s pose, the model values presence changes at run time, and for an in-process renderer a copy of MjData) and a batch of CameraRequest (camera, images asked for, world pose, field of view; the camera carries the intrinsics MuJoCo projects it with, roqsim.rendering.camera_intrinsics()), answered with one Frame per request stamped with the snapshot’s sim time; close(). Nothing in it assumes a GL context or the renderer’s process. What a renderer can give is declared on its class (RendererCapabilities: images, camera models, whether it composes moving bodies, draws the static world, renders a batch at once, is deterministic, runs in-process, draws decorations, draws only the geom groups a camera names, projects an off-centre principal point, projects non-square pixels, draws the moving bodies alone, draws a posed camera: one with no camera of the model, drawn at the pose and intrinsics of its request), and RenderService.check() holds every camera to it when the world loads: a camera a renderer cannot serve fails the load naming both, and nothing falls back to MuJoCo’s renderer. Every frame a renderer returns is held to its request: its camera, its snapshot’s sim time and step, and each image’s size and type (render_api.IMAGE_FORMATS); any other fails the tick naming both.

  • Per tick. The engine builds one service at setup, before configure, where each camera registers a RenderView per pass (colour, plus the depth camera of a device whose depth has optics of its own) with its own gate as the view’s wants. Between mj_step and post_step the engine calls RenderService.tick(): every view is asked whether it is due, one snapshot is taken, and the due views go to their renderers as one batch each; a camera’s post_step then turns its frame into its streams. Cameras render only when consumed (lazy), and their expensive endpoints are not published to nobody either: image, image_compressed, depth, depth_compressed, registered_depth and points set Endpoint.lazy, so a subscriber-less stream costs neither a draw nor a serialisation, and a camera nobody reads is in no batch – a world whose cameras nobody reads opens no GL context. The two checks answer different questions — the render gate ORs over every endpoint one pass feeds, the publish gate is per-endpoint — so a consumer of the compressed topic alone still gets frames, and a consumer of the raw topic alone does not pay for the JPEG (or, for depth published as 16UC1, for the RVL of its compressedDepth companion – an order dearer than the JPEG, since RVL has no C library behind it).

  • Two modes (sim.render.mode). sync, the default, draws on the physics thread and the tick waits for its frames: deterministic, and what lockstep (§10) requires – a world with sim.sync.enabled cannot ask for async. async gives each renderer a worker thread that opens, drives and closes it (a GL context is thread-affine) and draws its own copy of the model, updated from each snapshot; the physics thread hands it the batch and steps on. A slot of one: a batch posted while another waits replaces it (newest wins, the replaced ones counted as dropped), so nothing queues, and a frame is stamped with its snapshot’s time, a tick or more before the one that publishes it; its noise is drawn at that time (ctx.rng_for(..., at=)), so an async frame is the sync frame of its stamp. A worker whose renderer failed raises on the physics thread at the next tick, and a worker that does not open or draw a batch a caller waits for within sim.render.timeout_s is named as hung (opening waits for the renderer’s own open_timeout_s where that is longer: a renderer slow to start). sim.render.workers deals each renderer’s cameras to that many instances (a context each; a thread each in async), one camera’s views together (a view’s group), so its passes of one snapshot arrive as one – the seam a second GPU or process goes behind, which no camera plugin sees.

  • MuJoCo’s renderer holds one MjrContext and one upload per instance, whatever the camera count, and sizes its offscreen framebuffer to its largest camera in its own context, never in the shared model. Per batch it builds the scene once (mjv_updateScene); each camera then sets only its view (mjv_updateCamera), its lights (mjv_makeLights: the headlight follows the camera) and its clip planes, is drawn at the origin of the framebuffer, and its colour image is copied on the GPU into its tile of one atlas, read back once per batch. Depth and segmentation keep a pass of their own per camera, drawn with flat ID colours as mujoco.Renderer draws them; under MSAA the labels are drawn in a second, single-sampled context, since a multisampled buffer blends the id colours of two geoms at an edge into a third geom’s id. A camera with its own geom groups or decorations gets a build of its own, and so does a camera asking for the moving bodies alone (CameraSpec.bodies: moving), whose build takes MuJoCo’s dynamic category only – the bodies moving_bodies() marks, with no static geom, no floor and no decoration – which is what a renderer bringing its own static world composites by depth. A posed camera (RenderService.view_at) has no camera of the model: its scene is built through the default free camera, and then both GL cameras of the scene are written from the request’s pose and intrinsics (posed_gl_camera(), the frustum’s edges on the image’s outer edges, so cx, cy count from the top-left pixel’s centre) and its clip planes, before mjv_makeLights, so the headlight follows the view; everything else – the geom groups, the shadows of see-through geoms, the depth and label passes – is a model camera’s. Its picture is that of a model camera at the same pose with the same sensorsize, focal and principal, pixel for pixel: the labels to the bit, and colour and depth to the bit on a GPU, where a software rasteriser rounds them the other way at a few pixels, by one colour level or a float32 of depth (roqsim/tests/test_render_posed.py). The pictures are those a mujoco.Renderer per camera drew (roqsim/tests/test_render_service_pixels.py). Under MuJoCo’s default 4x MSAA a frame is not bit-reproducible on every GPU, with or without the service: a run may differ from another in a handful of values by one level; a model with <quality offsamples="0"/> draws exactly.

  • Filament (FilamentRenderer, filament) is MuJoCo’s physically based renderer (mjrf), retained-mode: it makes the model’s meshes, textures, lights and renderables once at open and per batch updates their poses from the snapshot; each image of each camera – colour, depth and segmentation, each in Filament’s own draw mode – is one mjrf render call read back into an array of its own, since MuJoCo 4.0 reads back one target per call, and every call of a batch is submitted before the first wait. It runs headless through Vulkan only: its OpenGL backend opens an X display (GLX), and both a missing display and a missing Vulkan driver end the process inside Filament, so the first context of a process is opened in a child first (probe()), which also names the device. Three properties of MuJoCo 4.0’s Filament shape it. A Filament engine destroyed off the thread that made it aborts the process, and a Vulkan context destroyed on an NVIDIA driver terminates the EGL display the classic renderer shares; so contexts are never destroyed: each renderer borrows one of its thread’s pool and gives it back on close, freeing only its world’s resources (and from another thread, not even those). One context holds one textured model at a time, which is why each open renderer has a context of its own. ModelRenderables takes a geom’s group when it is made and labels a geom of zero alpha, so what presence hides at run time is taken out of the scene by the renderer itself, and the renderables are made again when something hidden when they were made is shown. A flex and a spatial tendon are drawn as parts, each labelled as its object. Depth is reversed-Z, linearised in closed form; a posed camera is the mjrf.Camera of the GL camera posed_gl_camera() writes, between the request’s planes or the model’s; labels are the renderables’ own segmentation_id, mapped back to (object, mjtObj). With post-processing on, Filament’s dithering and ambient occlusion change from frame to frame, so it declares itself deterministic only with post_processing: false (capabilities_for).

  • Clip planes. MuJoCo derives every camera’s clip planes from the model, visual/map znear/zfar times its extent, so in a large world the near plane stands tens of centimetres out. A sensor camera draws instead between its render_near (a physical distance, default 0.01 m) and the model’s own far plane, so what it sees does not depend on the world’s size: the renderer sets those planes on the GL cameras of its own scene after the camera’s view is set and linearises its depth reads with them, and the model, the viewer, an export and every other camera keep theirs. Every pass of a camera – colour, depth, registered depth, labels – is drawn with its planes. What a depth camera senses is separate: clip_near/clip_far mask the rendered depth to “no return” afterwards, so a surface nearer than clip_near is drawn, hides what is behind it and reads “no return”; render_near must not exceed clip_near.

  • Without a tick. roqsim render and its videos, the thumbnails, the scene review and the coverage visualisation draw through FrameRenderer, one view of a service of its own; a views file (roqsim render --views, roqsim.views.render_views()) registers every view as a posed camera of one service before its renderer opens, and draws them in batches bounded by count and pixels from one state; roqsim render takes the world’s renderer, and the scene review stays on MuJoCo’s, since it picks and decorates the MuJoCo scene it edits.

  • The offscreen backend is bound by ``import mujoco``, so it is chosen by ``import roqsim``. MUJOCO_GL is read exactly once, inside mujoco/rendering/classic/gl_context.py, while mujoco is being imported; it assigns GLContext there and then, and an unset value is not an error but a choice — it falls through to glfw. Everything that follows from that is the reason roqsim.gl.select_offscreen_gl() is called from the package __init__ rather than from a driver’s main: a driver module’s own imports reach mujoco before its main body runs, so a selection made there sets a variable nobody will read again. A selection made in roqsim.runner.main would be inert for every headless run, invisibly, because a world with no camera never constructs a Renderer and therefore never instantiates the mis-bound backend; the first camera world on a headless node would then fail with mujoco.FatalError: gladLoadGL error from inside MjrContext. A PYOPENGL_PLATFORM of egl or osmesa decides, since each backend refuses to import under the other’s; with neither set, a node with a DRI render device gets egl and one without gets osmesa; an explicit MUJOCO_GL always wins and ROQSIM_NO_GL_SELECT opts out. Both backends are installed in the container images for the same reason the choice is deferred: which one works is a property of the node, not of the image. The one case the package __init__ cannot cover — a consumer importing mujoco first — is caught by roqsim.rendering.check_gl_backend(), which every renderer in the tree funnels through and which names the cause and the fix rather than leaving MuJoCo’s message to stand.

  • The interactive viewer (mujoco.viewer.launch_passive) is a driver concern, separate from the offscreen RenderService, so windowed vs headless is a driver switch, not a plugin change. The standalone runner sets the viewer’s initial free camera from the world’s optional sim.view block (lookat/distance/azimuth/elevation, plus track — an entity or body to follow — and follow_heading; any subset — omitted keys keep MuJoCo’s model-derived default). sim.view is the camera and only the camera: it is schema-checked on load, so an unknown key fails the run rather than being silently dropped. The two Simulate side panels are deliberately not expressible there — they are run-level flags (--left-ui/--right-ui, passed to launch_passive’s show_left_ui/show_right_ui, both hidden by default), on the same footing as --manual-control: a world describes the experiment, whereas panels and hand-driving describe one interactive session. All of it is windowed-only (ignored under headless) and is not a plugin concern. The keys roqsim adds to that window are declared once (roqsim.keys): the handlers take their keycodes from those records and the F1 list is rendered from them, so what the window says a key does and what it does are one declaration – and the list a run shows is merged from the handlers that run actually wired, so it never offers a key this window lacks. The window’s text overlay is owned by slot (roqsim.overlay) because set_texts replaces the whole set: the camera-mode notice and the key list are two writers, and either alone would take the other down.

  • Rendering an image is a driver concern too, and it is a separate process. roqsim render (roqsim.render, the tool; roqsim.rendering is the library it drives) compiles a target through the same dispatch as roqsim sim (roqsim.runner.config_for_input()) and writes one frame offscreen, so a world renders exactly as it simulates. It runs in its own process with its own GL context and touches no running simulation, which is why the picture path has no performance question attached to it. Three deliberate choices: the camera comes from the world’s sim.view, layered by --view through the same override path --set uses (so sim.view keeps one validator and one frozen key set — there is no second camera grammar); the headless camera is built by handing a shim to roqsim.viewer.setup_camera(), so track/follow_heading/preview framing are inherited rather than reimplemented; and a model’s home keyframe is preferred over qpos0, shared with roqsim assets render-thumbnails so a model’s thumbnail and its roqsim render output are the same picture; a robot whose manifest mounts devices is thumbnailed as spawn_robot builds it, devices attached, since its own MJCF does not carry them. Raw meshes are accepted here (wrapped in the preview scene roqsim.mesh_preview owns – in the core, not beside the prop pipeline that motivated it, because a capability roqsim render --help advertises cannot depend on an optional sibling being installed) even though roqsim sim refuses them: loose geometry cannot be meaningfully simulated, but rendering it is both harmless and useful. Stdout is exactly one line of JSON, a machine contract rather than a convenience — it reports the camera in --view’s own vocabulary, so a shot can be reproduced by copying it back. --views FILE is the one second camera grammar, and on purpose: a file of fixed cameras, each a pose and pinhole intrinsics (roqsim.views), which sim.view – an orbit with no roll and no principal point – cannot state; it is a file and not a world key, so sim.view keeps its one validator. Its conventions are declared once (roqsim.views.PRESETS), and --help, roqsim views describe, a refusal and the docs are made from that declaration.

  • A see-through geom throws no shadow. MuJoCo’s shadow map is binary, so a pane or a shrink film at 10 % opacity would block a shadow-casting light as completely as a steel plate and leave what is behind it in the dark. roqsim.rendering.MujocoRenderer, which every camera and roqsim render draw through, moves every geom whose resolved alpha is below 1 to mjCAT_DECOR after the scene is built – the one category MuJoCo leaves out of its shadow pass and uses for nothing else at that point – so it is still drawn and blended but no longer darkens what it covers. The interactive viewer is MuJoCo’s own and keeps its shadows.

  • A scene export is one walk and a writer. export gltf (glTF 2.0) writes the scene. roqsim.scene_source compiles it – a world through the same Engine a run builds, reset and optionally settled, or a bare MJCF – and roqsim.scene_content decides what it contains: bodies with their poses, the drawn geoms (one predicate, roqsim.scene_content.drawn_group()), meshes, skins and the flexes drawn as skins, materials, textures, the exported state a format without joints places bodies at (roqsim.scene_content.exported_state()) and the joints with their reference values, which glTF carries in extras, and the sensor cameras the configured plugins declare through Plugin.scene_cameras (roqsim.scene_content.sensor_cameras()), each on its body with the projection of the image it publishes. A writer only spells that, and a test holds the file to the walk (test_export_gltf.py). Primitives as triangles come from roqsim.tessellate, shared with export mesh; the textured surfaces there follow MuJoCo’s own renderer, so a texture lands where MuJoCo draws it.

  • Closing the window is a wait, not a request. MuJoCo runs the window on threads it owns and Handle.close() only sets exitrequest, so the window, its GL context and its X drawable are destroyed after the call returns. A process that closes and then exits promptly (a world that fails to load, --steps 1, a short --seconds) would race its own teardown: Python’s atexit runs glfw.terminate under the render thread, whose in-flight glXSwapBuffers then hits a destroyed drawable, and Xlib’s default handler calls exit() from that thread while the main thread is already finalizing — the process hangs after its last line of output (or segfaults). Both drivers therefore open with roqsim.viewer.launch_viewer() and close with roqsim.viewer.close_viewer(), which joins those threads (~10 ms) so the teardown is ordered; never Handle.close() or with handle: directly. Relatedly, the cosmetic X11 window branding (roqsim.window_branding) polls other clients’ windows, where a window closing mid-pass is normal, so it installs an ignoring X error handler for the duration — Xlib’s default one would kill the process over a window title.

  • Windowed run + cameras — two GL contexts, two backends. The viewer window is always glfw: mujoco.viewer imports and initialises glfw directly, independent of MUJOCO_GL, which selects only the offscreen Renderer backend. So a windowed run of a camera world holds a glfw window context and an offscreen render context at once, and they must not both be glfw — two glfw contexts in one process collide and MuJoCo aborts with gladLoadGL error. The runner (see roqsim.viewer.prepare_viewer_gl()) resolves this before any GL loads, for windowed launches only, with two overridable defaults: it preloads the system libGLEW (the glfw window context needs it in the global symbol namespace on many Linux/GL-driver combinations) via an LD_PRELOAD re-exec — LD_PRELOAD is read only at process startup — and defaults MUJOCO_GL=egl so the offscreen cameras get their own context. That default decides only under ROQSIM_NO_GL_SELECT: otherwise import roqsim has already chosen egl or osmesa, which is not glfw either. Override with MUJOCO_GL / ROQSIM_NO_GL_PRELOAD. Caveat: a hand-exported LD_PRELOAD=…libGLEW left in the shell drags GLX into the process alongside MuJoCo’s PyOpenGL EGL backend and crashes import mujoco with undefined symbol: eglQueryString — roqsim preloads libGLEW itself, so do not also export it.

9. Sensor noise

9.1 Sensor noise

Design note: there is no generic, composable error-model framework (a registry wired into sensors through an error_model: config key). Noise is sensor-specific — its parameters, where it applies, and how it degrades only make sense in the context of one sensor — so a generic cross-sensor abstraction adds indirection without real reuse.

Instead, each sensor owns its noise as plain config:

  • Lidar (roqsim_sensors): range_stddev adds zero-mean Gaussian noise to every hit (0 = off), and range_stddev_relative makes that sigma a fraction of the true distance at and beyond range_stddev_relative_from – the shape a triangulation scanner’s datasheet states (the LDS-01: +-10 mm below 0.5 m, +-3.5 % above). The noisy distance is floored at 0 and quantised to range_resolution (the S300’s 10 mm steps). It reaches a measured return and a 2D scan’s raw too-close return; a constant too_close/no_return value carries none. dropout_percent randomly drops that percentage of rays per scan to a no return (the scan’s no_return value, +inf by default). A systematic per-instance bias is not modelled: the datasheets state it as a bound with no distribution. The noise is drawn per ray: one draw per ray of the frame, in ray order, whether or not the ray returned, so ray i’s noise is a function of the key and i alone, and a ray that hits something else (a grazed edge, another ray-cast backend) changes its own value and no other. Drawn per return instead, one return more or fewer would hand every later return its neighbour’s draw. Determinism: seeded from the run’s seed (sim.seed in the world, or --seed, or the value the scenario adapter resolves from ROQSIM_SEED – an explicit one wins; with none of them, one is drawn and announced) through roqsim.context.SimContext.rng_for(), which returns a counter-based (Philox) generator keyed on (seed, run, sim_time, sensor address) – the address being the entity and label, which a manifest-injected sensor has where it has no name:. The run — run, the name reset() is given (reset(run="cfg-a/3"), the scenario adapter’s run argument, roqsim sim --run, ROQSIM_RUN) or the next unnamed one ("#0", "#1", …; roqsim.runs) — is what stops a process that serves several runs from replaying one noise sequence over and over: mj_resetData puts data.time back to zero, so keying on simulated time alone would make run 2 re-draw run 1’s noise step for step, and repeated runs of one configuration duplicates wearing the clothes of samples. It is the run’s name and not a count of resets, so the runs of one campaign never draw the same values whichever process they share – a process that runs several configurations one after another counts nothing that another process does not – and the same seed and run draw the same values in any process, whatever ran before. It occupies a counter slot, as a stable 64-bit hash of the name, rather than perturbing the key, so the key still means “the run’s seed” and the generator stays randomly accessible. Two campaigns, or a replay, that give the same seed and run share their draws; two configurations do not, since their runs have names of their own. A recording carries the run beside the seed, because the right seed at the wrong run reproduces noise that never happened, and entirely plausible-looking. A plugin that needs to see that a reset happened compares reset_count, which one run reset twice under its name still advances. Counter-based rather than stateful for a specific reason: a shared stateful generator’s position depends on how many draws happened before it — sensor rates, step count, and for cameras whether anyone was subscribed — so it is not a function of the world at all, and a value drawn at t = 12.5 could not be reproduced without replaying the whole run. Keying on simulated time rather than a step counter is what lets a sensor be re-run from a recording and produce the same noise the live run published, because a restored state carries its sim_time and nothing carries a step count. A sensor re-run from a recording (roqsim state --sensor) is therefore deterministic and noise-correct for the restored state, but not bit-identical to what the live run published at that timestamp: live, post_step runs at the physics rate, so a sensor’s own rate_hz gate fires between recorded samples and the endpoint holds a scan computed slightly earlier than the sample that recorded it. Measured, about a quarter coincide exactly. Recovering the rest would mean recording every firing — bagging the topic, at ~26x the size of the state recording — which is the trade this design refuses. An unresolved seed raises (roqsim.seed.SeedError) rather than standing in a 0: the seed is the driver’s to resolve, so a run without one is missing a required input, and the failure lands at the first draw instead of on every trial afterwards. It is raised from rng_for and not from setup() because that is the only place that knows a draw is happening – a geometry export or a scenes describe builds the same world and needs no seed. A preview – a driver that compiles a world in order to LOOK at it and never steps it into a run whose numbers anyone keeps – says so with Engine(cfg, preview=True), which pins the fixed roqsim.seed.PREVIEW_SEED: a picture is not a measurement, and two renders of one world must be the same picture. Plugins read the flag as ctx.preview: a scene, Python or OpenSCENARIO, runs nothing in a world compiled to look at it, though a replay or a settled export still steps it. A preview engine also leaves the world’s transport plugins out of the build (roqsim.config.drop_transport(): a class declaring transport_only, or a ROS bridge this environment cannot resolve), because a transport builds no geometry and its configure binds a port or waits for a peer a preview never starts; engine.dropped_transport names what went, logged once per build, and the caller’s config keeps what the world declares. A consumer that wants a picture even of a world whose third-party plugins are not installed – roqsim render, the review window, the map and the exporters – adds skip_unloadable=True, which also leaves out any ref that does not resolve and warns naming it, since the other way to get one is a misspelt ref; roqsim scenes describe and roqsim sensors coverage do not, so a misspelt geometry plugin stays a failure there. roqsim check validates every plugin the world declares before it loads the world without its transport, so it still needs the bridge’s package installed. That is a flag rather than a line each such tool remembers, because forgetting it is invisible until someone points the tool at a world that happens to draw: without it, roqsim render, roqsim check, roqsim scenes describe, the map and MoveIt exports and the scene preview would each refuse such a world, naming a seed their caller has no way to supply – and a campaign’s world check would refuse a perfectly good randomised world before spending anything on it. A driver may still assign ctx.seed itself afterwards; the flag sets the default, not the policy. Where a world is run repeatedly to sample a distribution, leave sim.seed unset – a stated one gives every repetition the same draws, which is reproducibility bought at the price of the variation those repetitions exist to measure.

  • Wheel odometry (roqsim_mobile): diff_drive’s odom_noise puts a multiplicative bias (linear_scale, angular_scale) and zero-mean white noise (linear_stddev, angular_stddev) on the velocities read off the wheels, before they are integrated, so the reported pose drifts the way real odometry does while the base itself moves exactly as the physics says. One draw per physics step from rng_for, under the same seed and run rules as the lidar; omitted, nothing is drawn.

  • Force/torque (roqsim_sensors): force_torque adds zero-mean white noise (noise_force_stddev, noise_torque_stddev), one draw per step, and a transducer’s error, held constant through a run: a zero offset bounded by bias_force/bias_torque and a linear drift rate bounded by drift_force/drift_torque, each drawn uniformly per channel, enter the raw reading before the tare, so a tare removes what has accumulated. range_force/range_torque saturate each channel. The run’s draws come from rng_for(name, per_run=True), which holds the counter’s step slot at zero: the draw is a function of (seed, run, name), whenever in the run it is made, so a reading at any sim time is still reproducible from that time alone. That is also why drift is linear rather than a random walk, which would need every earlier step.

  • Ground-truth physics stays clean for sensor noise: only the reported value is perturbed. A fault that is physical – a grasp that slips, a wheel that loses traction – is the opposite case, and is §9.2 rather than this.

Switching it mid-run. The values above are the sensor’s nominal config. A sensor may also carry a fault: block – the values it takes on while degraded – which a scenario applies and restores by the sensor’s address (entity_call(entity: 'robot.lidar', command: 'override')), over the same endpoint shape model_override uses. It is not a plugin: a component belongs to the entry it is nested under and a sensor registers no entity, so a separate fault entry could only have named its target in a config key – the ownership-as-a-value pattern §4 rules out (Model plugin manifests: ownership is the full address). Severity stays configured (so components.robot.lidar.fault.dropout_percent is an ordinary experiment factor) and only one bit crosses the wire; the world never owns when. Only keys the sensor reads per frame may be written, declared per sensor as an allowlist and refused by name otherwise – rays changes a LaserScan’s length, which is the §9.2 geom_size failure in sensor form: a write that lands, does nothing, and reads back as though it had. Implementation: roqsim_sensors/live_config.py.

When a future sensor needs a different noise shape, add it to that sensor’s config, not to a shared framework. Reference: roqsim_sensors/src/roqsim_sensors/plugins/lidar_common.py — the shared base every ray-casting range sensor derives from (the 2D lidar, livox_mid360, and seyond_robin_w1g), which owns the rate gate, the detection limits and the noise so the devices cannot drift apart on them: the far limit and the presence mask are applied there once, for every device.

One raycast seam: ``roqsim.raycast``. roqsim.raycast.cast() is the only mj_multiRay caller in the tree, and the seam a GPU backend stands behind — the lidar base, the coverage engine and sampler, spawn_sensor’s build-time occlusion probe, roqsim.rendering’s line-of-sight test and roqsim_assets’ moving_box all go through it. Three things live there because they must be decided once:

  • The visibility mask is the default. mj_multiRay’s geomgroup=None means every group, including roqsim.presence.ABSENT_GEOM_GROUP, so a caller who omits the mask sees entities that have been made absent — an absent entity reported as a return, with nothing downstream able to tell. Making the mask the default turns “forgot the mask” into an explicit geomgroup=None. The mask also leaves out roqsim.presence.WINDOW_GEOM_GROUP (5): a sensor’s window, which every render (rendering._vopt) and every viewer window (viewer.show_windows) draw and no ray meets. A head with its lidar’s opening cut into its collision mesh is drawn whole there, so it looks like the robot and still scans out.

  • It is single-threaded on purpose, and that is measured. Splitting a batch across threads looks free — rays are independent, mj_multiRay releases the GIL, and the output is bit-identical (1.5x at 360 rays, 3.1x at 20160). It is not: mj_multiRay allocates from ``mjData``’s stack (96 bytes, whatever the ray count), and that stack is one bump pointer in the shared mjData. Hammering one mjData with 8 threads × 40000 casts, a sampler saw pstack peak at 2112 bytes and return 1632 instead of 0 — MuJoCo guarantees a function restores pstack, and concurrency breaks it. The leak is monotonic, so a long trial walks toward stack exhaustion; the failure it produces is a core dump. Every one of those 320000 casts returned the right answer, which is the point: the race corrupts an allocator invariant, not the output, so it survives any amount of parity testing and then crashes in a long run. MuJoCo’s own guidance is one mjData per thread and the ray functions are not exempt. Where 3D-lidar throughput is binding, the route is the GPU backend below; a pool of per-worker mjData clones with geom poses copied in would need the mjData fields the ray path reads pinned down and kept pinned across MuJoCo upgrades.

  • The backend is a choice, auto the default. roqsim.raycast.RaycastService gives each sensor the backend it or its world names (raycaster:, sim.raycaster; Choosing a renderer, “Choosing a ray caster”), opening each backend once per world, when the first sensor that takes it is configured; every sensor on it shares that instance. cpu is cast() and cast_many() unchanged. auto, the default, takes per sensor the first installed backend that declares auto (a capability the backend declares, not a name the core lists), opens here, and is faster for the sensor’s ray count (its auto_min_rays); otherwise the CPU. A backend auto could not open is not tried again in that world. Every choice is stated: logged at load and raised as a raycaster condition whose details give what was asked for, the backend, the ray count and the reason, so a recording and a campaign’s run directory say what each lidar cast on and why.

    mjwarp (roqsim_raycast_mjwarp, MuJoCo Warp and Warp as its [mjwarp] extra, so nothing else imports Warp) casts on a CUDA GPU with mjw.rays’ BVH search, which applies the mask, flg_static and a per-ray excluded body inside the nearest-hit search and skips a geom whose resolved alpha is 0, as mj_multiRay does; it searches a mesh without culling the triangles a ray meets from behind, as mj_ray does and mjw.rays does not (a lidar inside a visual-only pillar reads the pillar on both). Its device scene (mjw.put_model, a pose-only device Data, a camera-less render context for the BVH) is built once after compile; per cast it uploads only what changed since the last – the geom poses, then a BVH refit, so one refit per tick however many lidars share it, and the presence fields geom_group/geom_rgba/ mat_rgba – and applies MuJoCo’s culling beyond cutoff on the host (roqsim.raycast.cull_beyond_cutoff(), which is the far-plane rule for a plane). It runs on the physics thread, reading model and data and writing neither. Its cost is a fixed hand-over per sweep, so it pays for a 3D lidar’s thousands of rays and for mesh-heavy worlds, and not for a 2D-lidar sweep in a small room: auto takes it from auto_min_rays (2,000 by default, the crossover in the default room) rays. Named, a backend that cannot run (no MuJoCo Warp, no CUDA device, a Warp build the driver cannot run, a model put_model refuses) fails the load, naming the sensor, the backend and the reason; under auto the sensor casts on the CPU and the condition says why. Cameras are unaffected either way – they rasterize through the render service on the GPU already (§8), and their depth is that render’s z-buffer, not a raycast.

The test for which of the two a perturbation is, is where the failure lives. A lidar that mis-measures a wall it can see is noise. A gripper that stops holding is not a measurement at all, and no perturbation of a report can produce it.

Reaching a sensor’s config from outside the world. A sensor usually arrives from a model manifest – spawn_robot: {model: turtlebot4} brings the lidar with it – so a world that only spawns a robot never names it. Two consequences, and they differ:

  • A world may set one key of a default without restating the rest. Declare it where the manifest puts it – for a TurtleBot 4, under the robot’s rplidar mount; expand_manifest merges the manifest’s config underneath that entry, per key, so:

    components:
      - spawn_robot: {model: turtlebot4}
        name: robot
        components:
          - spawn_sensor: {}                # the manifest's RPLIDAR mount, by its label
            name: rplidar
            components:
              - lidar: {range_stddev: 0.05}   # keeps the device's rays, max_range, frame_id
    

    Restating the rest would be a duplicate that silently diverges the day the manifest changes. The entry carries no robot: key: it belongs to the mount because it sits inside it.

  • An override reaches a default the document never declared. Expansion runs while the document loads, so --set components.robot.rplidar.lidar.range_stddev=0.05 resolves against what will actually run – no entry, no stub. It is still applied before compile, so the value is in the compiled model and therefore in the run’s provenance.

    An address is a path through the document: consume a segment while it names a component, and the first that does not begins the path into that component’s config. So the two spellings are the same assignment, which they have to be – a sweep flattens a path onto a command line, a saved override set writes a document, and they must not diverge:

    --set components.robot.rplidar.lidar.rays=720
    components: {robot.rplidar.lidar: {rays: 720}}
    

    Assignments are applied twice: once against what the document declares, then again once its models’ manifests have contributed. The first pass is what lets a structural override work – components.robot.model=husky_a200 lands before expansion reads model:, so the husky’s manifest is what expands – and the second is what reaches a component only a manifest supplies. An assignment that matched in neither pass is refused, which is the failure that matters: silently ignoring a swept parameter would let a sweep change nothing while every run looked healthy. The refusal names what the document does have, searching refs as well as addresses – a bare lidar against a robot carrying two is a no-match rather than an ambiguity, and the useful answer is both their addresses.

Proximity is a separate observable, and a separate plugin. contact_monitor answers did it touch; clearance_monitor answers how close did it come. Contact is the honest failure criterion and a poor optimisation target – a bit gives every non-touching configuration one score – so the pair exists to supply a verdict and a gradient over one geometry, with one owner each. The distance is measured in the simulator rather than derived afterwards from recorded poses for three reasons that cannot be fixed downstream: the closest approach falls between pose samples, and the faster the pass the more is missed; a footprint radius would put a calibration constant between the geometry and the result, which is the objection contact_monitor raises against a proximity proxy; and an articulated obstacle’s nearest part is a limb rather than its origin. mj_geomDistance measures the real shapes, so the limb is what it finds and names. Collision masks matter here and MuJoCo’s distance query does not apply them: a render-only geom would otherwise be reported as clearance to something the robot passes straight through (a pedestrian model carries six of those beside fifteen solid ones), so candidates and watched geoms are filtered by MuJoCo’s own pairing rule on both sides. entities narrows the candidates to named entities’ geoms, resolved at the first measurement through roqsim.presence.entity_geoms, which follows an entity’s bodies beside its root (a walker’s limbs are bodies of the world, not children of its pelvis); hit_geometry adds their non-colliding collision-group geoms, a walker’s arms, measured whatever their flags. The watched side is the whole entity the monitor is nested under in the same way, unless body narrows it to one body’s subtree. It never ends a trial – two plugins reporting one failure by different rules is how a trial starts disagreeing with itself, and a clearance threshold is exactly the tunable number the contact oracle avoids; a scenario that wants to stop on a near-miss reads the endpoint and decides, with the threshold stated in the experiment. Measuring is a distance query per geom pair, so compute_rate_hz (default 200) is decoupled from the publish rate: every physics step cost about a fifth of the step budget on a nav world, against a budget the simulator may already be over, while 200 Hz resolves ~1.5 mm at walking pace.

9.2 Physical faults (model_override)

The runtime counterpart to --set: name a model field, name the objects, name a target value, and let an external trigger switch between nominal and target. It is what makes “the robot loses the object it is carrying, at this instant” a property of the world rather than something scripted into whatever drives the robot. Save/restore is exact, from the values read at configure, the way roqsim.presence restores what it hid.

Not every model field can be written at runtime, and the ones that cannot fail silently – so the plugin ships a curated allowlist, one row per field with its object namespace, its write class and its caveat, and refuses everything else by name with the reason. Two write classes, both measured against MuJoCo 3.11.0:

  • live – in effect on the next step: geom_friction, geom_contype/geom_conaffinity, actuator_forcerange, and a flex’s flex_friction, flex_solref, flex_solimp and flex_damping (measured on MuJoCo 4.0.0). flex_damping is live only on a flex compiled with a non-zero damping: MuJoCo sizes the flex’s edge Jacobian at compile, and over a compiled 0 a written damping acts in part (measured: the ringing barely changes, where written over a compiled 1e-9 it reproduces the compiled run exactly), so that write is refused. A flex’s Young’s modulus and Poisson’s ratio have no row because they have no field – MuJoCo bakes them into flex_stiffness – and the flex_material plugin sets them before compile.

  • needs_setconst – body_mass, whose write the dynamics ignore until mj_setConst recomputes the derived inertia (measured: the mass matrix does not move, and body_invweight0/body_subtreemass keep their compile-time values). The plugin calls it.

geom_size is refused: geom_rbound is cached at compile, so a box grown 0.05 → 0.4 m kept rbound at 0.0866 and, while overlapping the floor, produced ncon = 0 – geometry that renders big and collides as if small. Three further refusals are decisions rather than safety, and the plugin says so: geom_priority (it also governs condim/solref/solimp, so it would swap the contact’s stiffness model at the instant of the fault), MuJoCo’s own sensor_noise (§9.1 gave that to per-sensor config), and every opt.* global (sim.contact_override and the sim: block own those, before compile, so they are in the compiled model and in the run’s provenance – a runtime write would make the recorded value differ from the one that ran).

That refusal governs a fault-injection hook poking a global whose recorded value is a single number; it is not a ban on writing an opt.* global. roqsim_aerial’s wind_field owns opt.wind and writes it every tick, because constant wind is the one wind a controller never has to reject – it trims against it once and the error goes to zero – so a world that can only state a constant cannot test disturbance rejection at all. The provenance argument does not carry across: the wind there is not a value but a signal, fully determined by the plugin’s declared parameters plus the run’s seed, both recorded with the world, and reproducible tick for tick. What keeps that inside the rule rather than around it is one owner per knob: wind_field refuses to load beside a sim.wind rather than merging with it, because two owners of one global is exactly the situation where the compiled model and the first tick disagree and the run records the value that was overwritten. A plugin that wants an opt.* global takes it over completely, says so, and fails loudly when something else has claimed it – it does not share it.

The plugin never decides when to fire. A fault’s timing is the experiment’s independent variable, and severity is the configured target value, so both stay sweepable: what crosses the wire is one bit. The inbound endpoint is therefore a std_srvs/SetBool service rather than a topic – a command whose outcome the caller needs – and its reply carries the verdict, so a scenario’s service_call() can fail a trial that failed to inject its fault.

An override that lands in the model and changes nothing is the failure that would otherwise produce plausible wrong data. MuJoCo takes a contact’s friction from the geom with the higher priority, and at equal priority the element-wise maximum of the two, so lowering one side cannot bring a pair below the other side’s value. configure raises for what is certain (an unknown name, an empty selection, an explicit <pair> covering a selected geom, a geom roqsim.presence has made absent, an all-visual-only selection, a geom_contype override without its geom_conaffinity partner – measured to be a no-op alone). The rest is caught at runtime by reading the applied contact rather than predicting it: one step after a change, verified reads landed, no_effect (with a warning, and a failed service reply) or untested. Deliberately not done: a configure-time analysis of which geom governs which pair, which would re-derive MuJoCo’s mixing rule inside a generic field writer and could only ever warn.

The allowlist is also the plugin’s documentation and its discovery surface: roqsim scenes describe reports it as overridable.fields (world-independent, so it costs no model build), and --overridable GLOB adds overridable.targets – the names an override can select and their current values – for a caller that is not a roqsim process.

10. Synchronous / lockstep mode [planned — seams exist, behaviour inert]

Later, as in CARLA’s synchronous mode (ref: github.com/carla-simulator/ros-bridge), the tick must be able to block until external consumers react: don’t advance until ROS 2 returns a control command computed from this tick’s sensor data, and/or until every sensor due this tick has published. This makes the loop a deterministic sensor-in → control-out lockstep, independent of wall-clock pacing.

Design:

  • Gates (ctx.register_gate(name, role)), two roles:

    • Producer (sensor): calls gate.satisfy() once it has published this tick; the engine computes the due set from sensor rates and, in sync mode, waits for all due producers.

    • Consumer (controller/bridge): gate stays pending until the expected input arrives via ctx.post.

  • Blocking step: in sync mode step() publishes (post_step), then blocks on the barrier (Event/Condition) until all gates clear or a timeout fires; the queued control is applied in the next pre_step. Composes with both drivers (scenario-execution’s step() just takes longer; pacer bypassed).

  • Config: sim.sync = {enabled, timeout_s, wait_for: [sensors, control]}; default off. GetSimulatorFeatures reports whether sync stepping is active.

  • Safety: timeout + a deadlock diagnostic (which gate never fired) prevents a missing/late node from hanging the sim.

The command-queue model (§7) is the substrate: sync mode adds a wait on named gates, not a new concurrency scheme. A camera’s frames already belong to their tick when the render service is in its default sync mode (§8), which is why a world turning lockstep on cannot ask for async; a camera’s producer gate would be satisfied by its post_step, once its frame is in. register_gate/gates exist and are reset each reset(), and the engine does not wait on them. roqsim_aerial’s px4_sitl is the one user: it registers a consumer gate and waits on it in its own post_step, with the timeout and deadlock diagnostic this section requires.

11. Performance & benchmarking

With Engine(profile=True) (the runner’s --profile) the engine times every overridden hook and the physics step itself and accumulates per-plugin, per-hook wall-time; profiling off means no timing work at all. Engine.timing_report() → {plugin: {hook: avg_µs}}, with the physics step under the <physics> key (mj_step, or mj_step1/gravity_reaction/mj_step2 for a step in two halves); Engine.format_timing() prints a table. Use it to answer “is a plugin slowing the sim?” — total plugin overhead should be a small fraction of the <physics> row. MuJoCo’s split of that row into its stages is the step_timers plugin (Available plugins). The same flag records one-shot load phases (plugin resolution, world parse, compile, data creation): Engine.load_report()/format_load_report(), printed by the runner right after setup — this answers “why does the world load slowly?”. For the practical workflow — measuring RTF, py-spy thread attribution, and the GIL caveat — see Profiling & performance debugging.

Parallel post-step [planned]: consistent with the single-writer rule, only post_step is safe to parallelize (read-only). Plugins opt in with parallel_safe = True; a future thread-pool executor runs the safe ones concurrently while pre_step (which drains the queue and writes data) stays sequential. Every hook runs sequentially; the threads beside the physics thread (the ROS executor, a transport’s reader such as px4_sitl’s, the viewer’s) reach data only through the command queue.

12. Conventions

  • Layout: the framework core is its own pip package roqsim/ (engine, plugin API, drivers, the generic dummy plugin, and the driver-level capture/render modules). Generic, robot-family-agnostic sensors live in roqsim_sensors/ (lidar, oakd_camera, realsense_d435, imu, gnss). Robot-family plugins + assets live in further sibling packages — wheeled bases in roqsim_mobile/ (floorplan/spawn_robot/diff_drive/omni_drive, models, worlds); arms and manipulators are further siblings, aerial vehicles in roqsim_aerial/ (quadrotor_controller, multirotor_motors, px4_sitl, models, worlds), and a robot belonging to two families goes in a package depending on both (roqsim_mobile_manipulation/) rather than widening one family’s dependencies. The ROS bridge and the nav2 example are colcon packages under ros2_ws/src/ (roqsim_ros_bridge, roqsim_nav2_example). Keep the core ROS-free.

  • Naming: plugin classes PascalCase, entry-point names snake_case; blackboard handles under <kind>:<name> (robot:<name>, metrics:<name>, model_override:<name>, contact_monitor:<name>, machine:<name> for every machine, zone:<name>, part_state, see Machines and scenarios).

  • Reaching a plugin from outside: a plugin an out-of-process or out-of-package driver must reach publishes a blackboard handle in configure — a small callable or dataclass under <kind>:<name>, where <name> is the instance’s world-YAML name:. Consumers resolve that key; they never iterate engine.plugins and never match on a class name, which breaks silently on a rename and cannot distinguish two instances of one plugin. Publish a callable when the value is replaced each step (contact_monitor.read_state) rather than the object it returns. The in-process seam a driver starts from is MujocoSim.context (a SimContext, i.e. exactly the rights a plugin has, single-writer rule included) — not the Engine, so plugins and config stay the engine’s own. Over a transport the same capability is an Endpoint (§13); the two are the same declaration read two ways, which is what lets one scenario action serve a stepped run and a ROS run.

  • Assets: record upstream license for any vendored MJCF/mesh next to it (see roqsim_mobile/.../husky_a200/husky_a200_LICENSE for the pattern). Where a provider ships its models flat, one directory holds several vendors’ terms and “the file beside it” attributes the wrong one, so the model names its own with license: in its manifest (roqsim.manifest.manifest_license(), read by both the docs catalog and roqsim catalog models).

  • Model headline: open a model’s MJCF with a comment whose first sentence says what the model is (Clearpath Ridgeback (4-wheel mecanum, holonomic) for MuJoCo.). The docs model catalog describes each model with that sentence and reads the licence out of the sidecar’s own text, so neither is prose anyone maintains twice; a model without one falls back to repeating its package’s summary, which roqsim/tests/test_model_docs.py fails on.

  • Model layout: a provider ships its models either one folder per model — models/<name>/<name>.xml with the manifest, licence and thumbnail beside it and its meshes in models/<name>/meshes/, referenced bare via <compiler meshdir="meshes"> (roqsim_manipulation_assets, roqsim_assets, roqsim_sensors, roqsim_mobile) — or flat, models/<name>.xml with meshes namespaced under models/meshes/<name>/ (roqsim_humanoid, roqsim_quadruped). resolve_model accepts both; follow whichever the package you are adding to already uses. Either way the meshes are per-model, never pooled in one dir, because Menagerie link names recur across robots. One consequence to know when borrowing: a folder-per-model provider sets MESHES_DIR to its models root, so a foreign model borrowing it via assets: names the mesh <model>/meshes/<file> (Frankie does this for the Panda’s meshes), whereas a flat provider’s is <model>/<file>.

  • New plugin checklist: subclass Plugin; implement only the hooks you need; add validate_config; register via the roqsim.plugins entry-point (built-ins) or reference by module:Class/file.py:Class; add a test.

13. Robot interface & transport bridges

A robot’s I/O is self-describing and transport-neutral, so it is not duplicated in a per-backend bridge and can be wired to any transport. It has three layers:

1. Endpoints (neutral, in the robot packages). A plugin declares its ports with decorators on the methods that serve them (roqsim.endpoint): @endpoint.out (the method returns the payload), @endpoint.command (a request with an outcome) and @endpoint.stream (an inbound stream, latest value wins). The method is the endpoint: its name is the endpoint’s name, its docstring’s first line the endpoint’s doc, and its signature the schema – a command’s or a stream’s parameters (types with the unit aliases of roqsim.types, defaults, docs from the docstring’s Args: section) and the return type become Endpoint.params and Endpoint.result, data any bridge reads. Payloads are neutral types: the dataclasses of roqsim.types (Twist, Pose, Odometry, JointState, JointPositions, Wrench, Imu, LaserScan, Image, CameraInfo, PointCloud, Transform, Transforms) or any dataclass of the plugin’s own, never positional tuples; an in endpoint names its type (@endpoint.stream(Twist)) and takes the fields it uses by name, and Endpoint.payload_type says what a transport carries. A bridge passes parameters by name, and write refuses a missing, unknown or mistyped one before queueing (ParameterError). Options name attributes or config keys (rate=, when=, lazy=, each=) rather than wrapping them in callables; the owner and namespace come from the plugin (endpoint_owner, endpoint_namespace; owner= for one that belongs elsewhere). The engine registers a plugin’s endpoints right after its configure (Plugin.register_endpoints), so an option may read what configure resolved, and a bridge listed later binds them; it then applies the plugin’s qos: to every endpoint the plugin registered, and the framework records its topics: renames as Endpoint.topic and renders a hint topic that names a sibling endpoint ("{image}/compressed") from where that sibling is carried (roqsim.endpoint.topic_of()). roqsim.endpoint.declared() lists a class’s endpoints with that schema without a world, and roqsim plugins describe publishes them, with how each installed transport (the roqsim.transports entry points) carries them. A port known only at run time is added with ctx.interface.add(Endpoint(...)). Either way an endpoint is (see roqsim.context.Endpoint): a name, direction ("out" → provide read; "in" → provide write), an owner (the entity), a namespace (a plain scope string each backend attaches to the endpoint’s topics/frames/actions), an optional rate_hz, and a backend dict of inert per-backend hints keyed by backend name, which for a decorated endpoint carries only its deviations from the type’s mapping (a frame, stamped, emit_tf, a QoS), and None to keep it off a backend. The read/write callables run on the physics thread. Crucially the robot packages import nothing transport-specific: a hand-built endpoint names its message type as a string under the backend hint, and a decorated one names none.

Entity poses are the core’s. Every entity whose body is in the model has an out endpoint sim/entities/<name>/pose (owner sim, roqsim.entity_pose): the body’s world position and (w, x, y, z) quaternion from xpos/xquat and its velocity from cvel, computed only when read, None while the entity is deleted, and movable, false for a body welded to the world (no joint on its chain to the world and not mocap), whose pose never changes. It carries no backend hint, so no bridge publishes it unasked, and it is registered even after a bridge bound, for a consumer that looks it up by name.

Marshalling is the framework’s. A decorated method runs on the physics thread and never posts itself. A command’s write is safe from any thread: it submits the method (submit()) and returns a CommandFuture, whose result(timeout) gives the caller what the method returned or re-raises what it raised. A stream’s write stores the payload in the endpoint’s StreamSlot, and drain_commands hands the newest one to the method once, after the queued commands; values superseded within a step are never applied. Such an endpoint is marshalled, and a bridge calls its write directly; any other in endpoint’s write is submitted to the physics thread by the bridge.

2. ``BridgeBase`` (backend-agnostic, in ``roqsim/bridge.py``). Shared machinery for every transport: it iterates ctx.interface, applies the optional owner filter, rate-gates each out endpoint, runs the per-tick publish loop on the physics thread, and marshals inbound data onto the physics thread via ctx.submit unless the endpoint marshals itself (single-writer rule intact, §7), handing the backend a callback that returns the command’s future. It binds an endpoint that carries a hint block for its backend, and a decorated one (Endpoint.transport) without one, from what its payload type maps to (_hints_for); a hint block of None keeps an endpoint off that backend. A backend that carries neutral payloads as they are (ipc) overrides _hints_for to bind every endpoint. A backend implements a few hooks: _setup / _hints_for / _make_output / _make_input / _publish / _now / _tick / _teardown. Each bridge records what it made of an endpoint (bound_name: a ROS topic after namespaces and renames), so another transport can say what the endpoint is called there. A write into a stream is tagged with the bridge’s backend, and two transports driving one stream within a second of each other are logged once, naming both.

The rate gate is tested once per physics step, so the publish rates a world can hold are exactly physics_rate / k for integer k — a request between two of them is served at one of them, as a different constant for the whole run rather than as jitter that averages out. The requested rate is therefore snapped to the nearest achievable one when the endpoint is bound (roqsim.rates, the same grid arithmetic a capture rate uses, and the same SNAP_QUIET / SNAP_NOTABLE bands for announcing the move in proportion to its size, naming the nearby achievable rates where it is large). Nearest, not rounded down: a snapped rate may be the faster neighbour, so a rate that is meant as a ceiling has to be one this world can hold. A gate built that way then counts steps rather than comparing sim-time — the spacing is the step count it was snapped to, which no accumulated float time can move.

The alternative — keeping the requested rate and advancing the deadline BY the period, so the spacing alternates (17, 17, 16, …) and the mean comes out right — is deliberately not taken: the spacing is what a consumer differentiates and what a filter’s dt is set from, so a rate that is right on average and wrong at every step buys a mean nobody observes with an alias somebody reads as the robot’s behaviour. It is the same alias the ROS bridge warns about when a coarse /clock quantises an output’s stamps.

Both numbers reach the run’s record: a recording’s provenance carries endpoint_rates, one row per gated publication — every bound output, plus the streams a backend publishes itself (a merged joint_states, /clock), which appear in no world document at all — with its requested_hz, its realised_hz and the every_steps behind it. So a rate quoted from the world document can be checked against the one the run actually published at without measuring arrival times.

3. A concrete backend (transport-aware, in its own package). roqsim_ros_bridge provides Ros2Bridge(BridgeBase) and one table from the neutral types to ROS messages (roqsim_ros_bridge/typemap.py, free of ROS imports): each type of roqsim.types and each scalar maps to its message (Twist to geometry_msgs/Twist, Odometry to nav_msgs/Odometry, …) with a converter each way, a stamped hint choosing between a message and its stamped form. typemap.resolve gives an endpoint’s effective hints – the message type (or a std_srvs/Trigger service for a command without parameters), the topic (roqsim.endpoint.topic_of(): the world’s topics: name, else the hint’s, else the endpoint’s name), the qos (the world’s qos:, else the hint’s, else default: reliable, depth 10) and the producer’s own frames – and the converters. A dataclass without a row maps by field name onto the message its hint names, checked when the bridge binds it: a field that does not fit is refused by name, never dropped. A package maps its own type once through the roqsim.ros2_types entry-point group; with neither, the endpoint is not on ROS, which roqsim plugins describe reports. A hand-built endpoint keeps the registry (roqsim_ros_bridge/registry.py): resolve_type turns the type string into a class via importlib (cached); converters keyed by that string fill an outbound message in place, decoders turn an inbound message into the positional payload its write takes, and a reflective path (msg.data = payload, and data inbound) covers primitive std_msgs with no registered converter. One converter per wire format, not per producer: the same rendered frame is published as sensor_msgs/Image or as sensor_msgs/CompressedImage purely by which type string an endpoint names, so a camera plugin offers a compressed stream without importing a codec (the encoder itself is roqsim/image_codec.py, and the fields of every sensor message are roqsim/ros_messages.py, both ROS-free so roqsim rebuild writes the same messages without ROS). Actions follow the same pattern one level up: an in endpoint whose ros2 hint block carries action (an action type string, e.g. control_msgs.action.FollowJointTrajectory) is served as an ActionServer whose goal-execution policy comes from a handler registry (roqsim_ros_bridge/actions.py) — so even MoveIt2 trajectory execution needs no dedicated bridge and no ROS import on the producer.

That policy includes what counts as done, which is a property of the joints rather than of the clock. FollowJointTrajectory grades its result on where the arm actually ended: the goal’s own goal_tolerance first, then the controller’s goal_tolerance config, then a deliberately loose default, and missing it aborts with GOAL_TOLERANCE_VIOLATED. Succeeding as soon as the last waypoint has been fed would make a blocked or saturated arm indistinguishable from one that did the job, and MoveIt forwards that verdict unchanged, so the caller would see a clean execution against a scene that never moved.

The rest of a JointTrajectoryController’s policy follows the controller’s hints where a robot states them (arm_controller’s path_tolerance, allow_partial_joints_goal, allow_nonzero_velocity_at_trajectory_end): a goal the controller would refuse is rejected before it executes, a joint trailing the trajectory by more than its path tolerance aborts it with PATH_TOLERANCE_VIOLATED, and a goal time tolerance of 0 waits for the joints without limit, upstream’s convention. Two of upstream’s rules hold for every arm, whether or not it states hints: one goal executes per controller, so a new one ends the running one with “Current goal cancelled due to new incoming action.”, and a goal that reaches its tolerance succeeds with “Goal successfully reached!” as its error_string. And a producer that cannot move now – arm_controller’s motion gate, closed by a driver interface – aborts its goal with the reason. These decisions are ROS-free (roqsim_ros_bridge/trajectory_policy.py) and tested without ROS.

The control socket (``ipc``). The second backend, roqsim.ipc.bridge.IpcBridge, is core roqsim behind the roqsim[ipc] extra (pyzmq), and roqsim sim adds it by default (--control, ROQSIM_CONTROL; none disables) together with the run_control plugin, which serves the driver’s RunControl as sim/run_control/{pause, resume, step, reset, state}, and entity_control, which serves roqsim.entity_control as sim/entities/{set_state, set_presence} – the same functions a stepped run’s scenario actions call, so a refusal reads the same over either. It wires every endpoint under a path built from the address of the plugin that registered it (Endpoint.producer, stamped by the registry while that plugin configures): robot.lidar + scan is robot/lidar/scan; two endpoints on one path are refused at bind naming both. It serves on demand and publishes on no schedule: a ROUTER answers describe / read / call on a background thread – a read is the endpoint’s read run on the physics thread through ctx.submit, a call a command’s future waited on, with a timeout that is an error and never a success – and an XPUB publishes, from post_step at each endpoint’s gated rate, only the outputs under a prefix some client subscribed to. With nobody subscribed its post_step checks two empty collections and returns. A command may name an out endpoint of its producer that confirms it (Endpoint.confirm); the reply carries that endpoint’s value read in the post_step of the step that applied the command, and while the run is paused it says verified: false rather than stepping. --no-communication keeps it: it reaches this process, not a middleware the experiment publishes on. The scenario-execution adapter never adds it – a stepped run is in-process. User-facing: Talking to a running simulation.

Injection, not authoring. A world does not declare its transport. with_transport appends the bridge at load time (roqsim sim --ros; ROQSIM_ROS for the scenario-execution adapter), which is the exact inverse of drop_transport_plugins and is what keeps a checked-in world ROS-free and therefore runnable in a pip-only environment where the bridge is not registered at all. Transport describes how a run is deployed; the world describes the experiment. Idempotent, so a world that does declare one is left alone.

Namespacing. One bridge serves the whole world. Each endpoint carries the namespace its producer declared (usually the spawn plugin’s namespace: config, inherited via the entity meta), and the backend attaches it to that endpoint’s topic (/robot1/odom), TF frames (robot1/base_link), and action name. The bridge-level namespace config is an optional global outer prefix for the whole sim; the owner filter remains for deliberately splitting endpoints across several transports.

Hardwired topics. A producer can pin an endpoint’s topic to an absolute name that ignores the namespace, so the sim matches an external / hardware topic layout exactly. Any endpoint-producing plugin accepts a topics: map keyed by endpoint role name — topics: {image: /camera/color/image_raw, joint_states: /joint_states} — which the framework records on a decorated endpoint (Endpoint.topic) and a hand-built one reads via Plugin.topic_override(name) (roqsim/plugin.py) when it fills the backend topic. An absolute topic (leading /) is published verbatim by the ROS backend (_resolve_topic in ros2_bridge.py), bypassing ep.namespace (and the node namespace); a relative topic renames the endpoint inside its namespace — how a robot manifest gives a second scanner the vendor’s scan2 under the robot’s namespace. Only the topic is overridden — TF frames stay namespaced. For example, a robot model can hardwire /joint_states and /camera/color/image_raw in its manifest so a sim world is a drop-in for the matching real robot + its operator UI (at the cost of being single-arm; see the manifest note).

Zero-copy / FPS. Message objects are preallocated once per endpoint and refilled each tick (reuse_messages, safe for inter-process subscribers); numeric arrays are handed to the message as matching-dtype numpy buffers (one C-level copy) instead of per-element Python loops. The ipc backend copies each array once on the physics thread, since a producer may overwrite its buffer in the next step, and hands that copy to ZeroMQ without another. Adding a new backend (zenoh) is a new BridgeBase subclass + its own registry — robots and worlds are unchanged.

14. Glossary & FAQ

  • spec vs model vs data: MjSpec is the editable scene description (mutate in build); MjModel is the compiled, immutable model; MjData is the mutable simulation state.

  • build phase: everything before spec.compile() — the only time to change scene structure.

  • driver: the code that owns the loop and calls the engine (standalone runner or the scenario-execution adapter).

  • gate: a named barrier for synchronous mode (§10).

  • Why a command queue instead of a lock? So plugin authors never reason about locks and mutation order is deterministic; the physics thread is the sole writer.

  • Can I spawn arbitrary bodies at runtime? Not by recompiling. A world declares everything a trial may bring in, and SpawnEntity / DeleteEntity activate one of those rather than creating it: see roqsim.presence. An absent entity keeps its pose and is excluded from raycasts, rendering and contacts, and from what GetEntities lists – all of it, its bodies with its root, so an absent walker leaves no limb behind. Parking it out of sight instead is the obvious alternative and is worse – a free body accelerates under gravity for as long as it is away, so it returns with whatever velocity it accumulated. An entry that registers an entity — any of them, which is what provides_entity declares — takes present: false to start it absent, which is how a world provides the spares for something that appears mid-trial; the declared value is re-applied on reset, because presence is a model field and mj_resetData restores data. Both are done from the engine, for the plugin’s declared entity, rather than by each plugin, so no plugin can accept the key and drop it. A plugin whose entity is registered by something under it — a population like boxes, whose instances are the entities — forwards it to them, since the engine sees the entry and not what the entry made. Absence also freezes the entity — compensated gravity, zeroed velocity — since taking a free body out of the contact set otherwise puts it in the very free fall the parking trick was rejected for. The gravity half is armed once per world, before compile, because MuJoCo decides there whether body_gravcomp is live at all.