import json import os import random import re import pybullet as pb from pybullet_object_models import ycb_objects from llm_panda import config from llm_panda.robot_controller import RobotController from llm_panda.gripper_controller import GripperController from llm_panda.scene_manager import SceneManager _YCB_DATA = ycb_objects.getDataPath() def _load_ycb(folder, position, orientation=[0, 0, 0, 1]): """Load a YCB URDF at *position*.""" urdf = os.path.join(_YCB_DATA, folder, "model.urdf") flags = pb.URDF_USE_INERTIA_FROM_FILE | pb.URDF_USE_MATERIAL_COLORS_FROM_MTL body = pb.loadURDF(urdf, position, orientation, flags=flags) try: base_rgba = pb.getVisualShapeData(body)[0][7] if max(base_rgba[:3]) < 0.05: tex_path = os.path.join(_YCB_DATA, folder, "texture_map.png") if os.path.exists(tex_path): tex = pb.loadTexture(tex_path) pb.changeVisualShape(body, -1, textureUniqueId=tex, rgbaColor=[1, 1, 1, 1]) except Exception: pass return body class EnvBuilder: """Reads environment and scenario config files to build the PyBullet scene.""" def __init__(self, sim_client, env_json_path, rng_seed=0): self.client = sim_client self.env_json_path = env_json_path self.rng = random.Random(rng_seed) self.table_id = None self.tray_id = None self.robot_id = None self.pedestal_id = None self.scene = SceneManager() def load_configs(self): with open(self.env_json_path, 'r', encoding='utf-8') as f: self.env_data = json.load(f) catalog_ref = self.env_data.get("semantic_catalog") catalog = {} catalog_path = None if catalog_ref: catalog_path = catalog_ref if not os.path.isabs(catalog_path): catalog_path = os.path.join( os.path.dirname(os.path.abspath(self.env_json_path)), catalog_path, ) with open(catalog_path, "r", encoding="utf-8") as f: catalog = json.load(f) configured_objects = { obj["name"] for obj in self.env_data.get("objects", []) } described_objects = set(catalog.get("objects", {})) missing_objects = sorted(configured_objects - described_objects) if missing_objects: raise ValueError( "Semantic catalog is missing configured object(s): " + ", ".join(missing_objects) ) expected_surfaces = set() if "table" in self.env_data: expected_surfaces.add("table") if "tray" in self.env_data: expected_surfaces.add("tray") if "structures" in self.env_data: for s in self.env_data["structures"]: expected_surfaces.add(s["id"]) missing_surfaces = sorted( expected_surfaces - set(catalog.get("surfaces", {})) ) if missing_surfaces: raise ValueError( "Semantic catalog is missing surface(s): " + ", ".join(missing_surfaces) ) self.scene.set_semantic_catalog(catalog, source=catalog_path) # Dynamically patch config.py with loaded environment settings table = None tray = None if "table" in self.env_data: table = self.env_data["table"] if "tray" in self.env_data: tray = self.env_data["tray"] if "structures" in self.env_data: for s in self.env_data["structures"]: if s["id"] in ["table", "coffee_table", "workbench", "kitchen_island", "conveyor_belt", "sorting_table"]: table = s elif s.get("type") == "container": tray = s if table: pos = table.get("position", table.get("center", [0.55, 0.0, 0.075])) config.TABLE_CENTER = tuple(pos[:2]) config.TABLE_HALF_EXTENTS = tuple(table["half_extents"]) config.TABLE_BASE_Z = config.TABLE_HALF_EXTENTS[2] config.TABLE_TOP_Z = 2 * config.TABLE_HALF_EXTENTS[2] if tray: config.TRAY_POSITION = tuple(tray["position"]) config.TRAY_HALF_EXTENTS = tuple(tray["half_extents"]) config.ROBOT_BASE_Z = self.env_data["robot"]["base_position"][2] config.ROBOT_PEDESTAL_HALF = self.env_data["robot"]["pedestal_half_extent"] config.PANDA_URDF = self.env_data["robot"]["urdf"] def build_static_scene(self): pb.loadURDF("plane.urdf") self.structure_ids = {} if "structures" in self.env_data: for struct in self.env_data["structures"]: pos = struct.get("position", struct.get("center", [0, 0, 0])) if len(pos) == 2: pos = [pos[0], pos[1], struct["half_extents"][2]] ext = struct["half_extents"] color = struct.get("color", [0.8, 0.8, 0.8, 1.0]) stype = struct.get("type", "box") scale = struct.get("scale", 1.0) if stype == "urdf": urdf_path = struct["file"] orn = struct.get("orientation", [0, 0, 0, 1]) body_id = pb.loadURDF(urdf_path, pos, orn, useFixedBase=True, globalScaling=scale) else: col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=ext) vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=ext, rgbaColor=color) body_id = pb.createMultiBody(0, col, vis, pos) pb.changeDynamics(body_id, -1, lateralFriction=0.8) self.structure_ids[struct["id"]] = body_id if struct["id"] in ["table", "coffee_table", "workbench", "kitchen_island", "conveyor_belt", "sorting_table", "kitchen_counter", "fridge_unit", "bed_frame", "dresser", "desk"]: self.table_id = body_id if stype == "container" or struct["id"] in ["tray", "toy_basket", "decorative_tray", "paper_tray", "laundry_basket", "sink_basin"]: self.tray_id = body_id else: # Fallback for old env configs tx, ty = config.TABLE_CENTER hx, hy, hz = config.TABLE_HALF_EXTENTS t_color = self.env_data["table"]["color"] col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz]) vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz], rgbaColor=t_color) self.table_id = pb.createMultiBody(0, col, vis, [tx, ty, config.TABLE_BASE_Z]) pb.changeDynamics(self.table_id, -1, lateralFriction=0.8) thx, thy, thz = config.TRAY_HALF_EXTENTS tray_color = self.env_data["tray"]["color"] tray_col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz]) tray_vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz], rgbaColor=tray_color) trx, try_, trz = config.TRAY_POSITION self.tray_id = pb.createMultiBody(0, tray_col, tray_vis, [trx, try_, config.TABLE_TOP_Z - thz]) def spawn_robot(self): ped_half = config.ROBOT_PEDESTAL_HALF ped_h = config.ROBOT_BASE_Z if ped_h > 0: ped_col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[ped_half, ped_half, ped_h / 2]) ped_vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[ped_half, ped_half, ped_h / 2], rgbaColor=[0.3, 0.3, 0.33, 1.0]) self.pedestal_id = pb.createMultiBody(0, ped_col, ped_vis, [0, 0, ped_h / 2]) robot_pos = self.env_data["robot"]["base_position"] self.robot_id = pb.loadURDF(config.PANDA_URDF, robot_pos, useFixedBase=True) gripper = GripperController(self.robot_id) controller = RobotController(self.robot_id, gripper=gripper) controller.table_id = self.table_id controller.tray_id = self.tray_id for finger in config.FINGER_JOINT_INDICES: pb.changeDynamics(self.robot_id, finger, lateralFriction=1.2) controller.reset_to_home() return controller, gripper def spawn_objects(self): cx, cy = config.TABLE_CENTER hx, hy = config.TABLE_HALF_EXTENTS[0], config.TABLE_HALF_EXTENTS[1] m = config.TABLE_EDGE_MARGIN x_min, x_max = cx - hx + m, cx + hx - m y_min, y_max = cy - hy + m, cy + hy - m static_fallbacks = [ [x, y, config.TABLE_TOP_Z + 0.05] for y in (cy - 0.15, cy + 0.15) for x in (cx - 0.10, cx, cx + 0.10) ] spawned = [] objects = self.env_data.get("objects", []) for i, obj in enumerate(objects): obj_name = obj["name"] obj_class = obj["class"] spawn_pos = obj.get("position") spawn_ori = obj.get("orientation", [0, 0, 0, 1]) if spawn_pos is None: for _ in range(100): x = self.rng.uniform(x_min, x_max) y = self.rng.uniform(y_min, y_max) if all(((x - sx) ** 2 + (y - sy) ** 2) ** 0.5 >= 0.11 for sx, sy, _ in spawned): spawn_pos = [x, y, config.TABLE_TOP_Z + 0.05] break if spawn_pos is None: spawn_pos = static_fallbacks[i % len(static_fallbacks)] spawned.append(spawn_pos) source = obj.get("source", "ycb") if source == "pybullet_data": import pybullet_data urdf = os.path.join(pybullet_data.getDataPath(), obj["file"]) try: body = pb.loadURDF(urdf, spawn_pos, spawn_ori) except Exception as e: print(f"Failed to load pybullet_data {urdf}: {e}") continue else: body = _load_ycb(obj.get("folder", ""), spawn_pos, spawn_ori) if body is not None: self.scene.register_object(body, obj_name, obj_class) def spawn_catalog_object(self, folder, position, name=None): """Spawn and register one YCB catalog item at runtime. Runtime objects receive generic, data-driven semantics so they are immediately visible to scene state and adaptive LLM prompts without requiring an environment-specific hard-coded object list. """ folder_path = os.path.join(_YCB_DATA, folder) if not ( isinstance(folder, str) and folder.startswith("Ycb") and os.path.isdir(folder_path) and os.path.isfile(os.path.join(folder_path, "model.urdf")) ): raise ValueError(f"Unknown YCB catalog folder: {folder!r}") stem = folder[3:] or "object" base_name = re.sub(r"(?