playful / chess-sim /code /sim /chess_world.py
Ali-Uraish's picture
Add files using upload-large-folder tool
9ffd3e8 verified
Raw History Blame Contribute Delete
7.27 kB
"""Board, squares and pieces of the generated chess scene, with helpers to place them.
The board is a static body. Its pose can be changed per episode through
`model.body_pos` / `model.body_quat`; square sites move with it.
"""
from __future__ import annotations
import mujoco
import numpy as np
FILES = "abcdefgh"
SQUARES = [f"{f}{r}" for r in range(1, 9) for f in FILES]
KINDS = ("pawn", "rook", "knight", "bishop", "queen", "king")
SYMBOL_KIND = dict(p="pawn", r="rook", n="knight", b="bishop", q="queen", k="king")
# Parking spots for pieces that are off the board: on the floor far from the table, out
# of every camera's view even when the table is slid so the floor shows.
PARK_ORIGIN = np.array([-2.2, 1.9, -0.735])
def quat_yaw(yaw: float) -> np.ndarray:
return np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)])
def yaw_of(mat: np.ndarray) -> float:
R = mat.reshape(3, 3)
return float(np.arctan2(R[1, 0], R[0, 0]))
class ChessWorld:
def __init__(self, m: mujoco.MjModel):
self.m = m
self.board = m.body("board").id
self.bin = m.body("bin").id
self.pieces = [m.body(i).name for i in range(m.nbody) if m.body(i).name.startswith(("w_", "b_"))]
self.body = {n: m.body(n).id for n in self.pieces}
self.kind = {n: n.split("_")[1] for n in self.pieces}
self.color = {n: n[0] for n in self.pieces}
self.qadr = {n: m.jnt_qposadr[m.body(n).jntadr[0]] for n in self.pieces}
self.vadr = {n: m.jnt_dofadr[m.body(n).jntadr[0]] for n in self.pieces}
self.square_local = {s: m.site(f"sq_{s}").pos.copy() for s in SQUARES}
self.board_top = float(self.square_local["a1"][2])
self.square_size = float(np.linalg.norm(self.square_local["b1"] - self.square_local["a1"]))
self.nominal_board_pos = m.body_pos[self.board].copy()
self.nominal_bin_pos = m.body_pos[self.bin].copy()
# Piece geometry, per kind, from the collision geoms of one body of that kind.
self.height, self.foot_radius = {}, {}
for kind in KINDS:
name = next(n for n in self.pieces if self.kind[n] == kind)
pts = self._collision_points(name)
self.height[kind] = float(pts[:, 2].max())
self.foot_radius[kind] = float(np.linalg.norm(pts[pts[:, 2] < 0.002, :2], axis=1).max())
# Tray interior (bin frame), from the geoms of scene_environment.tray: 2 mm walls,
# felt liner on the 4 mm floor, rounded rim (1.2 mm radius) on the wall tops.
floor = m.geom("tray_floor").id
wall = m.geom("tray_wall_y_1").id
self.bin_half = m.geom_size[floor][:2] - 0.002
self.bin_floor = 0.0041
self.bin_rim = float(m.geom_pos[wall][2] + m.geom_size[wall][2]) + 0.0012
self.table = m.body("table").id
self.nominal_table_pos = m.body_pos[self.table].copy()
def _collision_points(self, name):
bid = self.body[name]
out = []
for g in np.flatnonzero((self.m.geom_bodyid == bid) & (self.m.geom_group == 3)):
mid = self.m.geom_dataid[g]
v = self.m.mesh_vert[self.m.mesh_vertadr[mid]:self.m.mesh_vertadr[mid] + self.m.mesh_vertnum[mid]]
R = np.zeros(9)
mujoco.mju_quat2Mat(R, self.m.geom_quat[g])
out.append(v @ R.reshape(3, 3).T + self.m.geom_pos[g])
return np.concatenate(out)
# ------------------------------------------------------------------ board pose
def set_board_pose(self, offset_xy, yaw):
self.m.body_pos[self.board] = self.nominal_board_pos + [offset_xy[0], offset_xy[1], 0]
self.m.body_quat[self.board] = quat_yaw(yaw)
def board_yaw(self) -> float:
q = self.m.body_quat[self.board]
return float(2 * np.arctan2(q[3], q[0]))
def board_to_world(self, local_xyz) -> np.ndarray:
yaw = self.board_yaw()
c, s = np.cos(yaw), np.sin(yaw)
local = np.asarray(local_xyz, float)
x = c * local[..., 0] - s * local[..., 1]
y = s * local[..., 0] + c * local[..., 1]
return np.stack([x, y, local[..., 2]], -1) + self.m.body_pos[self.board]
def square_center(self, square: str) -> np.ndarray:
"""World position of a square centre on the board surface."""
return self.board_to_world(self.square_local[square])
def square_corners(self, square: str, grow=0.0) -> np.ndarray:
h = self.square_size / 2 + grow
c = self.square_local[square]
local = np.array([[c[0] - h, c[1] - h, c[2]], [c[0] + h, c[1] - h, c[2]],
[c[0] + h, c[1] + h, c[2]], [c[0] - h, c[1] + h, c[2]]])
return self.board_to_world(local)
def bin_center(self) -> np.ndarray:
return self.m.body_pos[self.bin] + [0, 0, self.bin_floor]
def bin_yaw(self) -> float:
q = self.m.body_quat[self.bin]
return float(2 * np.arctan2(q[3], q[0]))
def bin_point(self, u, v, z=0.0) -> np.ndarray:
"""World point at (u, v) in the tray's own frame, `z` above its felt floor."""
c, s = np.cos(self.bin_yaw()), np.sin(self.bin_yaw())
return self.bin_center() + [c * u - s * v, s * u + c * v, z]
def bin_corners(self) -> np.ndarray:
hx, hy = self.bin_half
return np.array([self.bin_point(u, v) for u, v in ((-hx, -hy), (hx, -hy), (hx, hy), (-hx, hy))])
def in_bin(self, pos) -> bool:
rel = np.asarray(pos)[:2] - self.m.body_pos[self.bin][:2]
c, s = np.cos(self.bin_yaw()), np.sin(self.bin_yaw())
local = np.array([c * rel[0] + s * rel[1], -s * rel[0] + c * rel[1]])
return bool(np.all(np.abs(local) < self.bin_half + 0.002) and pos[2] < self.bin_rim + 0.03)
def square_at(self, pos) -> str | None:
"""The square whose area contains world point `pos`, or None."""
yaw = self.board_yaw()
c, s = np.cos(yaw), np.sin(yaw)
rel = np.asarray(pos)[:2] - self.m.body_pos[self.board][:2]
local = np.array([c * rel[0] + s * rel[1], -s * rel[0] + c * rel[1]])
for sq, p in self.square_local.items():
if np.all(np.abs(local - p[:2]) < self.square_size / 2):
return sq
return None
# ------------------------------------------------------------------ pieces
def place(self, d, name, xyz, quat):
a = self.qadr[name]
d.qpos[a:a + 3] = xyz
d.qpos[a + 3:a + 7] = quat
v = self.vadr[name]
d.qvel[v:v + 6] = 0
def place_on_square(self, d, name, square, offset_xy=(0, 0), yaw=0.0):
c = self.square_center(square)
self.place(d, name, [c[0] + offset_xy[0], c[1] + offset_xy[1], self.board_top + 0.0002],
quat_yaw(yaw))
def park(self, d, name):
i = self.pieces.index(name)
self.place(d, name, PARK_ORIGIN + [0.035 * (i % 8), 0.035 * (i // 8), 0], [1, 0, 0, 0])
def base_pos(self, d, name) -> np.ndarray:
return d.xpos[self.body[name]].copy()
def tilt_deg(self, d, name) -> float:
return float(np.degrees(np.arccos(np.clip(d.xmat[self.body[name]][8], -1, 1))))
def on_board(self, d, name) -> bool:
p = self.base_pos(d, name)
return abs(p[2] - self.board_top) < 0.01 and self.square_at(p) is not None