"""Generate the MuJoCo chess scene for the SO-101 arm.
Outputs:
sim/assets/so101/so101.xml patched copy of the upstream arm (wrist camera added, base raised onto deck)
sim/chess_scene.xml full scene: table, rover deck, arm, board with 64 named square sites,
32 free chess pieces, capture bin, cameras, lights
Run: .venv/bin/python sim/make_scene.py
"""
from __future__ import annotations
import json
from dataclasses import dataclass
import re
from pathlib import Path
import numpy as np
import scene_environment as environment
HERE = Path(__file__).resolve().parent
ARM_DIR = HERE / "assets" / "so101"
UPSTREAM = ARM_DIR / "so101_camera_upstream.xml"
ARM_OUT = ARM_DIR / "so101.xml"
SCENE_OUT = HERE / "chess_scene.xml"
# Arm parts whose single upstream collision hull is replaced by several hulls:
# finger slabs (prepare_gripper_assets.py) and link decompositions (prepare_arm_collision.py).
ARM_HULLS = json.loads((ARM_DIR / "collision" / "manifest.json").read_text())["parts"]
# ---------------------------------------------------------------- geometry parameters (metres)
DECK_H = 0.06 # rover deck height; arm base sits on top of it
SQUARE = 0.025 # square size -> 20 cm board
BOARD_T = 0.008 # board thickness
BORDER = 0.012 # wooden border around the playing area
BOARD_CENTER = (0.21, 0.0) # x forward from arm base, y left
# Capture tray on the robot's right. At the Phase 1 spot (0.13, -0.20) the forearm hit
# the rover camera stalk on 8 of 9 release points; here all 9 clear it by 7 mm or more,
# and the tray stays at least 1 cm from the board under board-pose randomisation.
BIN_CENTER = (0.20, -0.18)
ROBOT_PLAYS = "black" # robot sits at rank 8 side; human at rank 1
@dataclass(frozen=True)
class Layout:
"""Board and tray geometry. The default is the nominal scene (chess_scene.xml);
phase 2 compiles random variants of it (piece_sets.sample_variant)."""
square: float = SQUARE
board_t: float = BOARD_T
border: float = BORDER
tray_half: tuple = (0.045, 0.035) # outer half extents of the tray floor
tray_rim: float = 0.020 # height of the rim centreline
NOMINAL = Layout()
TIMESTEP = 1 / 600 # 20 physics steps per 30 fps frame
# Stiff piece contacts: the gripper servo squeezes with up to 3.35 N m, about 40 N
# at the fingertips, which sank 2-3 mm into softer contacts. solmix makes these
# values dominate the arm's softer defaults in jaw-piece contacts.
PIECE_SOLREF = "0.005 1"
PIECE_SOLIMP = "0.97 0.995 0.0005"
FILES = "abcdefgh"
LIGHT_SQ = "0.98 0.97 0.94 1"
DARK_SQ = "0.95 0.93 0.90 1"
WHITE_PIECE = "0.93 0.88 0.76 1"
BLACK_PIECE = "0.14 0.11 0.09 1"
# Geometry, grasp points and estimated inertials come from the prepared mesh assets.
CHESS_DIR = HERE / "assets" / "chess"
PIECES = json.loads((CHESS_DIR / "manifest.json").read_text())["pieces"]
BACK_RANK = ["rook", "knight", "bishop", "queen", "king", "bishop", "knight", "rook"]
def square_xy(file_idx: int, rank_idx: int, square: float = SQUARE) -> tuple[float, float]:
"""Board-local xy of a square centre. file_idx 0..7 = a..h, rank_idx 0..7 = 1..8.
Robot (black) faces +x toward the human. Rank 8 is nearest the robot (small x).
From black's seat, file a is on the right (-y). The robot playing white is the
board turned half a turn (phase 2 randomises the board yaw).
"""
x = (3.5 - rank_idx) * square # rank 1 farthest (+x), rank 8 nearest
y = (file_idx - 3.5) * square # a at -y, h at +y
if ROBOT_PLAYS == "white":
x, y = -x, -y
return x, y
def lookat_xyaxes(pos, target, up=(0, 0, 1)) -> str:
pos, target, up = map(np.asarray, (pos, target, up))
f = target - pos
f /= np.linalg.norm(f)
right = np.cross(f, up)
right /= np.linalg.norm(right)
up_cam = np.cross(right, f)
return " ".join(f"{v:.5f}" for v in (*right, *up_cam))
def fmt(*vals) -> str:
return " ".join(f"{v:.5f}" for v in vals)
# ---------------------------------------------------------------- arm patch
def write_arm() -> None:
xml = UPSTREAM.read_text()
# compiler settings come from the scene file
xml = xml.replace('', "")
xml = xml.replace('', "")
# raise the base onto the rover deck
assert '
body x, cam y -> -body y, giving cam z = -body z with the jaws at the image bottom.
cam = ('\n'
' ')
assert xml.count("") == 1
xml = xml.replace("", cam)
# Only the printed-part finish changes; source meshes and joint/actuator data stay intact.
xml = xml.replace('rgba="1 0.82 0.12 1"',
'rgba="0.88 0.67 0.13 1" specular="0.12" shininess="0.2"')
# Contact shapes: each finger's single convex hull fills the gap between the jaws, and
# the bulky links' hulls are 1.7-4.3x the part, so the hand "hits" the shoulder in empty
# space. Each is replaced by several hulls in the same frame and class.
hull_meshes = []
for part, info in ARM_HULLS.items():
files = info["collision"]
pattern = re.compile(rf'( *)')
match = pattern.search(xml)
assert match and len(pattern.findall(xml)) == 1, part
indent, frame, material = match.groups()
geoms = [f'{indent}'
for i in range(len(files))]
xml = xml[:match.start()] + "\n".join(geoms) + xml[match.end():]
hull_meshes += [f' ' for i, f in enumerate(files)]
assert xml.count(" \n") == 1
xml = xml.replace(" \n", " \n" + "\n".join(hull_meshes) + "\n")
ARM_OUT.write_text(xml)
# ---------------------------------------------------------------- scene pieces
def chess_assets() -> str:
meshes = []
for kind, p in PIECES.items():
meshes.append(f'')
for i, file in enumerate(p["collision"]):
meshes.append(f'')
return "\n ".join(meshes)
def piece_body(name: str, kind: str, color: str, x: float, y: float, z: float,
quat: str = "1 0 0 0") -> str:
p = PIECES[kind]
# Group 2: visible mesh, never collides. Group 3: convex contact parts,
# hidden by the renderer/viewer but still active in physics.
geoms = [f'']
for i, _ in enumerate(p["collision"]):
geoms.append(f'')
inertia = " ".join(f"{v:.10g}" for v in p["fullinertia_kg_m2"])
com = " ".join(f"{v:.10g}" for v in p["center_of_mass_m"])
return f"""
{chr(10).join(geoms)}
"""
def build_scene(layout: Layout = NOMINAL) -> str:
SQUARE, BOARD_T, BORDER = layout.square, layout.board_t, layout.border
bx, by = BOARD_CENTER
half = 4 * SQUARE
board_top = BOARD_T # board body origin at table level; squares' top face at BOARD_T
# squares + sites (children of board body)
squares, sites = [], []
for r in range(8):
for f in range(8):
x, y = square_xy(f, r, SQUARE)
name = f"{FILES[f]}{r+1}"
dark = (f + r) % 2 == 0
material = "dark_square_mat" if dark else "light_square_mat"
squares.append(
f''
)
sites.append(f'')
# pieces in the starting position (world coordinates)
pieces, piece_qpos = [], []
for f in range(8):
for color, rank_back, rank_pawn, tag in (("white", 0, 1, "w"), ("black", 7, 6, "b")):
rgba = WHITE_PIECE if color == "white" else BLACK_PIECE
kind = BACK_RANK[f]
# The normalized knight faces +y; turn it toward the opponent (+x for black).
toward_positive_x = (color == "black") == (ROBOT_PLAYS == "black")
quat = "0.7071067812 0 0 -0.7071067812" if toward_positive_x else "0.7071067812 0 0 0.7071067812"
x, y = square_xy(f, rank_back, SQUARE)
pieces.append(piece_body(f"{tag}_{kind}_{FILES[f]}", kind, rgba, bx + x, by + y, board_top + 0.0005, quat))
piece_qpos.append(f"{fmt(bx + x, by + y, board_top + 0.0005)} {quat}")
x, y = square_xy(f, rank_pawn, SQUARE)
pieces.append(piece_body(f"{tag}_pawn_{FILES[f]}", "pawn", rgba, bx + x, by + y, board_top + 0.0005, quat))
piece_qpos.append(f"{fmt(bx + x, by + y, board_top + 0.0005)} {quat}")
# Folded rest pose. The earlier (-1.15, 1.1, 1.5) put the gripper servo's contact hull
# 1 mm inside the shoulder's; this one keeps 7 mm under +-0.06 rad of jitter.
home_arm = "0 -1.2 0.95 1.45 0 0.3"
# cameras
overhead_pos = environment.OVERHEAD_POS
overhead_xy = lookat_xyaxes(overhead_pos, (bx, by, BOARD_T), up=(-1, 0, 0))
rover_xy = lookat_xyaxes(environment.ROVER_CAMERA_POS, (bx, by, BOARD_T + 0.01))
side_xy = lookat_xyaxes((0.58, -0.85, 0.62), (0.12, 0.0, 0.18))
human_xy = lookat_xyaxes((0.72, 0.0, 0.32), (0.22, 0.0, 0.0))
return f"""
{chess_assets()}
{environment.assets()}
{environment.room()}
{environment.stand(DECK_H, rover_xy)}
{environment.camera_rig(overhead_pos, overhead_xy)}
{environment.cables()}
{environment.clutter()}
{chr(10).join(" " + s for s in squares)}
{chr(10).join(" " + s for s in sites)}
{environment.board_details(half, BORDER, BOARD_T)}
{environment.tray(*layout.tray_half, layout.tray_rim)}
{chr(10).join(pieces)}
"""
def main() -> None:
write_arm()
SCENE_OUT.write_text(build_scene())
import mujoco
m = mujoco.MjModel.from_xml_path(str(SCENE_OUT))
print(f"wrote {SCENE_OUT.relative_to(HERE.parent)}: nbody={m.nbody} ngeom={m.ngeom} nsite={m.nsite} ncam={m.ncam} nq={m.nq}")
if __name__ == "__main__":
main()