Skip to content

studio

SYNC_PERIOD module-attribute

Python
SYNC_PERIOD = 1 / 100

The shortest time between two syncs from the runtime. Physics may step thousands of times a second, and the viewer cannot show them all.

PUMP_PERIOD module-attribute

Python
PUMP_PERIOD = 1 / 60

How often the viewer is synced while the runtime is not doing it, i.e. when idle, paused, or stepping slowly.

START_TIMEOUT module-attribute

Python
START_TIMEOUT = 5.0

How long to wait for the browser viewer to come up before giving up.

SETTLE_SECONDS module-attribute

Python
SETTLE_SECONDS = 0.5

How long the browser viewer is given, after the first model is published, before anything can connect to it. Studio's own code crashes, intermittently and without a Python error, if a page's UI connection arrives within the first few tenths of a second.

DEFAULT_WEB_PORT module-attribute

Python
DEFAULT_WEB_PORT = 8080

The first port tried for the browser viewer when none is given.

ViewerUnavailableError

Bases: RuntimeError

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

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.

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 []
    )

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

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