add modified sru-navigation-sim (added go2 code)

This commit is contained in:
MattMa
2026-07-13 15:13:55 +08:00
parent 9e8f17bab0
commit 58b25cb40a
86 changed files with 10524 additions and 0 deletions
@@ -0,0 +1,63 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Maze terrain generation for navigation tasks.
This module provides:
- Maze terrain generation with various obstacle types
- Stair/platform terrain for elevation training
- Pit terrain with negative obstacles
- Monkey-patches for Isaac Lab terrain system integration
- Optimized mesh generation for reduced GPU memory
Key files:
- terrain_constants.py: Centralized height values and thresholds
- hf_terrains_maze.py: Terrain generation functions
- hf_terrains_maze_cfg.py: Terrain configurations
- patches.py: Isaac Lab integration patches
"""
# Patches first (no Isaac Sim required)
from .patches import apply_terrain_patches
# Constants (no Isaac Sim required)
from .terrain_constants import (
HEIGHTS,
THRESHOLDS,
PADDING,
STAIRS,
HeightValues,
SamplingThresholds,
VERTICAL_SCALE,
HORIZONTAL_SCALE,
CELL_SIZE,
CELL_PIXELS,
)
# Terrain generation (requires Isaac Sim)
from .hf_terrains_maze_cfg import HfMazeTerrainCfg
from .hf_terrains_maze import maze_terrain
from .maze_config import MAZE_TERRAIN_CFG
__all__ = [
# Patches
"apply_terrain_patches",
# Constants
"HEIGHTS",
"THRESHOLDS",
"PADDING",
"STAIRS",
"HeightValues",
"SamplingThresholds",
"VERTICAL_SCALE",
"HORIZONTAL_SCALE",
"CELL_SIZE",
"CELL_PIXELS",
# Terrain configs
"HfMazeTerrainCfg",
"MAZE_TERRAIN_CFG",
# Terrain functions
"maze_terrain",
]
@@ -0,0 +1,714 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Maze terrain generation for navigation tasks.
This module generates terrain height fields with explicit valid position masks.
The key simplification is that terrain generation directly outputs:
- `heights`: Actual terrain heights for rendering/physics
- `valid_mask`: Boolean mask of valid goal/spawn positions
This eliminates the need for complex height-based classification in goal sampling.
The terrain data is stored on the config during generation, then picked up by
the patches system and stored on TerrainImporter for access via:
- self.env.scene.terrain._height_field_visual
- self.env.scene.terrain._height_field_valid_mask
- self.env.scene.terrain._height_field_platform_mask
"""
from __future__ import annotations
import numpy as np
from dataclasses import dataclass, field
from scipy.ndimage import binary_dilation, rotate, shift
from typing import TYPE_CHECKING, Tuple
import torch
from isaaclab.terrains.height_field.utils import height_field_to_mesh
from .terrain_constants import HEIGHTS, PADDING, STAIRS, OBSTACLES, ObstacleType
if TYPE_CHECKING:
from . import hf_terrains_maze_cfg
# =============================================================================
# Terrain Data Container
# =============================================================================
@dataclass
class TerrainData:
"""Container for terrain height field and valid position mask.
Attributes:
heights: Height field for rendering/physics (actual terrain heights).
valid_mask: Boolean mask where True = valid for goals/spawns.
platform_mask: Boolean mask where True = elevated platform (for curriculum).
"""
heights: np.ndarray
valid_mask: np.ndarray
platform_mask: np.ndarray = field(default_factory=lambda: np.array([]))
@classmethod
def create(cls, width: int, height: int) -> "TerrainData":
"""Create empty terrain data with ground-level heights."""
return cls(
heights=np.zeros((width, height), dtype=np.int16),
valid_mask=np.ones((width, height), dtype=bool), # Start all valid
platform_mask=np.zeros((width, height), dtype=bool),
)
def set_obstacle(
self,
x_start: int, x_end: int,
y_start: int, y_end: int,
height_value: int
):
"""Set a region as an obstacle (invalid for goals)."""
self.heights[x_start:x_end, y_start:y_end] = height_value
self.valid_mask[x_start:x_end, y_start:y_end] = False
def set_platform(
self,
x_start: int, x_end: int,
y_start: int, y_end: int,
height_value: int
):
"""Set a region as a platform (valid for goals, elevated)."""
self.heights[x_start:x_end, y_start:y_end] = height_value
self.valid_mask[x_start:x_end, y_start:y_end] = True
self.platform_mask[x_start:x_end, y_start:y_end] = True
def set_ground(self, x_start: int, x_end: int, y_start: int, y_end: int):
"""Set a region as flat ground (valid for goals)."""
self.heights[x_start:x_end, y_start:y_end] = HEIGHTS.GROUND
self.valid_mask[x_start:x_end, y_start:y_end] = True
self.platform_mask[x_start:x_end, y_start:y_end] = False
def apply_padding(self, padding_cells: int):
"""Dilate invalid regions by padding cells for safety margin."""
obstacles = ~self.valid_mask
kernel = np.ones((2 * padding_cells + 1, 2 * padding_cells + 1), dtype=bool)
dilated = binary_dilation(obstacles, structure=kernel)
self.valid_mask = ~dilated
def create_spawn_mask(self, spawn_padding_cells: int) -> np.ndarray:
"""Create a mask for spawn positions with larger padding than goals."""
extra_padding = spawn_padding_cells - PADDING.GOAL_PADDING
if extra_padding > 0:
obstacles = ~self.valid_mask
kernel = np.ones((2 * extra_padding + 1, 2 * extra_padding + 1), dtype=bool)
dilated = binary_dilation(obstacles, structure=kernel)
return ~dilated
return self.valid_mask.copy()
def exclude_borders(self, border_cells: int = 2):
"""Mark terrain borders as invalid."""
self.valid_mask[:border_cells, :] = False
self.valid_mask[-border_cells:, :] = False
self.valid_mask[:, :border_cells] = False
self.valid_mask[:, -border_cells:] = False
def apply_height_transition_padding(self, height_threshold: int, padding_cells: int):
"""Mark cells near height transitions as invalid."""
grad_x = np.abs(np.diff(self.heights, axis=0, prepend=self.heights[:1, :]))
grad_y = np.abs(np.diff(self.heights, axis=1, prepend=self.heights[:, :1]))
grad_x_back = np.abs(np.diff(self.heights, axis=0, append=self.heights[-1:, :]))
grad_y_back = np.abs(np.diff(self.heights, axis=1, append=self.heights[:, -1:]))
max_grad = np.maximum.reduce([grad_x, grad_y, grad_x_back, grad_y_back])
transition_mask = (max_grad >= height_threshold).astype(bool)
if padding_cells > 0:
kernel = np.ones((2 * padding_cells + 1, 2 * padding_cells + 1), dtype=bool)
transition_mask = binary_dilation(transition_mask, structure=kernel).astype(bool)
self.valid_mask = self.valid_mask & ~transition_mask
def get_cell_bounds(
cell_x: int, cell_y: int, cell_pixels: int, max_x: int, max_y: int
) -> Tuple[int, int, int, int]:
"""Get pixel bounds for a maze cell with clamping.
Returns:
Tuple of (x_start, x_end, y_start, y_end).
"""
return (
max(0, cell_x * cell_pixels),
min(max_x, (cell_x + 1) * cell_pixels),
max(0, cell_y * cell_pixels),
min(max_y, (cell_y + 1) * cell_pixels),
)
# =============================================================================
# Maze Generation
# =============================================================================
def generate_maze(
rng: np.random.Generator,
width: int,
height: int,
open_prob: float
) -> np.ndarray:
"""Generate maze using DFS with random openings.
Args:
rng: Random number generator for reproducibility.
width: Maze width in cells.
height: Maze height in cells.
open_prob: Probability of random wall removal.
Returns:
2D array where 1=wall, 0=path.
"""
maze = np.ones((width, height), dtype=np.uint8)
stack = [(0, 0)]
maze[0, 0] = 0
while stack:
x, y = stack[-1]
neighbors = []
for dx, dy in [(-2, 0), (2, 0), (0, -2), (0, 2)]:
nx, ny = x + dx, y + dy
if 0 <= nx < width and 0 <= ny < height and maze[nx, ny] == 1:
neighbors.append((nx, ny))
if neighbors:
idx = rng.integers(len(neighbors))
nx, ny = neighbors[idx]
maze[(x + nx) // 2, (y + ny) // 2] = 0
maze[nx, ny] = 0
stack.append((nx, ny))
else:
stack.pop()
# Random openings
maze[rng.random((width, height)) < open_prob] = 0
return maze
def clear_center(maze: np.ndarray, terrain: TerrainData, cell_pixels: int):
"""Clear the center area for spawning."""
cx, cy = maze.shape[0] // 2, maze.shape[1] // 2
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if abs(dx) + abs(dy) <= 1: # Plus shape
nx, ny = cx + dx, cy + dy
if 0 <= nx < maze.shape[0] and 0 <= ny < maze.shape[1]:
maze[nx, ny] = 0
x_start = (cx - 1) * cell_pixels
x_end = (cx + 2) * cell_pixels
y_start = (cy - 1) * cell_pixels
y_end = (cy + 2) * cell_pixels
terrain.set_ground(x_start, x_end, y_start, y_end)
# =============================================================================
# Obstacle Generators
# =============================================================================
def make_pillar(
_rng: np.random.Generator,
size: int,
wall_height: int,
scale: float,
is_pit: bool,
thickness: int
) -> np.ndarray:
"""Generate a centered pillar obstacle."""
grid = np.zeros((size, size), dtype=np.int16)
h = int(wall_height * scale) * (-1 if is_pit else 1)
grid[thickness:size-thickness, thickness:size-thickness] = h
return grid
def make_bar(
rng: np.random.Generator,
size: int,
wall_height: int,
scale: float,
is_pit: bool,
thickness: int
) -> np.ndarray:
"""Generate a rotated bar obstacle."""
grid = np.zeros((size, size), dtype=np.int16)
center = size // 2
h = int(wall_height * scale)
grid[center - thickness//2:center + thickness//2, :] = h
angle = rng.uniform(-180, 180)
grid = rotate(grid, angle, reshape=False, order=1).astype(np.int16)
if is_pit:
grid = -grid
return grid
def make_cross(
rng: np.random.Generator,
size: int,
wall_height: int,
scale: float,
is_pit: bool,
thickness: int
) -> np.ndarray:
"""Generate a cross-shaped obstacle."""
grid = np.zeros((size, size), dtype=np.int16)
center = size // 2
h = int(wall_height * scale)
grid[center - thickness//2:center + thickness//2, :] = h
grid[:, center - thickness//2:center + thickness//2] = h
angle = rng.uniform(-180, 180)
grid = rotate(grid, angle, reshape=False, order=1).astype(np.int16)
if is_pit:
grid = -grid
return grid
def make_shifted_block(
rng: np.random.Generator,
size: int,
wall_height: int,
scale: float,
is_pit: bool,
thickness: int
) -> np.ndarray:
"""Generate a randomly shifted block."""
grid = np.zeros((size, size), dtype=np.int16)
h = int(wall_height * scale)
grid[thickness:size-thickness, thickness:size-thickness] = h
room = max(0, size // 2 - thickness)
shift_amt = (
rng.integers(-room, room + 1),
rng.integers(-room, room + 1)
)
grid = shift(grid, shift=shift_amt, cval=0).astype(np.int16)
if is_pit:
grid = -grid
return grid
# Obstacle generator lookup table
_OBSTACLE_GENERATORS = {
ObstacleType.PILLAR: make_pillar,
ObstacleType.BAR: make_bar,
ObstacleType.CROSS: make_cross,
ObstacleType.SHIFTED_BLOCK: make_shifted_block,
}
def make_random_obstacle(
rng: np.random.Generator,
size: int,
wall_height: int,
is_pit: bool | None = None,
pillar_weight: float | None = None
) -> np.ndarray:
"""Generate a random obstacle type.
Args:
rng: Random number generator.
size: Size of the obstacle grid in pixels.
wall_height: Height of walls in terrain units.
is_pit: Force pit (True) or wall (False). None = random.
pillar_weight: Weight for pillars (0-1). None = uniform distribution.
"""
scale = rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX)
if is_pit is None:
is_pit = rng.random() < OBSTACLES.DEFAULT_PIT_PROB
thickness = rng.integers(OBSTACLES.THICKNESS_MIN, OBSTACLES.THICKNESS_MAX)
# Select obstacle type (with optional pillar weighting)
if pillar_weight is not None and pillar_weight > 0:
# Weighted selection: pillar_weight for pillars, rest split evenly
other_weight = (1.0 - pillar_weight) / (ObstacleType.NUM_TYPES - 1)
weights = [other_weight] * ObstacleType.NUM_TYPES
weights[ObstacleType.PILLAR] = pillar_weight
obstacle_type = rng.choice(ObstacleType.NUM_TYPES, p=weights)
else:
# Uniform selection
obstacle_type = rng.integers(ObstacleType.NUM_TYPES)
generator = _OBSTACLE_GENERATORS[obstacle_type]
return generator(rng, size, wall_height, scale, is_pit, thickness)
# =============================================================================
# Stair/Platform Generator
# =============================================================================
class StairGenerator:
"""Generates stair structures with platforms."""
LAYOUTS = [
{"platforms": [(1, 0), (1, 1), (1, 2), (0, 1), (2, 1)],
"stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "w")]},
{"platforms": [(0, 1), (1, 1), (2, 1)],
"stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "n")]},
{"platforms": [(0, 1), (1, 1), (2, 1), (1, 0), (1, 2)],
"stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "n")]},
]
def __init__(self, wall_height: float, vertical_scale: float):
self.wall_height = wall_height
self.platform_height = int(wall_height - 0.5 / vertical_scale)
self.vertical_scale = vertical_scale
self._make_stair_templates()
def _make_stair_templates(self):
"""Create stair templates for each direction."""
cell_px = STAIRS.SINGLE_CELL_PIXELS
step_res = cell_px // STAIRS.NUM_STEPS
east = np.zeros((cell_px, cell_px), dtype=np.float32)
for i in range(STAIRS.NUM_STEPS):
h = STAIRS.STEP_HEIGHT_METERS * (i + 1) / self.vertical_scale
east[i * step_res:(i + 1) * step_res, :] = h
self.templates = {
"e": east,
"n": rotate(east, 90),
"w": rotate(east, 180),
"s": rotate(east, 270),
}
def generate(self, rng: np.random.Generator) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Generate a 3x3 stair/platform structure.
Args:
rng: Random number generator.
Returns:
Tuple of (heights, valid_mask, platform_mask).
"""
layout = self.LAYOUTS[rng.integers(len(self.LAYOUTS))]
size = STAIRS.STAIR_GRID_SIZE * STAIRS.SINGLE_CELL_PIXELS
cell_px = STAIRS.SINGLE_CELL_PIXELS
heights = np.zeros((size, size), dtype=np.float32)
valid_mask = np.zeros((size, size), dtype=bool)
platform_mask = np.zeros((size, size), dtype=bool)
for gx, gy in layout["platforms"]:
xs, xe = gx * cell_px, (gx + 1) * cell_px
ys, ye = gy * cell_px, (gy + 1) * cell_px
heights[xs:xe, ys:ye] = self.platform_height
valid_mask[xs:xe, ys:ye] = True
platform_mask[xs:xe, ys:ye] = True
for gx, gy, direction in layout["stairs"]:
xs, xe = gx * cell_px, (gx + 1) * cell_px
ys, ye = gy * cell_px, (gy + 1) * cell_px
heights[xs:xe, ys:ye] = self.templates[direction]
return heights, valid_mask, platform_mask
# =============================================================================
# Main Terrain Generation
# =============================================================================
def _get_rng(cfg: "hf_terrains_maze_cfg.HfMazeTerrainCfg") -> np.random.Generator:
"""Get RNG from config or create a new one."""
if cfg.rng is not None:
return cfg.rng
# Fallback: create unseeded RNG (non-reproducible)
return np.random.default_rng()
@height_field_to_mesh
def maze_terrain(difficulty: float, cfg: "hf_terrains_maze_cfg.HfMazeTerrainCfg") -> np.ndarray:
"""Generate maze terrain with obstacles and valid position mask.
Args:
difficulty: Terrain difficulty (0-1).
cfg: Terrain configuration.
Returns:
Height field for mesh generation.
"""
rng = _get_rng(cfg)
# Setup dimensions
cell_pixels = int(cfg.cell_size / cfg.horizontal_scale)
wall_height = int(cfg.wall_height / cfg.vertical_scale)
terrain_w = int(cfg.size[0] / cfg.horizontal_scale)
terrain_h = int(cfg.size[1] / cfg.horizontal_scale)
terrain = TerrainData.create(terrain_w, terrain_h)
stair_gen = StairGenerator(wall_height, cfg.vertical_scale)
# Generate base pattern
if cfg.non_maze_terrain:
maze = np.zeros(cfg.grid_size, dtype=np.uint8)
obstacle_prob = difficulty * OBSTACLES.NON_MAZE_DENSITY
maze[rng.random(cfg.grid_size) < obstacle_prob] = 1
else:
maze = generate_maze(rng, cfg.grid_size[0], cfg.grid_size[1], 1 - difficulty)
clear_center(maze, terrain, cell_pixels)
# Generate terrain features based on type
if cfg.dynamic_obstacles:
_add_pits(rng, terrain, cfg, difficulty, wall_height, cell_pixels)
elif cfg.stairs:
_add_stairs(rng, terrain, cfg, difficulty, wall_height, cell_pixels, stair_gen)
else:
_add_walls(rng, maze, terrain, cfg, wall_height, cell_pixels)
clear_center(maze, terrain, cell_pixels)
# Apply height transition padding for stair terrain
if cfg.stairs:
terrain.apply_height_transition_padding(
height_threshold=PADDING.HEIGHT_TRANSITION_THRESHOLD,
padding_cells=PADDING.HEIGHT_TRANSITION_PADDING
)
# Apply safety padding and border exclusion
terrain.apply_padding(PADDING.GOAL_PADDING)
terrain.exclude_borders(PADDING.BORDER_CELLS)
# Create spawn mask with larger padding
spawn_mask = terrain.create_spawn_mask(PADDING.SPAWN_PADDING)
spawn_mask[:PADDING.BORDER_CELLS, :] = False
spawn_mask[-PADDING.BORDER_CELLS:, :] = False
spawn_mask[:, :PADDING.BORDER_CELLS] = False
spawn_mask[:, -PADDING.BORDER_CELLS:] = False
# Store data on cfg for patches to pick up
if cfg.add_goal:
cfg.height_field_visual = torch.from_numpy(terrain.heights.copy()).unsqueeze(0)
cfg.height_field_valid_mask = torch.from_numpy(terrain.valid_mask.copy()).unsqueeze(0)
cfg.height_field_platform_mask = torch.from_numpy(terrain.platform_mask.copy()).unsqueeze(0)
cfg.height_field_spawn_mask = torch.from_numpy(spawn_mask.copy()).unsqueeze(0)
return terrain.heights
# =============================================================================
# Terrain Type Generators
# =============================================================================
def _add_walls(
rng: np.random.Generator,
maze: np.ndarray,
terrain: TerrainData,
cfg,
wall_height: int,
cell_pixels: int
):
"""Add wall obstacles to terrain based on maze pattern."""
# Use pillar weighting for non-maze terrain (more thin pillars)
pillar_weight = OBSTACLES.NON_MAZE_PILLAR_WEIGHT if cfg.non_maze_terrain else None
for x in range(cfg.grid_size[0]):
for y in range(cfg.grid_size[1]):
if maze[x, y] != 1:
continue
xs, xe, ys, ye = get_cell_bounds(
x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
)
if cfg.randomize_wall and rng.random() < cfg.random_wall_ratio:
obs = make_random_obstacle(rng, cell_pixels, wall_height, pillar_weight=pillar_weight)
terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys]
terrain.valid_mask[xs:xe, ys:ye] = False
else:
h = int(wall_height * rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX))
terrain.set_obstacle(xs, xe, ys, ye, h)
def _add_stairs(
rng: np.random.Generator,
terrain: TerrainData,
cfg,
difficulty: float,
wall_height: int,
cell_pixels: int,
stair_gen: StairGenerator
):
"""Add stair/platform structures to terrain."""
grid_w, grid_h = cfg.grid_size
grid_middle = grid_w // 2
excluded = set(range(grid_middle - 1, grid_middle + 1))
# Compute stair placement locations (avoid center and edges)
# Stairs are 3x3, so max position is grid_size - 4 to fit with margin
stair_margin = 1
max_x = grid_w - STAIRS.STAIR_GRID_SIZE - stair_margin
max_y = grid_h - STAIRS.STAIR_GRID_SIZE - stair_margin
num_locations = 6
x_locs = set(np.round(np.linspace(stair_margin, max_x, num_locations)).astype(int)) - excluded
y_locs = set(np.round(np.linspace(stair_margin, max_y, num_locations)).astype(int)) - excluded
processed = set()
stair_size = STAIRS.STAIR_GRID_SIZE * STAIRS.SINGLE_CELL_PIXELS
stair_prob = difficulty * OBSTACLES.STAIRS_PLACEMENT_PROB
obstacle_prob = difficulty * OBSTACLES.STAIRS_OBSTACLE_DENSITY
for x in range(grid_w):
for y in range(grid_h):
if (x, y) in processed:
continue
# Try placing stair structure at valid locations
if x in x_locs and y in y_locs and rng.random() < stair_prob:
heights, valid, platform = stair_gen.generate(rng)
xs = x * cell_pixels
xe = min(terrain.heights.shape[0], xs + stair_size)
ys = y * cell_pixels
ye = min(terrain.heights.shape[1], ys + stair_size)
sx, sy = xe - xs, ye - ys
terrain.heights[xs:xe, ys:ye] = heights[:sx, :sy]
terrain.valid_mask[xs:xe, ys:ye] = valid[:sx, :sy]
terrain.platform_mask[xs:xe, ys:ye] = platform[:sx, :sy]
# Mark 3x3 area as processed
for dx in range(3):
for dy in range(3):
processed.add((x + dx, y + dy))
elif rng.random() < obstacle_prob:
xs, xe, ys, ye = get_cell_bounds(
x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
)
# Check if area is clear before placing
if terrain.valid_mask[xs + 1:xe - 1, ys + 1:ye - 1].all():
obs = make_random_obstacle(rng, cell_pixels, wall_height)
terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys]
terrain.valid_mask[xs:xe, ys:ye] = False
def _add_pits(
rng: np.random.Generator,
terrain: TerrainData,
cfg,
difficulty: float,
wall_height: int,
cell_pixels: int
):
"""Add pit/trough obstacles to terrain.
Layout:
- Two horizontal pit trenches with random bridges for crossing
- Random obstacles (mostly pits) scattered in the middle area
"""
grid_w, grid_h = cfg.grid_size
# Pit trench rows (near top and bottom)
trench_offset = OBSTACLES.PITS_TRENCH_ROW_OFFSET
pit_rows = {trench_offset, grid_h - trench_offset - 1}
# Generate bridge positions for crossing pit trenches
bridges = _generate_bridges(rng, grid_w)
# Add pit trenches (negative height = troughs)
for pit_y in pit_rows:
for x in range(grid_w):
if x in bridges:
continue
xs, xe, ys, ye = get_cell_bounds(
x, pit_y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
)
terrain.set_obstacle(xs, xe, ys, ye, -wall_height)
# Add random obstacles in middle area (between pit trenches)
_add_middle_obstacles(rng, terrain, cfg, difficulty, wall_height, cell_pixels, pit_rows)
def _generate_bridges(rng: np.random.Generator, grid_width: int) -> set:
"""Generate bridge positions across pit rows.
Returns set of x-coordinates where bridges (gaps in pits) are placed.
Bridges are 2 cells wide for easier robot crossing.
"""
num_bridges = rng.integers(OBSTACLES.BRIDGE_COUNT_MIN, OBSTACLES.BRIDGE_COUNT_MAX)
margin = OBSTACLES.PITS_EDGE_MARGIN
available = list(range(margin, grid_width - margin))
rng.shuffle(available)
bridges = set()
for i in range(min(num_bridges, len(available))):
pos = available[i]
bridges.add(pos)
# Make bridges 2 cells wide
if pos + 1 < grid_width - margin:
bridges.add(pos + 1)
return bridges
def _add_middle_obstacles(
rng: np.random.Generator,
terrain: TerrainData,
cfg,
difficulty: float,
wall_height: int,
cell_pixels: int,
pit_rows: set
):
"""Add random obstacles in the middle area between pit rows."""
grid_w, grid_h = cfg.grid_size
obstacle_prob = difficulty * OBSTACLES.PITS_DENSITY
# Compute valid placement bounds (avoid edges and pit rows)
margin = OBSTACLES.PITS_EDGE_MARGIN
trench_offset = OBSTACLES.PITS_TRENCH_ROW_OFFSET
x_range = range(margin, grid_w - margin)
# Middle area: between the two pit trenches, with 1 cell buffer
y_range = range(trench_offset + 1, grid_h - trench_offset - 1)
# Iterate only over valid cells (more efficient)
for x in x_range:
for y in y_range:
if y in pit_rows:
continue
if rng.random() < obstacle_prob:
xs, xe, ys, ye = get_cell_bounds(
x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
)
obs = _generate_pit_obstacle(rng, cell_pixels, wall_height)
terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys]
terrain.valid_mask[xs:xe, ys:ye] = False
def _generate_pit_obstacle(
rng: np.random.Generator,
cell_pixels: int,
wall_height: int
) -> np.ndarray:
"""Generate an obstacle for pit terrain with high pit probability.
Distribution:
- 60% bars (75% negative/pits) -> 45% pit bars
- 40% random shapes (50% negative/pits) -> 20% pit shapes
- Total: ~65% negative obstacles
"""
if rng.random() < OBSTACLES.PITS_BAR_RATIO:
# Bar obstacle with high pit probability
is_pit = rng.random() < OBSTACLES.PITS_BAR_PIT_PROB
scale = rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX)
thickness = rng.integers(OBSTACLES.THICKNESS_MIN, OBSTACLES.THICKNESS_MAX)
return make_bar(rng, cell_pixels, wall_height, scale, is_pit, thickness)
else:
# Random obstacle type (pillar, cross, block) with moderate pit probability
is_pit = rng.random() < OBSTACLES.PITS_RANDOM_PIT_PROB
return make_random_obstacle(rng, cell_pixels, wall_height, is_pit=is_pit)
@@ -0,0 +1,111 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Configuration for maze height field terrains."""
from dataclasses import MISSING
from typing import Any, Optional
import numpy as np
import torch
from isaaclab.utils import configclass
from isaaclab.terrains.height_field.hf_terrains_cfg import HfTerrainBaseCfg
from . import hf_terrains_maze
@configclass
class HfMazeTerrainCfg(HfTerrainBaseCfg):
"""Configuration for a maze height field terrain.
This terrain generates a procedural maze with configurable wall structures,
obstacles, and optional stairs. The maze can be used for navigation tasks
with various difficulty levels.
Height Field Data (set during terrain generation):
- height_field_visual: Heights for Z-lookup (num_terrains, W, H)
- height_field_valid_mask: Valid goal positions with safety padding
- height_field_platform_mask: Platform positions for curriculum
- height_field_spawn_mask: Valid spawn positions with larger padding
"""
function = hf_terrains_maze.maze_terrain
# =========================================================================
# Height Field Storage (populated during terrain generation)
# =========================================================================
height_field_visual: torch.Tensor = None
"""Height field for Z-lookup (actual terrain heights)."""
height_field_valid_mask: torch.Tensor = None
"""Boolean mask of valid goal positions (padded with GOAL_PADDING)."""
height_field_platform_mask: torch.Tensor = None
"""Boolean mask of platform positions for curriculum learning."""
height_field_spawn_mask: torch.Tensor = None
"""Boolean mask of valid spawn positions (larger padding for robot body)."""
# =========================================================================
# Maze Generation Parameters
# =========================================================================
maze: bool = True
"""Flag indicating this is a maze terrain."""
open_probability: float = None
"""Probability of a cell being open in the maze."""
grid_size: tuple[int, int] = (15, 15)
"""Size of the maze grid (number of cells in width and height)."""
cell_size: float = 2.0
"""Size of each cell in the maze grid (in meters)."""
wall_height: float = 1.5
"""Height of the walls (in meters). Defaults to 1.5."""
# =========================================================================
# Terrain Features
# =========================================================================
add_goal: Any = MISSING
"""Enable goal sampling data generation."""
add_noise_to_flat: Any = MISSING
"""Add noise to flat areas of the maze."""
randomize_wall: Any = MISSING
"""Use randomized obstacle shapes instead of full walls."""
random_wall_ratio: float = 0.5
"""Mix ratio between randomized and standard walls. Defaults to 0.5."""
non_maze_terrain: bool = False
"""Use non-maze terrain with random obstacles. Defaults to False."""
stairs: bool = False
"""Add stairs to empty map. Defaults to False."""
add_stairs_to_maze: bool = False
"""Add stairs to the maze. Defaults to False."""
dynamic_obstacles: bool = False
"""Enable pit/trough obstacles. Defaults to False."""
# =========================================================================
# Random Number Generator
# =========================================================================
rng: Optional[np.random.Generator] = None
"""Random number generator for reproducible terrain generation.
Set by the terrain generator (patches.py) before calling the terrain function.
If None, will create a new unseeded generator (non-reproducible).
"""
@@ -0,0 +1,72 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Configuration for maze terrains."""
from isaaclab.terrains.terrain_generator_cfg import TerrainGeneratorCfg
from .hf_terrains_maze_cfg import HfMazeTerrainCfg
MAZE_TERRAIN_CFG = TerrainGeneratorCfg(
size=(30.0, 30.0),
border_width=30.0, # Border around the entire terrain grid (not per-tile)
num_rows=6,
num_cols=30,
horizontal_scale=0.1,
vertical_scale=0.005,
slope_threshold=0.75,
use_cache=False,
curriculum=False,
difficulty_range=(0.5, 1.0),
sub_terrains={
"maze": HfMazeTerrainCfg(
proportion=0.3,
open_probability=0.9,
grid_size=(15, 15),
cell_size=2.0,
add_noise_to_flat=False,
add_goal=True,
randomize_wall=True,
random_wall_ratio=0.5,
add_stairs_to_maze=True,
),
"non_maze": HfMazeTerrainCfg(
proportion=0.2,
open_probability=0.9,
grid_size=(15, 15),
cell_size=2.0,
add_noise_to_flat=False,
add_goal=True,
randomize_wall=True,
random_wall_ratio=1.0,
non_maze_terrain=True,
),
"stairs": HfMazeTerrainCfg(
proportion=0.3,
open_probability=0.9,
grid_size=(15, 15),
cell_size=2.0,
add_noise_to_flat=False,
add_goal=True,
randomize_wall=False,
random_wall_ratio=1.0,
non_maze_terrain=False,
stairs=True,
),
"pits": HfMazeTerrainCfg(
proportion=0.2,
open_probability=0.9,
grid_size=(15, 15),
cell_size=2.0,
add_noise_to_flat=False,
add_goal=True,
randomize_wall=True,
random_wall_ratio=1.0,
non_maze_terrain=True,
dynamic_obstacles=True, # Enables pit/trough generation
),
},
)
"""Maze terrain configuration for navigation tasks."""
@@ -0,0 +1,550 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Monkey-patches for Isaac Lab terrain system to support navigation tasks.
This module patches TerrainGenerator and TerrainImporter to:
1. Store height field data for goal/spawn sampling
2. Use optimized mesh generation to reduce GPU memory
The patches add these attributes to TerrainImporter (accessed via env.scene.terrain):
- _height_field_visual: Heights for Z-lookup (num_terrains, W, H)
- _height_field_valid_mask: Valid goal positions with safety padding
- _height_field_platform_mask: Platform positions for curriculum
- _height_field_spawn_mask: Valid spawn positions with larger padding
"""
from __future__ import annotations
import os
from typing import TYPE_CHECKING
import numpy as np
import torch
import trimesh
if TYPE_CHECKING:
from isaaclab.terrains.terrain_generator import TerrainGenerator
from isaaclab.terrains.terrain_importer import TerrainImporter
# Flag to track if patches have been applied
_patches_applied = False
# Shared storage for passing height field data from TerrainGenerator to TerrainImporter
# Works because TerrainImporter creates TerrainGenerator synchronously in __init__
_height_field_storage = {
"height_field_visual": None,
"height_field_valid_mask": None,
"height_field_platform_mask": None,
"height_field_spawn_mask": None,
}
def apply_terrain_patches():
"""Apply monkey-patches to Isaac Lab terrain classes.
Patches applied:
1. height_field_to_mesh - optimized mesh generation (reduces GPU memory)
2. TerrainGenerator - collects height field data for goal sampling
3. TerrainImporter - stores height field data as attributes
4. PinholeCameraPatternCfg - adds from_ros_camera_info convenience method
Safe to call multiple times - patches are only applied once.
"""
global _patches_applied
if _patches_applied:
return
_patch_height_field_to_mesh()
_patch_terrain_generator()
_patch_terrain_importer()
_patch_pinhole_camera_pattern_cfg()
_patches_applied = True
def _convert_height_field_to_mesh_with_optimization_dynamic(
height_field: np.ndarray, horizontal_scale: float, vertical_scale: float, block_size: int = 20
) -> tuple[np.ndarray, np.ndarray]:
"""Convert a height-field array to a triangle mesh, optimizing large flat ground blocks (20x20, 10x10, 5x5).
This function optimizes mesh generation by detecting flat regions and simplifying them
to just 2 triangles instead of generating full detail. It uses a hierarchical approach:
- 20x20 blocks are checked first
- Non-flat blocks are subdivided into 10x10, then 5x5
- Only 5x5 or smaller blocks with height variation get full detail
This can dramatically reduce vertex count for terrains with large flat areas,
significantly reducing GPU memory usage during simulation.
Args:
height_field: The input height-field array.
horizontal_scale: The discretization of the terrain along the x and y axis.
vertical_scale: The discretization of the terrain along the z axis.
block_size: Initial block size for optimization (default 20).
Returns:
The vertices and triangles of the mesh:
- **vertices** (np.ndarray(float)): Array of shape (num_vertices, 3).
- **triangles** (np.ndarray(int)): Array of shape (num_triangles, 3).
"""
num_rows, num_cols = height_field.shape
vertices = []
triangles = []
vertex_count = 0
def process_block(i, j, block_size):
"""Process a block and decide whether to simplify or subdivide into smaller blocks."""
nonlocal vertex_count
# Skip if starting position is at or beyond the terrain bounds
if i >= num_rows or j >= num_cols:
return
# Determine block dimensions within bounds of the height field
block_end_row = min(i + block_size + 1, num_rows) # +1 to handle the right and bottom edges
block_end_col = min(j + block_size + 1, num_cols) # +1 to handle the right and bottom edges
# Extract the block of height data
block = height_field[i:block_end_row, j:block_end_col]
# Skip empty or single-element blocks (can't form triangles)
if block.size == 0 or block.shape[0] < 2 or block.shape[1] < 2:
return
# Check if the entire block is flat (all heights are the same)
if np.all(block == block[0, 0]):
# Simplify the block by using two large triangles for the whole flat region
v0 = [i * horizontal_scale, j * horizontal_scale, block[0, 0] * vertical_scale]
v1 = [block_end_row * horizontal_scale, j * horizontal_scale, block[0, 0] * vertical_scale]
v2 = [i * horizontal_scale, block_end_col * horizontal_scale, block[0, 0] * vertical_scale]
v3 = [block_end_row * horizontal_scale, block_end_col * horizontal_scale, block[0, 0] * vertical_scale]
# Add the vertices for the large triangles
vertices.extend([v0, v1, v2, v3])
# Add the two triangles for the block
triangles.append([vertex_count, vertex_count + 1, vertex_count + 2])
triangles.append([vertex_count + 1, vertex_count + 3, vertex_count + 2])
vertex_count += 4
else:
# If block is not flat and the block size is larger than 5x5, subdivide into smaller blocks
if block_size > 5:
half_size = block_size // 2
# Process each of the four quadrants of the block
process_block(i, j, half_size)
process_block(i + half_size, j, half_size)
process_block(i, j + half_size, half_size)
process_block(i + half_size, j + half_size, half_size)
else:
# If block size is 5x5 or smaller, generate detailed triangles for each grid point
for x in range(block_end_row - i):
for y in range(block_end_col - j):
# Get the height at this point
z = block[x, y] * vertical_scale
v = [(i + x) * horizontal_scale, (j + y) * horizontal_scale, z]
vertices.append(v)
# Now create triangles for all internal points including the last row and last column
for x in range(block_end_row - i - 1): # Handle rows, including the last row
for y in range(block_end_col - j - 1): # Handle columns, including the last column
ind0 = vertex_count + x * (block_end_col - j) + y
ind1 = ind0 + 1
ind2 = ind0 + (block_end_col - j)
ind3 = ind2 + 1
# Create two triangles for this grid cell
triangles.append([ind0, ind3, ind1])
triangles.append([ind0, ind2, ind3])
vertex_count += (block_end_row - i) * (block_end_col - j)
# Start by processing blocks with the initial block size (20x20)
for i in range(0, num_rows, block_size):
for j in range(0, num_cols, block_size):
process_block(i, j, block_size)
vertices = np.array(vertices)
triangles = np.array(triangles)
# Return vertices and triangles arrays
return vertices, triangles
def _patch_height_field_to_mesh():
"""Patch height_field_to_mesh decorator to use optimized mesh generation.
This patch replaces the mesh generation in the height_field_to_mesh decorator
with an optimized version that reduces vertex count for flat terrain regions,
significantly reducing GPU memory usage during simulation with many environments.
"""
import copy
import functools
from isaaclab.terrains.height_field import utils as hf_utils
def _patched_height_field_to_mesh(func):
"""Patched decorator that uses optimized mesh generation."""
@functools.wraps(func)
def wrapper(difficulty: float, cfg):
# check valid border width
if cfg.border_width > 0 and cfg.border_width < cfg.horizontal_scale:
raise ValueError(
f"The border width ({cfg.border_width}) must be greater than or equal to the"
f" horizontal scale ({cfg.horizontal_scale})."
)
# allocate buffer for height field (with border)
width_pixels = int(cfg.size[0] / cfg.horizontal_scale) + 1
length_pixels = int(cfg.size[1] / cfg.horizontal_scale) + 1
border_pixels = int(cfg.border_width / cfg.horizontal_scale) + 1
heights = np.zeros((width_pixels, length_pixels), dtype=np.int16)
# override size of the terrain to account for the border
sub_terrain_size = [width_pixels - 2 * border_pixels, length_pixels - 2 * border_pixels]
sub_terrain_size = [dim * cfg.horizontal_scale for dim in sub_terrain_size]
# update the config
terrain_size = copy.deepcopy(cfg.size)
cfg.size = tuple(sub_terrain_size)
# generate the height field
z_gen = func(difficulty, cfg)
# handle the border for the terrain
heights[border_pixels:-border_pixels, border_pixels:-border_pixels] = z_gen
# set terrain size back to config
cfg.size = terrain_size
# PATCH: Use optimized mesh generation to reduce GPU memory usage
vertices, triangles = _convert_height_field_to_mesh_with_optimization_dynamic(
heights, cfg.horizontal_scale, cfg.vertical_scale, 20
)
mesh = trimesh.Trimesh(vertices=vertices, faces=triangles)
# compute origin
x1 = int((cfg.size[0] * 0.5 - 1) / cfg.horizontal_scale)
x2 = int((cfg.size[0] * 0.5 + 1) / cfg.horizontal_scale)
y1 = int((cfg.size[1] * 0.5 - 1) / cfg.horizontal_scale)
y2 = int((cfg.size[1] * 0.5 + 1) / cfg.horizontal_scale)
origin_z = np.max(heights[x1:x2, y1:y2]) * cfg.vertical_scale
origin = np.array([0.5 * cfg.size[0], 0.5 * cfg.size[1], origin_z])
# return mesh and origin
return [mesh], origin
return wrapper
# Apply patch to the height_field_to_mesh decorator
hf_utils.height_field_to_mesh = _patched_height_field_to_mesh
def _patch_terrain_generator():
"""Patch TerrainGenerator to collect height field data for goal sampling."""
from isaaclab.terrains.terrain_generator import TerrainGenerator
from isaaclab.terrains.utils import color_meshes_by_height
from isaaclab.utils.timer import Timer
from isaaclab.utils.io import dump_yaml
from isaaclab.utils.dict import dict_to_md5_hash
# Height field attribute names we collect
_HEIGHT_FIELD_ATTRS = [
"height_field_visual",
"height_field_valid_mask",
"height_field_platform_mask",
"height_field_spawn_mask",
]
def _patched_init(self, cfg, device: str = "cpu"):
"""Patched __init__ that collects height field data."""
# Validate inputs
if len(cfg.sub_terrains) == 0:
raise ValueError("No sub-terrains specified in the configuration!")
if cfg.curriculum and cfg.difficulty_range is None:
raise ValueError("Curriculum learning requires 'difficulty_range' to be specified!")
# Store inputs
self.cfg = cfg
self.device = device
# Set common values for all sub-terrains
for sub_cfg in self.cfg.sub_terrains.values():
sub_cfg.size = self.cfg.size
sub_cfg.horizontal_scale = self.cfg.horizontal_scale
sub_cfg.vertical_scale = self.cfg.vertical_scale
sub_cfg.slope_threshold = self.cfg.slope_threshold
# Set seed for reproducibility
# - seed=None (default): random terrain each time (for training variety)
# - seed=<int>: reproducible terrain (for debugging/evaluation)
# Note: Always create RNG because Isaac Lab's base code uses self.np_rng
self.np_rng = np.random.default_rng(self.cfg.seed)
self._reproducible = self.cfg.seed is not None
# Initialize buffers
self.flat_patches = {}
self.terrain_meshes = []
self.terrain_origins = np.zeros((self.cfg.num_rows, self.cfg.num_cols, 3))
# PATCH: Temporary lists to collect height field data during generation
self._height_field_lists = {attr: [] for attr in _HEIGHT_FIELD_ATTRS}
# Generate terrains
if self.cfg.curriculum:
with Timer("[INFO] Generating terrains based on curriculum took"):
self._generate_curriculum_terrains()
else:
with Timer("[INFO] Generating terrains randomly took"):
self._generate_random_terrains()
# Add border and combine meshes
self._add_terrain_border()
self.terrain_mesh = trimesh.util.concatenate(self.terrain_meshes)
# PATCH: Consolidate collected height fields into tensors and store in shared storage
for attr in _HEIGHT_FIELD_ATTRS:
data_list = self._height_field_lists[attr]
if data_list:
setattr(self, attr, torch.cat(data_list, dim=0))
_height_field_storage[attr] = getattr(self, attr)
else:
setattr(self, attr, None)
_height_field_storage[attr] = None
del self._height_field_lists # Free memory
# Color the terrain mesh
if self.cfg.color_scheme == "height":
self.terrain_mesh = color_meshes_by_height(self.terrain_mesh)
elif self.cfg.color_scheme == "random":
self.terrain_mesh.visual.vertex_colors = self.np_rng.choice(
range(256), size=(len(self.terrain_mesh.vertices), 4)
)
elif self.cfg.color_scheme != "none":
raise ValueError(f"Unknown color scheme: {self.cfg.color_scheme}")
# Move flat patches to device
for name in self.flat_patches:
self.flat_patches[name] = self.flat_patches[name].to(self.device)
def _patched_get_terrain_mesh(self, difficulty: float, cfg) -> tuple:
"""Patched _get_terrain_mesh that collects height field data from each terrain."""
# Copy configuration and set parameters
cfg = cfg.copy()
cfg.difficulty = float(difficulty)
cfg.seed = self.cfg.seed
# Clear non-serializable fields for hashing
for attr in _HEIGHT_FIELD_ATTRS:
if hasattr(cfg, attr):
setattr(cfg, attr, None)
# Clear RNG for hashing (seed already included, RNG is derived from it)
if hasattr(cfg, 'rng'):
cfg.rng = None
# Generate hash and cache paths
sub_terrain_hash = dict_to_md5_hash(cfg.to_dict())
sub_terrain_cache_dir = os.path.join(self.cfg.cache_dir, sub_terrain_hash)
sub_terrain_obj_filename = os.path.join(sub_terrain_cache_dir, "mesh.obj")
sub_terrain_csv_filename = os.path.join(sub_terrain_cache_dir, "origin.csv")
sub_terrain_meta_filename = os.path.join(sub_terrain_cache_dir, "cfg.yaml")
# Check cache
if self.cfg.use_cache and os.path.exists(sub_terrain_obj_filename):
mesh = trimesh.load_mesh(sub_terrain_obj_filename, process=False)
origin = np.loadtxt(sub_terrain_csv_filename, delimiter=",")
return mesh, origin
# Set RNG for terrain generation (after hashing, before generation)
# Only pass RNG if seed was explicitly set (for reproducibility)
# Otherwise cfg.rng stays None and terrain uses fresh random each time
if hasattr(cfg, 'rng') and self._reproducible:
cfg.rng = self.np_rng.spawn(1)[0]
# Generate mesh
meshes, origin = cfg.function(difficulty, cfg)
if not isinstance(meshes, list):
meshes = [meshes]
mesh = trimesh.util.concatenate(meshes)
# Center the mesh
transform = np.eye(4)
transform[0:2, -1] = -cfg.size[0] * 0.5, -cfg.size[1] * 0.5
mesh.apply_transform(transform)
origin += transform[0:3, -1]
# PATCH: Collect height field data from cfg (set by terrain generation function)
for attr in _HEIGHT_FIELD_ATTRS:
if hasattr(cfg, attr):
data = getattr(cfg, attr)
if data is not None:
self._height_field_lists[attr].append(data)
setattr(cfg, attr, None) # Clear after collecting
# Cache if enabled
if self.cfg.use_cache:
os.makedirs(sub_terrain_cache_dir, exist_ok=True)
mesh.export(sub_terrain_obj_filename)
np.savetxt(sub_terrain_csv_filename, origin, delimiter=",", header="x,y,z")
dump_yaml(sub_terrain_meta_filename, cfg)
return mesh, origin
# Apply patches
TerrainGenerator.__init__ = _patched_init
TerrainGenerator._get_terrain_mesh = _patched_get_terrain_mesh
def _patch_terrain_importer():
"""Patch TerrainImporter to store height field data as attributes.
After TerrainGenerator populates shared storage, we capture the data
and store it as attributes on TerrainImporter for access via env.scene.terrain.
"""
from isaaclab.terrains.terrain_importer import TerrainImporter
_original_importer_init = TerrainImporter.__init__
# Attribute names (with underscore prefix for storage on importer)
_HEIGHT_FIELD_ATTRS = [
"height_field_visual",
"height_field_valid_mask",
"height_field_platform_mask",
"height_field_spawn_mask",
]
def _patched_importer_init(self, cfg):
"""Patched __init__ that captures height field data from TerrainGenerator."""
# Clear previous storage
for attr in _HEIGHT_FIELD_ATTRS:
_height_field_storage[attr] = None
# Call original __init__ - creates TerrainGenerator which populates storage
_original_importer_init(self, cfg)
# Capture height field data from storage and store as attributes
for attr in _HEIGHT_FIELD_ATTRS:
setattr(self, f"_{attr}", _height_field_storage.get(attr))
TerrainImporter.__init__ = _patched_importer_init
def _patch_pinhole_camera_pattern_cfg():
"""Patch PinholeCameraPatternCfg to add from_ros_camera_info method."""
from isaaclab.sensors.ray_caster.patterns.patterns_cfg import PinholeCameraPatternCfg
# Check if already patched
if hasattr(PinholeCameraPatternCfg, 'from_ros_camera_info'):
return
# Add downsample_factor attribute if not present
if not hasattr(PinholeCameraPatternCfg, 'downsample_factor'):
PinholeCameraPatternCfg.downsample_factor = 1
# Store original from_intrinsic_matrix
_original_from_intrinsic_matrix = PinholeCameraPatternCfg.from_intrinsic_matrix
@classmethod
def _patched_from_intrinsic_matrix(
cls,
intrinsic_matrix: list[float],
width: int,
height: int,
focal_length: float = 1.0,
downsample_factor: int = 1,
) -> PinholeCameraPatternCfg:
"""Create a PinholeCameraPatternCfg from an intrinsic matrix with downsampling support.
Args:
intrinsic_matrix: The intrinsic matrix as a 9-element list [f_x, 0, c_x, 0, f_y, c_y, 0, 0, 1].
width: Width of the image (in pixels).
height: Height of the image (in pixels).
focal_length: Focal length of the camera (in cm). Defaults to 1.0 cm.
downsample_factor: Downsampling factor for RL training. Defaults to 1 (no downsampling).
Returns:
An instance of the PinholeCameraPatternCfg class.
"""
# Extract standard intrinsic parameters (in pixels)
f_x = intrinsic_matrix[0]
c_x = intrinsic_matrix[2]
f_y = intrinsic_matrix[4]
c_y = intrinsic_matrix[5]
# Apply downsampling adjustments
if downsample_factor > 1:
f_x = f_x / downsample_factor
f_y = f_y / downsample_factor
c_x = c_x / downsample_factor
c_y = c_y / downsample_factor
width = width // downsample_factor
height = height // downsample_factor
# Convert to USD camera parameters
horizontal_aperture = width * focal_length / f_x
vertical_aperture = height * focal_length / f_y
# Convert principal point offset from pixels to physical units (cm)
horizontal_aperture_offset = (c_x - width / 2) * horizontal_aperture / width
vertical_aperture_offset = (c_y - height / 2) * vertical_aperture / height
return cls(
focal_length=focal_length,
horizontal_aperture=horizontal_aperture,
vertical_aperture=vertical_aperture,
horizontal_aperture_offset=horizontal_aperture_offset,
vertical_aperture_offset=vertical_aperture_offset,
width=width,
height=height,
)
@classmethod
def from_ros_camera_info(
cls,
fx: float,
fy: float,
cx: float,
cy: float,
width: int,
height: int,
focal_length: float = 1.0,
downsample_factor: int = 1,
) -> PinholeCameraPatternCfg:
"""Create a PinholeCameraPatternCfg from ROS CameraInfo parameters.
This is a convenience method for creating camera configurations directly from
ROS camera_info topic parameters, avoiding the need to construct the full
intrinsic matrix.
Args:
fx: Focal length in x-direction (pixels).
fy: Focal length in y-direction (pixels).
cx: Principal point x-coordinate (pixels).
cy: Principal point y-coordinate (pixels).
width: Image width (pixels).
height: Image height (pixels).
focal_length: USD focal length scaling factor (cm). Defaults to 1.0 cm.
downsample_factor: Downsampling factor for RL training. Defaults to 1 (no downsampling).
Returns:
A PinholeCameraPatternCfg instance.
Example:
# From your camera info topic:
# K: [419.663, 0, 425.728, 0, 419.663, 238.272, 0, 0, 1]
# size: 848 x 480
# Original resolution
cfg = PinholeCameraPatternCfg.from_ros_camera_info(
fx=419.663, fy=419.663, cx=425.728, cy=238.272,
width=848, height=480
)
# 4x downsampled for RL training (212x120)
cfg_rl = PinholeCameraPatternCfg.from_ros_camera_info(
fx=419.663, fy=419.663, cx=425.728, cy=238.272,
width=848, height=480, downsample_factor=4
)
"""
# Create intrinsic matrix in row-major format
intrinsic_matrix = [fx, 0, cx, 0, fy, cy, 0, 0, 1]
return cls.from_intrinsic_matrix(intrinsic_matrix, width, height, focal_length, downsample_factor)
# Apply patches
PinholeCameraPatternCfg.from_intrinsic_matrix = _patched_from_intrinsic_matrix
PinholeCameraPatternCfg.from_ros_camera_info = from_ros_camera_info
@@ -0,0 +1,341 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Constants for terrain generation and goal sampling.
This module centralizes all height field values and terrain parameters used across
terrain generation and goal sampling code. Using these constants ensures consistency
and makes the height semantics explicit.
Height Field Value Semantics (in discretized units):
====================================================
The height field stores heights as integers where:
actual_height_meters = height_value * VERTICAL_SCALE
Key height values:
- GROUND: 0 (flat walkable ground at z=0)
- PLATFORM: ~200 (flat raised platforms at ~1.0m, valid for goals)
- WALL: ~300 (obstacles/walls at ~1.5m, always excluded from goals)
- PIT: ~-300 (negative obstacles/troughs at ~-1.5m, always excluded)
Goal Sampling Valid Ranges:
- Ground: -10 to 50 (allows small noise/variation)
- Platform: 150 to 250 (captures platform height with margin)
- Excluded: < -10 (pits) or > 250 (walls)
"""
from dataclasses import dataclass
from typing import Tuple
# =============================================================================
# Scale Factors
# =============================================================================
HORIZONTAL_SCALE: float = 0.1
"""Horizontal resolution of height field in meters per cell."""
VERTICAL_SCALE: float = 0.005
"""Vertical resolution of height field (height_meters = height_value * VERTICAL_SCALE)."""
CELL_SIZE: float = 2.0
"""Size of each maze cell in meters (default: 2m x 2m)."""
CELL_PIXELS: int = int(CELL_SIZE / HORIZONTAL_SCALE)
"""Number of height field pixels per maze cell (20 at default scale)."""
# =============================================================================
# Height Values (in discretized units, multiply by VERTICAL_SCALE for meters)
# =============================================================================
@dataclass(frozen=True)
class HeightValues:
"""Standard height values for terrain features."""
# Ground level (valid for goals/spawn)
GROUND: int = 0
# Platform height: wall_height - 0.5m in vertical scale units
# = 1.5/0.005 - 0.5/0.005 = 300 - 100 = 200
PLATFORM: int = 200
# Wall/obstacle height: 1.5m in vertical scale units
# = 1.5/0.005 = 300
WALL: int = 300
# Pit/trough height (negative obstacle)
PIT: int = -300
@property
def platform_meters(self) -> float:
"""Platform height in meters."""
return self.PLATFORM * VERTICAL_SCALE
@property
def wall_meters(self) -> float:
"""Wall height in meters."""
return self.WALL * VERTICAL_SCALE
HEIGHTS = HeightValues()
"""Singleton instance of standard height values."""
# =============================================================================
# Goal Sampling Thresholds
# =============================================================================
@dataclass(frozen=True)
class SamplingThresholds:
"""Thresholds for classifying height values during goal/spawn sampling.
These values match the old implementation for strict height classification.
"""
# Ground range (strict: 0-10, allows minimal noise)
GROUND_MIN: int = 0
GROUND_MAX: int = 10
# Platform range (strict: 195-205 for stair platforms at ~1.0m)
PLATFORM_MIN: int = 195
PLATFORM_MAX: int = 205
# Wall threshold (anything above 10 is obstacle, but also check platform edges)
WALL_THRESHOLD: int = 10
# Pit threshold (anything below 0 is pit/excluded)
PIT_THRESHOLD: int = 0
# Edge detection threshold for Sobel filter (old: any edge > 0.0)
EDGE_THRESHOLD: float = 0.0
# Obstacle marker value (used to mark excluded cells)
OBSTACLE_MARKER: int = 110
# Extended platform range for edge detection (180-220)
# Used during padding to detect platform edges with safety margin
PLATFORM_EDGE_MIN: int = 180
PLATFORM_EDGE_MAX: int = 220
THRESHOLDS = SamplingThresholds()
"""Singleton instance of sampling thresholds."""
# =============================================================================
# Padding and Border Configuration
# =============================================================================
@dataclass(frozen=True)
class PaddingConfig:
"""Configuration for obstacle padding and borders.
These values match the old implementation for consistent safety margins.
With horizontal_scale=0.1m/cell, these translate to:
- GOAL_PADDING (3 cells) = 0.3m around obstacles for goal positions
- SPAWN_PADDING (8 cells) = 0.8m around obstacles for spawn positions
The larger spawn padding accounts for:
- Robot body dimensions (~0.5m x 0.3m for quadrupeds)
- Random yaw orientation (diagonal ~0.58m requires ~0.3m radius)
- Platform edge clearance (prevent falling when spawning near stair edges)
- Controller startup imprecision
"""
# Padding around obstacles for goals (in height field cells)
# 5 cells * 0.1m/cell = 0.5m padding (robot just needs to reach)
GOAL_PADDING: int = 5
# Larger padding for spawn positions (in height field cells)
# 6 cells * 0.1m/cell = 0.6m padding
# This accounts for:
# - Robot body radius (~0.5m) with worst-case orientation
# - Additional safety margin for platform edges
# - Controller startup behavior
SPAWN_PADDING: int = 6
# Border exclusion (keep away from terrain edges)
# Old implementation used 2 layers (inner + outer), we use 2 cells
BORDER_CELLS: int = 2
# Pillar expanded footprint size (5x5 cells around pillar center)
PILLAR_FOOTPRINT: int = 5
# Pillar safe margin from cell edges
PILLAR_EDGE_MARGIN: int = 2
# Height transition detection threshold (height field units)
# Marks cells with height differences >= this value as transitions
HEIGHT_TRANSITION_THRESHOLD: int = 100
# Padding around detected height transitions (in cells)
HEIGHT_TRANSITION_PADDING: int = 1
PADDING = PaddingConfig()
"""Singleton instance of padding configuration."""
# =============================================================================
# Stair Configuration
# =============================================================================
@dataclass(frozen=True)
class StairConfig:
"""Configuration for stair generation."""
# Number of steps in a staircase
NUM_STEPS: int = 5
# Height of each step in meters
STEP_HEIGHT_METERS: float = 0.2
# Grid size for 3x3 stair structures
STAIR_GRID_SIZE: int = 3
# Single cell size in pixels (same as CELL_PIXELS)
SINGLE_CELL_PIXELS: int = 20
@property
def step_height_units(self) -> float:
"""Step height in discretized units."""
return self.STEP_HEIGHT_METERS / VERTICAL_SCALE
@property
def step_resolution(self) -> int:
"""Pixels per step (cell_pixels / num_steps)."""
return self.SINGLE_CELL_PIXELS // self.NUM_STEPS
STAIRS = StairConfig()
"""Singleton instance of stair configuration."""
# =============================================================================
# Obstacle Structure Types
# =============================================================================
class ObstacleType:
"""Enumeration of obstacle structure types for random generation."""
PILLAR = 0
BAR = 1
CROSS = 2
SHIFTED_BLOCK = 3
# Total number of obstacle types
NUM_TYPES = 4
# =============================================================================
# Obstacle Generation Parameters
# =============================================================================
@dataclass(frozen=True)
class ObstacleConfig:
"""Configuration for random obstacle generation.
Controls the randomness parameters for obstacle shapes, sizes, and pit ratios.
All probabilities are in [0, 1] range.
"""
# Height scale range (multiplier for wall_height)
SCALE_MIN: float = 0.5
SCALE_MAX: float = 1.5
# Thickness range (margin cells from obstacle center)
# Higher thickness = thinner pillar, thicker bar
# Range 7-9: pillars 2-6 pixels (0.2-0.6m), bars 7-9 pixels (0.7-0.9m)
THICKNESS_MIN: int = 7
THICKNESS_MAX: int = 10 # exclusive upper bound
# Default pit probability when not specified
DEFAULT_PIT_PROB: float = 0.15
# Pit environment specific settings
PITS_BAR_RATIO: float = 0.6 # Ratio of bars vs random obstacles in pit terrain
PITS_BAR_PIT_PROB: float = 0.75 # Pit probability for bar obstacles
PITS_RANDOM_PIT_PROB: float = 0.5 # Pit probability for random obstacles
# Bridge configuration for pit terrain
BRIDGE_COUNT_MIN: int = 3
BRIDGE_COUNT_MAX: int = 6 # exclusive upper bound
# Pit terrain layout (cell indices from grid edge)
PITS_TRENCH_ROW_OFFSET: int = 2 # Pit trenches at rows [offset, grid_h - offset - 1]
PITS_EDGE_MARGIN: int = 2 # Margin from grid edges for middle obstacles
# Obstacle density multipliers (applied to difficulty)
NON_MAZE_DENSITY: float = 0.5 # For non-maze terrain (increased from 0.35)
PITS_DENSITY: float = 0.6 # For pit terrain middle area
STAIRS_OBSTACLE_DENSITY: float = 0.35 # For random obstacles in stair terrain
STAIRS_PLACEMENT_PROB: float = 0.75 # Probability of placing stairs at valid locations
# Non-maze terrain pillar weight (higher = more pillars)
# Default uniform is 0.25 (1/4 types), 0.5 means ~50% pillars
NON_MAZE_PILLAR_WEIGHT: float = 0.5
OBSTACLES = ObstacleConfig()
"""Singleton instance of obstacle configuration."""
# =============================================================================
# Helper Functions
# =============================================================================
def height_to_meters(height_value: int) -> float:
"""Convert discretized height value to meters."""
return height_value * VERTICAL_SCALE
def meters_to_height(meters: float) -> int:
"""Convert meters to discretized height value."""
return int(meters / VERTICAL_SCALE)
def is_valid_ground(height: int) -> bool:
"""Check if height value represents valid ground."""
return THRESHOLDS.GROUND_MIN <= height <= THRESHOLDS.GROUND_MAX
def is_valid_platform(height: int) -> bool:
"""Check if height value represents valid platform."""
return THRESHOLDS.PLATFORM_MIN <= height <= THRESHOLDS.PLATFORM_MAX
def is_valid_goal_position(height: int) -> bool:
"""Check if height value is valid for goal/spawn placement."""
return is_valid_ground(height) or is_valid_platform(height)
def is_obstacle(height: int) -> bool:
"""Check if height value represents an obstacle (wall or pit)."""
return height > THRESHOLDS.WALL_THRESHOLD or height < THRESHOLDS.PIT_THRESHOLD
def is_pit(height: int) -> bool:
"""Check if height value represents a pit."""
return height < THRESHOLDS.PIT_THRESHOLD
def is_wall(height: int) -> bool:
"""Check if height value represents a wall."""
return height > THRESHOLDS.WALL_THRESHOLD
def cell_to_pixels(cell_idx: int) -> Tuple[int, int]:
"""Convert cell index to pixel range.
Args:
cell_idx: Cell index in maze grid.
Returns:
Tuple of (start_pixel, end_pixel).
"""
start = cell_idx * CELL_PIXELS
end = (cell_idx + 1) * CELL_PIXELS
return start, end