"""Importing a `kk-scene-package/1` or `/2`.
The failures worth pinning here all produce a running simulation rather than an
error:
- a package handed to `train.py` puts one room at the world origin, so exactly
one environment is indoors and every other one trains on empty ground. It
trains, it converges, nothing reports it;
- a prop's position read with the wrong meaning puts the room's contents at the
origin, which is usually a plausible enough place to go unquestioned;
- an asset whose base name collides with another file is silently substituted,
because MuJoCo's asset lookup falls back to the base name;
- the world spliced into the host instead of attached rewrites the robot's joint
limits, mass and timestep, and compiles either way;
- `spawn` ignored puts the robot at the world origin, which on a real map is
inside a shelf or on a ramp -- and it still stands there, so it looks fine;
- the task's plane left under the package fills in its pits, and a narrow bridge
becomes a painted strip on a floor;
- a foot on the package's floor, platform or ramp is invisible to a contact
sensor that counts the body `terrain`, so the robot reads as airborne.
The package fixtures are built here rather than committed, so the manifest can be
perturbed one field at a time and every hash stays real.
"""
from __future__ import annotations
import hashlib
import json
import shutil
import struct
import zipfile
from pathlib import Path
import mujoco
import numpy as np
import pytest
from scenes.package import PackageError, is_package_path, load_package, read_package
#: A world with its own compiler settings and root defaults -- the two things
#: that rewrite a host robot when a package is spliced rather than attached.
WORLD = """
"""
#: The task's ground as mjlab builds it: a plane `terrain` in a body `terrain`,
#: attached through an identity frame (`mjlab.terrains.terrain_entity`).
TERRAIN = ('
'
'')
def _host(body: str = "", after: str = "") -> mujoco.MjSpec:
"""An environment the way `decorate` meets one: a ground, and whatever else."""
return mujoco.MjSpec.from_string(
f'{TERRAIN}{body}'
f"{after}"
)
def _compiled(package: Path, host: mujoco.MjSpec | None = None):
spec = host if host is not None else _host()
load_package(package).decorate(spec)
model = spec.compile()
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
return model, data
def _id(model, kind, name: str) -> int:
index = mujoco.mj_name2id(model, kind, name)
assert index >= 0, f"{name} is not in the compiled model"
return index
#: A prop written as its own model, the way kk-rl-mjlab writes one.
BALL = """
"""
def _bytes(body: str | bytes) -> bytes:
return body if isinstance(body, bytes) else body.encode()
def _manifest(files: dict[str, str | bytes], **overrides):
listed = {
name: {"bytes": len(_bytes(body)), "sha256": hashlib.sha256(_bytes(body)).hexdigest()}
for name, body in files.items()
}
manifest = {
"schema": "kk-scene-package/1",
"id": "fixture_room",
"description": "a room",
"use": "watching",
"world": {
"file": "scene.xml",
"assetDir": "assets",
"terrainType": "none",
"counts": {"geoms": 3, "bodies": 2, "lights": 1},
"decorativeGeoms": [],
"collidingGeoms": [],
"attach": {"prefix": "scn_"},
},
"props": [{"name": "kettle", "body": "kettle", "freeJoint": True,
"position": [0.4, 0.2, 0.3], "geoms": ["kettle_geom"]}],
"spawn": {"position": [-0.6, -1.2, 0.0], "yaw": 90.0, "site": "spawn"},
"rules": {},
"files": listed,
}
manifest.update(overrides)
return manifest
def write_package(root: Path, *, files: dict[str, str | bytes] | None = None,
**overrides) -> Path:
files = files if files is not None else {"scene.xml": WORLD}
root.mkdir(parents=True, exist_ok=True)
for name, body in files.items():
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(_bytes(body))
manifest = _manifest(files, **overrides)
(root / "scene-package.json").write_text(json.dumps(manifest, indent=2), "utf-8")
return root
#: What `/2` adds beside the world, as kingkong_design writes it. The two
#: previews share a base name on purpose: every map in that library does.
V2_EXTRA = {
"preview/preview.png": "the map, for people",
"robot/preview/preview.png": "the robot, for people",
"robot/skin-package.json": "{}",
}
def write_map(root: Path, *, files: dict[str, str | bytes] | None = None, **overrides) -> Path:
"""A `kk-scene-package/2`: the world, the robot beside it, a spawn."""
files = {**(files if files is not None else {"scene.xml": WORLD}), **V2_EXTRA}
overrides.setdefault("schema", "kk-scene-package/2")
overrides.setdefault("requiredCapabilities", ["rigid"])
return write_package(root, files=files, **overrides)
@pytest.fixture
def package(tmp_path):
return write_package(tmp_path / "room.scene")
def test_reads_a_package_and_names_how_to_mount_it(package):
read = read_package(package)
assert read.id == "fixture_room"
assert read.prefix == "scn_"
assert read.spawn["site"] == "spawn"
def test_reads_a_zip_and_keeps_the_files_alive(tmp_path):
"""A `.zip` is expanded somewhere temporary, and the world is not read until
mjlab builds the environment -- long after the reader returned."""
source = write_package(tmp_path / "room.scene")
archive = tmp_path / "room.scene.zip"
with zipfile.ZipFile(archive, "w") as zf:
for path in sorted(source.rglob("*")):
if path.is_file():
zf.write(path, path.relative_to(source).as_posix())
shutil.rmtree(source)
read = read_package(archive)
assert read.world.is_file()
# The temporary directory has to outlive the call that made it.
assert read.spec("scene.xml").compile().ngeom == 3
def test_reads_a_v2_map_and_hands_mujoco_only_its_world(tmp_path):
"""`/2` carries the robot the map was authored around and a thumbnail. The
robot here is the task's, and neither is handed to MuJoCo -- where every map
in kingkong_design's library would collide on `preview.png`.
The control is the same files declared as `/1`, where `robot/` and
`preview/` are ordinary directories: refused on that same base name, which
is what shows the collision in the fixture is real.
"""
read = read_package(write_map(tmp_path / "room.map"))
assert read.manifest["schema"] == "kk-scene-package/2"
assert not [name for name in read.assets() if name.startswith(("robot/", "preview/"))]
assert "scene.xml" in read.assets()
as_v1 = write_package(tmp_path / "room.scene", files={"scene.xml": WORLD, **V2_EXTRA})
with pytest.raises(PackageError, match="same file name"):
read_package(as_v1)
def test_refuses_a_version_it_does_not_know(tmp_path):
"""Read as the nearest known version, a `/3` would load and be wrong in
whatever way `/3` differs. The contract says an old consumer rejects it."""
with pytest.raises(PackageError, match="kk-scene-package/3"):
read_package(write_map(tmp_path / "room.map", schema="kk-scene-package/3"))
def test_refuses_a_v2_map_without_a_spawn(tmp_path):
with pytest.raises(PackageError, match="spawn"):
read_package(write_map(tmp_path / "room.map", spawn=None))
@pytest.mark.parametrize("spawn", [
{"position": [0.0, 0.0], "yaw": 0.0},
{"position": [0.0, 0.0, 0.0], "yaw": "90"},
{"position": [0.0, float("nan"), 0.0], "yaw": 0.0},
])
def test_refuses_a_spawn_that_cannot_be_placed(tmp_path, spawn):
with pytest.raises(PackageError, match="spawn"):
read_package(write_map(tmp_path / "room.map", spawn=spawn))
def test_refuses_a_capability_it_cannot_run(tmp_path):
"""Running it anyway is what the contract forbids: whatever needed the
capability would be dropped, and the rest would look complete."""
with pytest.raises(PackageError, match="teleport"):
read_package(write_map(tmp_path / "room.map",
requiredCapabilities=["rigid", "teleport"]))
assert read_package(write_map(tmp_path / "ok.map",
requiredCapabilities=["rigid", "hfield"])).id
def test_refuses_a_file_that_does_not_hash_to_what_was_declared(tmp_path):
root = write_package(tmp_path / "room.scene")
(root / "scene.xml").write_text(WORLD.replace("3 3 0.02", "9 9 0.02"), "utf-8")
with pytest.raises(PackageError, match="SHA-256"):
read_package(root)
def test_refuses_a_file_that_rode_along_undeclared(package):
(package / "assets").mkdir(exist_ok=True)
(package / "assets" / "extra.png").write_bytes(b"not declared")
with pytest.raises(PackageError, match="without being declared"):
read_package(package)
def test_refuses_two_files_with_the_same_base_name(tmp_path):
"""MuJoCo's asset lookup falls back to the base name, so these are one file
as far as it is concerned -- including against a robot's own mesh."""
root = write_package(
tmp_path / "room.scene",
files={"scene.xml": WORLD, "assets/pattern.png": "a", "extra/pattern.png": "b"},
)
with pytest.raises(PackageError, match="same file name"):
read_package(root)
def test_refuses_a_world_that_sets_the_hosts_physics(tmp_path):
root = write_package(
tmp_path / "room.scene",
files={"scene.xml": WORLD.replace("", '')},
)
with pytest.raises(PackageError, match="