Skip to content

backends

ConnectionInfo dataclass

Python
ConnectionInfo(
    url: str,
    tunnel_command: str | None = None,
    warning: str | None = None,
)

How to reach a browser based viewer, shown in the Reloaded terminal UI.

url instance-attribute

Python
url: str

Address to open in a browser on the machine running Reloaded.

tunnel_command class-attribute instance-attribute

Python
tunnel_command: str | None = None

Command to run on a local machine to forward the viewer's port, when Reloaded is on a remote host.

warning class-attribute instance-attribute

Python
warning: str | None = None

Standing caution about the viewer, e.g. that it listens on every network interface without authentication.

OnReloadCallback

Bases: Protocol

Called with the model once it has been generated, so a viewer can show it.

ViewerBackend

Bases: Protocol

What Reloaded needs from a viewer.

A backend only shows state. It never owns the command loop, so the terminal UI and the unit tests can drive every backend the same way.

failure property

Python
failure: str | None

Why the viewer stopped when it was not the user closing it, or None.

viewer_lock property

Python
viewer_lock: (
    Callable[[], AbstractContextManager[Any]] | None
)

Lock the RuntimeManager holds while mutating model and data, or None if the viewer works on its own copy.

attach

Python
attach(controls: ViewerControls) -> None

Hands the viewer what its own buttons may ask for. Called once, before start.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def attach(self, controls: ViewerControls) -> None:
    """Hands the viewer what its own buttons may ask for. Called once, before `start`."""
    ...

start

Python
start(state: MjState) -> None

Opens the viewer on the initial model.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def start(self, state: MjState) -> None:
    """Opens the viewer on the initial model."""
    ...

close

Python
close() -> None

Shuts the viewer down and releases its resources.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def close(self) -> None:
    """Shuts the viewer down and releases its resources."""
    ...

is_running

Python
is_running() -> bool

Whether the viewer is still alive, e.g. its window has not been closed.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def is_running(self) -> bool:
    """Whether the viewer is still alive, e.g. its window has not been closed."""
    ...

on_reload

Python
on_reload(state: MjState) -> None

Shows a new or refreshed model. Called once the model is generated and again after a run finishes.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def on_reload(self, state: MjState) -> None:
    """Shows a new or refreshed model. Called once the model is generated and again after a run finishes."""
    ...

sync_hook

Python
sync_hook(
    state: MjState,
    arrows: list[ArrowConfig],
    lines: list[LineConfig],
) -> None

Pushes the current physics state and overlays to the viewer. Called by the RuntimeManager after every step.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def sync_hook(
    self, state: MjState, arrows: list[ArrowConfig], lines: list[LineConfig]
) -> None:
    """Pushes the current physics state and overlays to the viewer. Called by the `RuntimeManager` after every step."""
    ...

pump

Python
pump() -> None

Keeps the viewer responsive while no run is stepping physics, i.e. while idle or paused.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def pump(self) -> None:
    """Keeps the viewer responsive while no run is stepping physics, i.e. while idle or paused."""
    ...

connection_info

Python
connection_info() -> ConnectionInfo | None

How to reach the viewer from a browser, or None for a native window.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def connection_info(self) -> ConnectionInfo | None:
    """How to reach the viewer from a browser, or `None` for a native window."""
    ...

ViewerControls

Bases: Protocol

What a viewer's own buttons can ask of Reloaded. The controller implements it, so a button and the same word typed in the terminal do the same thing.

paused property

Python
paused: bool

Whether the run in progress is being held.

speed property

Python
speed: float

The playback speed: a multiple of real time, 0 for stepping by hand, or inf.

rerun

Python
rerun() -> None

Runs the last command again, if nothing is running.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/base.py
Python
def rerun(self) -> None:
    """Runs the last command again, if nothing is running."""
    ...

OpenGLBackend dataclass

Python
OpenGLBackend(xml_path: Callable[[], Path])

The classic MuJoCo viewer (mujoco.viewer.launch_passive): a native window drawn with OpenGL.

It needs a display, so over SSH it needs X11 forwarding. The viewer reads the model and data from its own thread, which is why the RuntimeManager holds viewer_lock while it steps physics.

xml_path instance-attribute

Python
xml_path: Callable[[], Path]

Gives the file the current model was written to, which the viewer shows in its title and reloads from.

StudioBackend dataclass

Python
StudioBackend(
    xml_path: Callable[[], Path],
    web: bool,
    port: int | None = None,
    gfx: StudioGraphics = DEFAULT,
    title: str = "MuJoCo Mojo Reloaded",
    studio: ReloadedStudioSettings = ReloadedStudioSettings(),
)

MuJoCo Studio, in a native window or in a browser.

Studio keeps its own copy of the model and data and shows what sync hands it, so unlike the classic viewer it never reads Mojo's data on its own. Mojo's runtime steps the physics, and this backend calls sync after steps and, when the runtime is not doing so, from a thread of its own, which keeps the viewer's buttons and camera alive. The viewer writes some things back into the data during sync (the Inspector's edits, dragging a body), so every sync and every step of the physics happens under one lock.

xml_path instance-attribute

Python
xml_path: Callable[[], Path]

Gives the file the current model was written to, which Studio shows in its title and keeps its camera by.

web instance-attribute

Python
web: bool

Whether to show Studio in a browser instead of a native window.

port class-attribute instance-attribute

Python
port: int | None = None

The first port to try for the browser viewer, or DEFAULT_WEB_PORT when not given.

gfx class-attribute instance-attribute

Python
gfx: StudioGraphics = DEFAULT

How the native window is drawn. The browser viewer ignores it.

studio class-attribute instance-attribute

Python
studio: ReloadedStudioSettings = field(
    default_factory=ReloadedStudioSettings
)

Which parts of Studio are showing when it opens.

ViewerUnavailableError

Bases: RuntimeError

The chosen viewer cannot run here. The message says why and what to use instead.

check_studio_available

Python
check_studio_available(ui: UserInterface) -> None

Raises ViewerUnavailableError if the Studio viewer chosen by ui cannot run with the installed MuJoCo.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/studio.py
Python
def check_studio_available(ui: UserInterface) -> None:
    """Raises `ViewerUnavailableError` if the Studio viewer chosen by `ui` cannot run with the installed MuJoCo."""
    if not studio_available():
        raise ViewerUnavailableError(
            f"The `{ui.value}` viewer needs MuJoCo Studio, which MuJoCo {mujoco.__version__} does not include. Use `-ui opengl` for now."
        )
    if ui is UserInterface.WEB and not web_client_available():
        raise ViewerUnavailableError(
            "The `web` viewer needs the Studio browser client, and this MuJoCo build does not have it. Use `-ui studio` or `-ui opengl`, or set MUJOCO_WEB_VIEWER_DIST to a directory with a built client."
        )
    # the native window exits the whole process if it cannot open the display, so this must be known before it starts
    problem = display_problem() if ui is UserInterface.STUDIO else None
    if problem is not None:
        raise ViewerUnavailableError(
            f"The `studio` viewer opens a window on this machine, but {problem}. Run Reloaded from a terminal on the machine's own desktop, check that `DISPLAY` is not being overridden (for example in ~/.bashrc), or use `-ui web` to see the model in a browser."
        )

route_web_server_logs

Python
route_web_server_logs() -> None

Has the browser viewer's server log through Reloaded's own logging, once the viewer is up.

The server reports each browser that connects or leaves, and why one is turned away, but it does so with a handler fixed to the terminal's stdout. Under the terminal UI that writes over the screen, and the messages are never seen. This swaps it for one that forwards to the root logger, and turns the server's debug messages on, since those say why a page is refused or is still waiting for the UI. They are few: one or two per page.

The server module is imported first. It sets up its logger the moment it is first imported, and gives up if the logger already has a handler, which would leave its quiet log level and its filter for harmless handshake errors unset.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/studio.py
Python
def route_web_server_logs() -> None:
    """
    Has the browser viewer's server log through Reloaded's own logging, once the viewer is up.

    The server reports each browser that connects or leaves, and why one is turned away, but it does so with a handler fixed to the terminal's stdout. Under the terminal UI that writes over the screen, and the messages are never seen. This swaps it for one that forwards to the root logger, and turns the server's debug messages on, since those say why a page is refused or is still waiting for the UI. They are few: one or two per page.

    The server module is imported first. It sets up its logger the moment it is first imported, and gives up if the logger already has a handler, which would leave its quiet log level and its filter for harmless handshake errors unset.
    """
    importlib.import_module("mujoco.studio.web.web_server")
    web_logger = logging.getLogger("WebServer")
    for handler in list(web_logger.handlers):
        if type(handler) is logging.StreamHandler:
            web_logger.removeHandler(handler)
    if not any(isinstance(h, _ForwardToRoot) for h in web_logger.handlers):
        web_logger.addHandler(_ForwardToRoot())
    web_logger.setLevel(logging.DEBUG)
    # the forwarder hands records to the root logger itself, so they must not also travel there on their own
    web_logger.propagate = False

studio_available

Python
studio_available() -> bool

Whether the installed MuJoCo includes Studio. Released builds do not yet, so this is only true for a build made from the MuJoCo source.

Source code in src/mujoco_mojo/utils/layers/reloaded/backends/studio.py
Python
def studio_available() -> bool:
    """Whether the installed MuJoCo includes Studio. Released builds do not yet, so this is only true for a build made from the MuJoCo source."""
    try:
        importlib.import_module("mujoco.studio._studio")
    except ImportError:
        return False
    return True

web_client_available

Python
web_client_available() -> bool

Whether the browser viewer can run: MuJoCo has its native state_payload bindings, and there is a client to serve. The client is the one in the mujoco-studio-wasm package (MuJoCo 4.0.1 and later), the one built into the mujoco.studio.web package (earlier releases), or the one MUJOCO_WEB_VIEWER_DIST points at.

Some builds (e.g. the 4.0.0 Windows wheel) have neither bindings nor a client, and a client from MUJOCO_WEB_VIEWER_DIST cannot make up for missing bindings.

The bindings are imported, not looked up with find_spec. They are a submodule of MuJoCo's compiled extension that mujoco.studio.web registers in sys.modules when it is first imported, so there is no file for find_spec to find, and it only reports them once something else has imported that package (the first call here used to say no and the second yes).

Source code in src/mujoco_mojo/utils/utils.py
Python
def web_client_available() -> bool:
    """
    Whether the browser viewer can run: MuJoCo has its native `state_payload` bindings, and there is a client to serve. The client is the one in the `mujoco-studio-wasm` package (MuJoCo 4.0.1 and later), the one built into the `mujoco.studio.web` package (earlier releases), or the one `MUJOCO_WEB_VIEWER_DIST` points at.

    Some builds (e.g. the 4.0.0 Windows wheel) have neither bindings nor a client, and a client from `MUJOCO_WEB_VIEWER_DIST` cannot make up for missing bindings.

    The bindings are imported, not looked up with `find_spec`. They are a submodule of MuJoCo's compiled extension that `mujoco.studio.web` registers in `sys.modules` when it is first imported, so there is no file for `find_spec` to find, and it only reports them once something else has imported that package (the first call here used to say no and the second yes).
    """
    try:
        importlib.import_module("mujoco.studio.web.state_payload")
    except ImportError:
        return False
    override = os.environ.get("MUJOCO_WEB_VIEWER_DIST")
    if override and Path(override).is_dir():
        return True
    if importlib.util.find_spec("mujoco_studio_wasm") is not None:
        return True
    spec = importlib.util.find_spec("mujoco.studio.web")
    if spec is None:
        return False
    return any(
        (Path(location) / "dist").is_dir()
        for location in spec.submodule_search_locations or []
    )