December 1, 2026
Teaching Drones to Dodge: A GPU Obstacle-Course Simulator for Model-Based RL
30 min read
A drone has 18 metres to cross. Between it and a glowing green goal stand pillars, slabs, boulders and tilted beams. Some of them spin like turnstiles, and some drift and tumble through the air. The drone has no map and no camera, only 64 laser rays and a sense of its own motion. It gets 15 seconds and one attempt. One graze and the episode is over.
That is the task this project throws at three model-based reinforcement learning agents: MBPO, DreamerV3 and TD-MPC2. Model-based RL promises to learn from far less data by building a model of the world and practising inside it. Benchmarks like Pendulum or Walker barely test that promise. A cluttered 3D world that changes while the agent is still flying through it tests it properly.
No off-the-shelf simulator fit. It had to run thousands of drones at once on a single GPU, and it had to let the learning algorithm query the obstacle geometry exactly. So the whole environment was written from scratch in PyTorch: the physics, the geometry, the obstacle forests and the 3D replays. This post walks through how it works, the design decisions behind it and the bugs that shaped it, and then shows trained agents flying through it.

Goals
The requirements were:
- Thousands of parallel environments on one GPU. MBPO, DreamerV3 and TD-MPC2 all need a lot of data, and full sweeps (3 algorithms × 3 experiments × several seeds) had to finish in hours rather than days.
- Geometry the algorithm can query exactly. The MBPO variant used here is hybrid: its learned model predicts only the drone’s physics, and everything that depends on obstacles is computed exactly from the map. For that, the code that computes observations, rewards and terminations has to be shared and batched.
- Procedural maps with a guarantee that a path exists, to test generalization to new maps, new shapes and higher densities.
- Obstacles that move, so the agent can’t just memorize a static layout.
- A 3D view of every flight, because success rates on their own hide a lot.
Architecture at a glance
Each step, the agent sends a batch of actions into VecQuadEnv. quadrotor.py integrates the physics. task.py then asks geometry.py how far the drone is from every surface, using obstacle poses that the MapBank evaluates for the current time step. The resulting observation goes back to the agent, and the full transition goes into the replay buffer. Drones that crash or arrive respawn straight away on a fresh map. MBPO’s imagined rollouts call the very same geometry and task code, which is what keeps imagination honest about obstacles.
The whole stack is plain PyTorch:
| Module | Responsibility |
|---|---|
envs/geometry.py | Signed distance functions and exact ray intersection for 5 shape types |
envs/forest.py | Procedural map generator with a feasibility check, plus a GPU MapBank |
envs/motion.py | Closed-form obstacle motion (spin, drift, tumble) |
envs/quadrotor.py | Batched rigid-body dynamics with an inner body-rate controller |
envs/task.py | Observation, reward and termination as pure batched functions |
envs/quad_env.py | VecQuadEnv: auto-resetting vectorized environment |
viz/ | MuJoCo scene builder and replay/video renderer |
Contact physics is left out on purpose: any collision ends the episode, so there is never anything to simulate after one, and no need for MuJoCo physics or Isaac. MuJoCo is used only to draw the flights.
The code snippets in this post are lightly trimmed from the source to show the core idea of each piece. From the outside, the environment behaves like any vectorized environment. Generate a bank of maps, wrap it in VecQuadEnv, and step thousands of drones with one call:
from envs.forest import ForestConfig, MapBank
from envs.quad_env import VecQuadEnv
cfg = ForestConfig(shape_mix={"cylinder": 0.4, "box": 0.3, "sphere": 0.15, "capsule": 0.15})
maps = MapBank.generate(cfg, num_maps=2000, seed=0, device="cuda")
env = VecQuadEnv(maps, num_envs=4096, episode_schedule=True)
obs = env.reset() # [4096, 80]
out = env.step(policy(obs)) # actions: [4096, 4] in [-1, 1]
out["reward"], out["terminated"], out["info"]["collision"]
The quadrotor
The drone is a 1 kg quadrotor with a diagonal inertia of (0.008, 0.008, 0.014) kg·m², a thrust-to-weight ratio of 2.5 and linear drag.
Action space. The policy outputs 4 numbers in [-1, 1]:
a[0]: collective thrust, mapped to[0, T_max]a[1:4]: desired body rates, up to 6 rad/s for roll and pitch and 3 rad/s for yaw
An inner P-controller turns the desired rates into clamped body torques. Thrust plus body rates is the usual action space for drone RL. It is much easier for SAC-style learners than raw motor commands or torques, and it still allows aggressive flight.
Integration. The control period is 50 ms (20 Hz), with 5 semi-implicit Euler substeps per control step. At 20 Hz, an 18 m crossing takes about 100 to 150 decisions, which is a manageable horizon for RL.
Each substep is a handful of tensor operations over all N drones at once: thrust along the body z-axis, gravity and drag for the translation, then the rate controller and a quaternion update for the rotation.
def _substep(self, x, thrust, rates_des, dt):
pos, vel, q, w = x[..., 0:3], x[..., 3:6], x[..., 6:10], x[..., 10:13]
rot = quat_to_rot(q)
# Translation: thrust along body z, gravity, linear drag (semi-implicit Euler).
acc = rot[..., :, 2] * (thrust / self.p.mass)[..., None] + self.g - self.p.drag / self.p.mass * vel
vel = vel + acc * dt
pos = pos + vel * dt
# Rotation: P-controller on body rates, clamped torques, gyroscopic term.
gyro = torch.cross(w, self.J * w, dim=-1)
torque = self.J * self.rate_kp * (rates_des - w) + gyro
torque = torch.maximum(torch.minimum(torque, self.max_torque), -self.max_torque)
w = w + (torque - gyro) / self.J * dt
q = quat_mul(q, quat_from_rotvec(w * dt)) # integrate orientation
return torch.cat([pos, vel, q / q.norm(dim=-1, keepdim=True), w], dim=-1)
State representation. Internally the simulator keeps a quaternion. The learned models see a 15-D state instead:
s = [ position(3), velocity(3), rot6d(6), body_rates(3) ]
rot6d is the first two columns of the rotation matrix (Zhou et al., 2019). It is continuous, so a dynamics model can predict Δstate without angle wrap-around or gimbal lock. After every model step, the prediction is projected back onto SO(3) with Gram–Schmidt.
The dynamics have unit tests. At hover thrust, altitude holds within 1 cm over 5 s. Free fall matches g. The rate step response settles. The quaternion stays unit-norm.
Geometry: five shapes, exact rays
Each map is a padded tensor of obstacles. Each row holds:
[type, center(3), half_extents(3), R(9), active, bound_radius]
There are five shape types: cylinders, boxes, spheres, ellipsoids and capsules. Every shape uses its local z-axis as its main axis, which matches MuJoCo’s geom conventions, so the renderer can write the same parameters straight into MJCF.
Two queries are batched over all drones and all obstacles:
sdf(points, obstacles): the signed distance to the nearest surface, including the floor and ceiling. It is used for clearance, collision and the proximity penalty.raycast(origins, dirs, obstacles): exact analytic ray–shape intersection, using slabs for boxes and quadratics for the round shapes, in a single pass. Sphere tracing was the first attempt, and it was about 20× slower.
Branching on shape type would break batching, so both queries use the same trick. Every point or ray is moved into each obstacle’s local frame, the formula for all five shapes is evaluated, and gather picks the one that matches each obstacle’s type:
def obstacle_sdf(points, obstacles): # [B, P, 3], [B, O, 18] -> [B, P, O]
rel = points[:, :, None, :] - center[:, None, :, :]
local = torch.einsum("bpoi,boij->bpoj", rel, rot) # world -> local frame (R^T p)
all_sdf = _shape_sdfs(local, half) # [B, P, O, 5]: one SDF per shape type
d = all_sdf.gather(-1, shape_type[:, None, :, None].expand(*all_sdf.shape[:-1], 1)).squeeze(-1)
return torch.where(active[:, None, :], d, FAR) # padded slots are infinitely far away
Ray intersections follow the same pattern. A box is the overlap of three slab intervals, a sphere or an ellipsoid is a quadratic, and a capsule is an infinite cylinder capped by two spheres:
x0, x1 = _slab(ox, dx, -hx, hx)
y0, y1 = _slab(oy, dy, -hy, hy)
z0, z1 = _slab(oz, dz, -hz, hz)
box = _first_hit(torch.maximum(torch.maximum(x0, y0), z0), torch.minimum(torch.minimum(x1, y1), z1))
cap = torch.minimum(cyl, torch.minimum(sphere_at(hz), sphere_at(-hz)))
The drone senses its surroundings with 64 rays on a Fibonacci sphere, clipped at 5 m. Each drone only tests its 24 nearest obstacles, which keeps the cost flat as maps get denser.

The geometry is checked against independent references. The SDF matches brute-force surface sampling. Raycasts match analytic ray–sphere and ray–box hits. The distance MuJoCo reports agrees with the torch SDF to within 1 cm, so the crash frame in a video is the same frame the environment flagged.
Procedural forests
ForestGenerator builds a map in four steps:
- Place obstacles. Footprints are placed by Poisson-disk sampling in XY over a 20 m × 10 m × 4 m arena, with a minimum free gap of 0.6 m between footprints.
- Keep the endpoints clear. The start (x = 1 m) and the goal (x = 19 m) are kept free within a 1.2 m radius. Their y and z coordinates are random.
- Sample each shape. Shapes are drawn from a configurable
shape_mix, and each shape has its own size ranges. Ellipsoids get a random tilt, and capsules can lie at any angle. - Check that a path exists. A coarse voxel flood fill (0.2 m voxels, inflated by the drone’s radius) checks that the goal can be reached. Maps with no path are resampled.
Placement is rejection sampling. The shape is picked first and its position retried up to 40 times, so big shapes that are harder to fit don’t end up under-represented in the mix:
shape = int(rng.choice(self.shape_ids, p=self.shape_probs))
for _ in range(40):
xy = np.array([rng.uniform(x_lo, x_hi), rng.uniform(y_lo, y_hi)])
row = self._sample_obstacle(rng, shape, xy)
ext = geo.horizontal_extent(row)
if np.linalg.norm(xy - start[:2]) - ext < c.clear_radius:
continue # too close to the start (same check for the goal)
if centers and (np.linalg.norm(np.asarray(centers) - xy, axis=1) - np.asarray(extents) - ext).min() < c.min_gap:
continue # too close to a neighbour
rows.append(row); centers.append(xy); extents.append(ext)
break
The flood fill reuses the SDF and a neat GPU trick. Mark the free voxels, seed the start voxel, and grow the reachable region with a 3×3×3 max-pool until it touches the goal or stops growing:
free = (sdf(voxel_centres, obstacles, z_range) > drone_radius).reshape(1, 1, nx, ny, nz).float()
reach = torch.zeros_like(free)
reach[0, 0][start_idx] = 1.0
while True:
reach = F.max_pool3d(reach, 3, stride=1, padding=1) * free # one step of 26-connected growth
if reach[0, 0][goal_idx] > 0:
return True # goal is reachable
if reach.sum() == previous_count:
return False # no progress: no path exists
previous_count = reach.sum()
All maps are stacked on the GPU in a MapBank with shape [M, O_max, …]. Replay buffers store a map_id per transition instead of a copy of the geometry. Observations and rewards are then recomputed from the bank whenever they are needed, for both real and imagined transitions.
The first sanity check was an obstacle-blind PD controller that flies straight at the goal. It mostly hits things, which is the point: it shows the forests actually block the straight line.
Making obstacles move
Static maps can be memorized, so envs/motion.py adds analytic motion. Every obstacle’s pose is a closed-form function of time:
centre(t) = c0 + Σ_k amp_k · sin(2π · freq_k · t + phase_k) (z clamped to the arena)
rotation(t) = Rot(axis, ω·t) · R0
There are three modes:
static: no motion.spin: each obstacle rotates about the vertical axis through its centre. Thin “wall” boxes and tilted capsules sweep through space, with tip speeds near 1.8 m/s.move: each obstacle drifts around its anchor along two sinusoids per axis (including vertically) and tumbles about a random axis. Translation speed is capped. Full-height obstacles only move horizontally, so they never pass through the floor or ceiling.
Because motion is deterministic given the map seed, MapBank.obstacles_at(map_id, t) can pose any map at any episode step on the GPU. In code, the formula above is two lines over a whole batch of maps:
def pose_at(obstacles, motion, seconds, z_range):
ts = seconds[:, None, None, None]
disp = (motion["amp"] * torch.sin(2 * math.pi * motion["freq"] * ts + motion["phase"])).sum(-2)
center = obstacles[..., I_CENTER] + disp # z is then clamped to the arena
rot = axis_angle_matrix(motion["axis"], motion["omega"] * seconds[:, None]) @ base_rotation
# ... reassemble the obstacle rows with the new centre and rotation
Every geometry query takes the step t as an argument. This matters for MBPO: its imagined rollouts can query the exact future obstacle poses. That is privileged information, so a flag (--rollout-motion frozen) turns it off for ablations.
Range-rate observation. A memoryless policy can’t tell from one set of ray distances whether an obstacle is approaching. The dynamic experiments add a second 64-channel signal. It casts the rays again from the same position against the obstacles’ poses at t − 1, and takes the difference. Since the drone hasn’t moved between the two casts, the difference comes only from obstacle motion. The observation grows to 144-D.
Observation, reward and termination
Observation. All three parts are computed, never predicted:
- Proprioception (16-D): unit direction to the goal, distance to the goal, velocity, rot6d and body rates.
- Rays (64-D):
1 − d / 5 m, so 0 means free space and 1 means touching. - Range rates (64-D): dynamic experiments only.
Reward.
r = 5.0 · (progress toward goal)
− 0.5 · exp(−clearance / 0.3) # stay away from surfaces
− 0.01 · ‖body-rate command‖² # smooth control
− 0.5 · max(0, speed − 4 m/s)² # soft speed limit
+ 30 · success
− 20 · crash
Termination. An episode ends on a collision (the drone’s 0.2 m sphere touches a surface), leaving the arena, flipping upside down, reaching the 1 m goal sphere, or hitting the 300-step time limit. Time-limit truncations are never stored as terminals.
One bug took a while to track down. At 8 m/s, the drone moves 0.4 m per step. When only the endpoints of each step were tested, the policy learned to skip through the goal sphere and to clip obstacle corners between frames. Collision is now checked at the midpoint and the end of each step, with the obstacles posed at the matching times. Goal success uses the closest point on the step segment:
mid = 0.5 * (pos + next_pos)
clear_both = self.clearance(torch.cat([mid, next_pos]), torch.cat([map_id, map_id]), torch.cat([t + 0.5, t + 1]))
collision = torch.minimum(*clear_both.chunk(2)) < 0.0
seg = next_pos - pos # closest approach to the goal along the step
u = (((goal - pos) * seg).sum(-1) / (seg * seg).sum(-1).clamp(min=1e-9)).clamp(0.0, 1.0)
success = (torch.linalg.vector_norm(goal - (pos + u[:, None] * seg), dim=-1) < goal_radius) & ~crash
All of this lives in task.py as pure functions of (state, action, next_state, goal, map_id, t). The real environment and MBPO’s imagined rollouts call the same code. A parity test checks that they agree exactly.
Fair comparisons
Comparing several algorithms in procedurally generated environments raises fairness problems, so fairness is built into the environment itself:
-
Same maps. Run i of every algorithm uses the same training maps and the same evaluation maps.
-
Same episode sequence. With
episode_schedule=True, the map and start noise for env slot i’s j-th episode come from a counter-based hash of(seed, i, j). Every algorithm with the same seed sees exactly the same sequence of maps and starts in every slot, whatever its policy does.keys = (torch.full_like(idx, self.seed), idx, self.episode_count[idx]) # (seed, slot, episode) u = torch.stack([hash_uniform(*keys, torch.full_like(idx, j)) for j in range(5)], -1) maps = (u[:, 0] * len(self.maps)).long() # which map start = self.maps.starts[maps] + (u[:, 1:4] * 2 - 1) * self.start_pos_noise -
Matched difficulty. Density is tuned so that the obstacle-blind straight-line controller succeeds 6% of the time in the static experiment, 16% with rotating obstacles and 12% with moving obstacles.
The three experiments
| Experiment | Shapes | Motion | Out-of-distribution eval |
|---|---|---|---|
| (a) static | cylinder, box, sphere, capsule | none | dense: density 0.12 → 0.18 obstacles/m² |
| (b) rotating | thin wall boxes, capsules, ellipsoids | spin, 0.3–1.0 rad/s | fast_spin: 1.0–1.8 rad/s |
| (c) moving | all five shapes | drift + tumble, ≤ 1 m/s | fast: ≤ 1.8 m/s, higher frequencies |


Watching the agents fly
Every evaluation episode is saved as an .npz file with the states, actions, goal, obstacle parameters and motion. viz/replay.py rebuilds the scene in MuJoCo, poses moving obstacles frame by frame, and renders a chase camera next to an overview. With MUJOCO_GL=egl it renders headless on vast.ai instances.
The overlays show:
- the flown path, coloured by clearance
- the optional lidar rays
- MBPO’s ensemble prediction fans, when they are logged
The first learned controller was MBPO in open space, with no obstacles.
The clips below are the best successful episode from each agent’s final evaluation, chosen automatically by scripts/record_best.py. They show what each agent can do, not how it usually performs.
(a) Static forest
(b) Rotating obstacles
(c) Moving obstacles
Wrapping up
Go back to the drone at the start of this post: 18 metres of pillars, spinning walls and tumbling boulders, 64 laser rays, and one attempt. Every piece of this environment exists to make that moment fair, fast and honest.
Fair, because every agent faces the same maps, the same starts and the same sequence of episodes, and the difficulty is pinned to a simple straight-line baseline. Fast, because the physics, the geometry and the obstacle motion all run as batched PyTorch on one GPU, so thousands of drones fly at once. Honest, because the reward and the crash checks are computed exactly from the obstacle geometry, along the whole path of each step, by the same code for real flights and imagined ones.
The design comes down to one idea: compute what can be computed, and learn only what has to be learned. The physics of a drone is smooth and worth learning. The distance to a spinning wall is not. Keeping that line sharp is what lets a model-based agent practise in its own imagination without fooling itself about where the obstacles are.
The result is more than a single benchmark. It is a configurable testbed, with shape mixes, densities and motion modes that can each be adjusted, held out or pushed past what any agent saw in training. Watch the videos again with that in mind. Each clean pass between two moving obstacles is a policy that learned to turn a sphere of laser distances into a flight path through a world that keeps changing.