This project is a 2D overhead demo of MPPI (Model Predictive Path Integral) control. MPPI is a controller that plans by sampling. It does not use gradients or a solver.
A drone flies through a field of pillars to a goal. Each control step, the controller imagines many possible futures. It scores each future, weights it, and averages the futures into one plan.
The user controls the temperature λ (lambda). λ sets how strongly the best futures win the average. The demo shows how a high λ makes the drone fly into a pillar.
The application is vanilla JavaScript. It runs from the local disk in a browser, with no server. An optional backend runs the rollouts in WebAssembly.
Live demo: mraad.github.io/drone-mppi. Source code: github.com/mraad/drone-mppi.
Each step below matches a numbered comment in mppiStep() in mppi.js.
The drone is a point mass. The state is position and velocity: (x, y, vx, vy), in metres and m/s. The control is acceleration (ax, ay), in m/s². The controller clamps each acceleration to ±10 m/s².
The model uses semi-implicit Euler integration with a time step dt of 0.05 s:
v ← v + a · dt
p ← p + v · dt
U holds 30 accelerations. 30 steps of 0.05 s give a horizon of 1.5 s. The plan starts at zero.Vk = clamp(U + εk) through the model. This gives K futures.wk = exp(-(ck - cmin) / λ). Then it normalizes the weights so that they sum to 1.U ← Σ wk Vk. This is equal to the old plan plus the weighted average of the noise.Steps 3 and 4 are independent for each sample. Thus the work can run in parallel.
| Term | Value per step | Effect |
|---|---|---|
| Distance to goal | Euclidean distance, m | Pulls the drone toward the goal. Typical values: 1 to 15. |
| Pillar contact | 1000 (HIT) | Added for each step where the drone centre is closer than pillar radius + 0.3 m. |
| Off the map | 1000 (HIT) | Added for each step outside the 20 m × 20 m map. |
The collision cost is large but finite. Thus futures that all crash still have an order. A future that crashes later costs less.
The subtraction of cmin cancels during normalization, so it does not change the weights. It keeps the best weight at exactly 1.
Without it, a small λ makes every weight 0. For example, at λ = 0.01 and a best cost of 244, exp(-24 400) is 0 in floating point. The normalization then divides 0 by 0, and the plan becomes NaN. A test examines this case (see Tests).
The noise is smooth in time. It is an AR(1) process (a first-order auto-regressive filter):
εt = 0.9 · εt-1 + sqrt(1 - 0.9²) · σ · n, n ~ N(0, 1)
The standard deviation stays σ. With white noise (independent values per step), the random pushes in one future mostly cancel. In the 12 m/s test case, no white-noise future of 1000 missed the pillar. With smooth noise, about 10% of the futures miss it, split evenly between left and right.
The effective sample size (ESS) is 1 / Σ wk². It shows how many futures have a real vote. ESS ≈ 1 means that the best future wins. ESS ≈ K means that all futures have an equal vote.
The project has three runtime files. index.html loads two classic scripts, then runs the user interface.
| Component | File | Job |
|---|---|---|
| User interface | index.html | Reads the sliders. Runs the control loop at 20 Hz. Draws the canvas and the statistics. |
| MPPI core | mppi.js | Model, cost, noise, weights, plan update, scenarios. It has no DOM code. The page and Node both load it. |
| JS rollout | rolloutJS() in mppi.js | Simulates K futures and writes K costs. |
| WASM rollout | kernel.wat | The same rollout in hand-written WebAssembly text. It mirrors rolloutJS() operation for operation. |
| WASM loader | makeWasmRollout() in mppi.js | Copies trees and controls into WASM memory, calls the kernel, reads the costs back. |
| Build script | build-wasm.js | Assembles kernel.wat into kernel.wasm.js. |
| Tests | test.js | Six Node tests (see Tests). |
file://. Thus the page uses classic <script src> tags. mppi.js sets globalThis.MPPI, and sets module.exports for Node.fetch() of a .wasm file on file://. Thus the build puts the WASM bytes into kernel.wasm.js as a base64 string. The page decodes it with atob().The page runs one control step per 50 ms of real time. Each animation frame adds the elapsed time to an accumulator. The accumulator adds at most 50 ms per frame. Thus a frame runs at most one control step. If a step takes longer than 50 ms, the simulation runs slower than real time.
| Use | Requirement | Version used for this document |
|---|---|---|
| Run the demo | A browser with WebAssembly and canvas support | Google Chrome (headless, for screenshots) |
| Run the tests | Node.js with node:test and global performance | Node v26.14.0 |
| Rebuild the WASM kernel | npm package wabt | 1.0.39 (pinned in package.json) |
The demo needs no server, no network, and no npm packages to run.
To run the demo without a download, open the live demo. To run it from the local disk, do these steps:
drone-mppi.index.html.The page opens in the default browser. The drone starts to fly at once.
npm testThe output shows pass 6 and fail 0.
Do this only after you change kernel.wat. The project includes a built kernel.wasm.js.
npm installnpm run buildkernel.wasm.js: 376 bytes of wasm.npm test. The bit-identical test must pass.Do not edit kernel.wasm.js by hand. The build overwrites it.
| Item on the canvas | Meaning |
|---|---|
| Quadcopter frame | The drone, seen from above. It has a rectangular body, four arms, and four rotor circles. The red nose points in the direction of flight. |
| Short black line from the drone | Velocity. Length = distance flown in 0.3 s. |
| Green discs | Pillars (trees) |
| Green ring | Goal. Radius 0.5 m. |
| Grey lines | Sampled futures. A darker line has a larger weight. |
| Red lines | Sampled futures that hit a pillar or left the map |
| Orange line | The future with the lowest cost |
| Thick blue line | The new plan (the weighted average) |
| Red flash / green flash | Crash / goal reached. Then the drone goes back to the start. |
The page draws the drone at 2 times its collision radius, so that the frame is easy to see. The collision test uses a circle with radius 0.3 m (DRONE_R) at the drone centre. Thus the drawing can touch a pillar before a crash occurs.
| Action | Result |
|---|---|
| Click an empty point | Adds a pillar with radius 0.6 m |
| Click a pillar | Removes the pillar |
| Shift + click | Moves the goal to that point |
| Button | Result |
|---|---|
| Scenario list | Selects "Pillar dead ahead" or "Forest". The drone goes back to the start. |
| Reset | Puts the drone at the start and clears the plan. The pillars you added stay. |
| Pause / Play | Stops or starts the simulation |
| New forest | Makes a new random forest with the next seed |
| Control | Type | Range | Default | Effect |
|---|---|---|---|---|
| λ temperature | Log slider | 0.01 to 107 | 1 | Low: the best futures win. High: all futures have an equal vote. |
| Samples K | Slider, step 100 | 100 to 20 000 | 1000 | Number of futures per step |
| Noise σ | Slider, step 0.5 | 0.5 to 10 m/s² | 5 | Standard deviation of the noise |
| Rollout backend | List | JavaScript, WebAssembly | JavaScript | Selects the rollout code. The result is identical. |
| Futures drawn | Slider, step 10 | 0 to 300 | 120 | Number of sampled futures on the canvas. It does not change the control. |
To change a constant, edit mppi.js and reload the page. If you change W, H, DT, T or HIT, the WASM kernel gets the new value as an argument. No rebuild is necessary.
| Name | Type | Default | Effect |
|---|---|---|---|
W, H | number | 20, 20 m | Map size. Outside the map counts as a crash. |
DT | number | 0.05 s | Model time step and control period |
T | integer | 30 | Steps in the plan. Horizon = T · DT = 1.5 s. |
DRONE_R | number | 0.3 m | Drone radius. Added to each pillar radius for collisions. |
GOAL_R | number | 0.5 m | Distance to the goal that counts as reached. Also the radius of the goal ring. |
A_MAX | number | 10 m/s² | Acceleration limit per axis |
HIT | number | 1000 | Cost per step inside a pillar or off the map |
SMOOTH | number | 0.9 | Noise correlation between steps. 0 gives white noise. |
| Scenario | Start | Goal | Pillars |
|---|---|---|---|
Pillar dead ahead (deadAhead()) | (2, 10) m, velocity 12 m/s toward the goal | (18, 10) m | One pillar at (10, 10) m, radius 1.2 m |
Forest (forest(seed)) | (1.5, 10) m, at rest | (18.5, 10) m | 28 random pillars, radius 0.4 to 1.0 m, at least 0.9 m clearance between them |
In "Pillar dead ahead", the drone cannot brake in time. At 10 m/s², a stop from 12 m/s needs 12² / (2 · 10) = 7.2 m. The pillar edge (with the drone radius) is 6.5 m away. Thus the drone must swerve or crash.
Conditions: K = 1000, σ = 5 m/s², planner seeds 1 to 5, at most 300 steps (15 s). One step is 0.05 s.
| λ | Result | Cause |
|---|---|---|
| 0.01 to 1 | Goal in about 1.5 s, all seeds | A few futures have almost all the weight. The drone selects one side at once. |
| 10 to 30 | Goal in 1.7 to 2.3 s | The average is softer but still selects a side. |
| 100 to 1000 | No crash. No goal in 15 s. | Crashed futures have no weight. The goal term is small relative to λ, so the goal pull averages away. |
| 3000 | Crash in 4 of 5 seeds | λ is larger than a few collision steps. Crashed futures start to get weight. |
| ≥ 10 000 | Crash at about 0.55 s, all seeds | All futures have almost equal weight. The noise averages to about 0, so the plan stays straight. |
At λ = 300, about 50 safe futures pass on each side of the pillar. In one iteration, their average points at the pillar (Figure 3).
The drone did not crash at λ = 100 to 1000 in any seed. The split is never exactly equal. The plan moves a little toward the larger group. The warm start keeps this plan, so the next samples move further to that side. The drone has about 10 iterations before impact, which is enough for this to win.
The crash at high λ has a different cause. Crashed futures get almost the same weight as safe futures. The average is then close to "no control".
Conditions: Node v26.14.0 (V8 engine), Apple arm64, forest seed 1 (28 pillars). Times are milliseconds per iteration.
| K | Rollout, JS (ms) | Rollout, WASM (ms) | Full iteration, JS backend (ms) |
|---|---|---|---|
| 1 000 | 0.81 | 0.42 | 2.4 to 2.6 |
| 5 000 | 4.23 | 1.96 | 14.0 |
| 20 000 | 16.8 | 8.0 | 57 |
The noise generation takes more time than the rollout. It uses log, sqrt, sin and cos (Box-Muller method). The page shows the time for noise, rollout, and weights + average in the statistics box.
The kernel in kernel.wat does the rollout and the cost. JavaScript still makes the noise and does the weights and the average.
All values are 64-bit floats (f64).
| Byte offset | Content | Size |
|---|---|---|
| 0 | Pillars: cx, cy, rr for each pillar, where rr = (r + DRONE_R)² | 24 bytes per pillar |
65 536 (CTRL) | Controls: ax, ay for each step of each sample | K · T · 16 bytes |
CTRL + K · T · 16 | Output costs | K · 8 bytes |
The loader grows the WASM memory when K increases. It makes a new Float64Array view on each call, because a memory grow detaches the old views.
Do not add more than 2730 pillars when you use the WASM backend. The pillar region ends at byte 65 536, and more pillars overwrite the controls.
The kernel uses the same operations in the same order as rolloutJS(): add, subtract, multiply, square root, and compare. IEEE 754 rounds these operations exactly in both engines. Thus the costs are identical, bit for bit. A test compares 2000 random control sequences in a 28-pillar forest.
The WASM rollout is about 2 times faster than the JS rollout. But the rollout is about one third of an iteration. At K = 1000, WASM saves about 0.4 ms of about 2.5 ms. At the default settings, both backends fit in the 50 ms control period.
The project does not use the GPU. The reasons:
mapAsync read-back adds its own delay and makes the control loop asynchronous. This delay is not measured in this project.A GPU path can be useful at about K ≥ 20 000. It must also make the noise on the GPU, because the noise is the largest cost.
Run npm test. The tests use node:test and node:assert. The planner seed is 1, K = 1000, σ = 5.
| Test | What it examines |
|---|---|
| low lambda | At λ = 1, the drone reaches the goal in "Pillar dead ahead". |
| tiny lambda | At λ = 0.01, the drone reaches the goal. This test fails if the code does not subtract the minimum cost. |
| huge lambda | At λ = 105, the drone crashes. |
| middle lambda | At λ = 300, more than 25 safe futures pass on each side, and the drone does not crash. |
| forest | At λ = 1, the drone reaches the goal in forest seed 7. |
| WASM and JS | The two backends give identical costs for 2000 sequences, and the same flight result. |
| Symptom | Cause | Fix |
|---|---|---|
The page is empty. The browser console shows an error from atob. | kernel.wasm.js is missing, so MPPI_WASM_B64 is not defined. | Run npm install, then npm run build. |
npm run build shows Cannot find module 'wabt'. | The build tool is not installed. | Run npm install. |
The WASM test fails after you change kernel.wat or rolloutJS(). | The two rollouts no longer use the same operations in the same order. | Make the operations match. Then run npm run build and npm test. |
| The page is slow at a high sample count. | One iteration takes longer than 50 ms (about 57 ms at K = 20 000, JS backend). | Decrease K, or select the WebAssembly backend. |
| The drone crashes at each start. | λ is too high, or a pillar is on the start point. | Decrease λ to 1. Click the pillar at the start to remove it. |
| The drone does not reach the goal but does not crash. | λ is in the range 100 to 1000. The goal pull averages away. | Decrease λ to 30 or less. |
| The drone does not move in the forest at high λ. | All futures have equal weight, and the drone starts at rest. | Decrease λ. |
λ · uT Σ-1 ε.| File | Content |
|---|---|
index.html | Application page, canvas, controls |
mppi.js | MPPI core, used by the page and by Node |
kernel.wat | WebAssembly rollout source |
kernel.wasm.js | Generated. Assembled kernel as base64. |
build-wasm.js | Assembles kernel.wat into kernel.wasm.js |
test.js | Node tests |
package.json | Scripts build and test. Development dependency wabt. |
README.md | Markdown write-up |
docs/index.html | This document. GitHub Pages serves the repository root, so the app is at the site root and this document is at /docs/. |
| Command | Result |
|---|---|
npm install | Installs wabt for the build |
npm run build | Runs node build-wasm.js. Writes kernel.wasm.js. |
npm test | Runs node --test test.js |
The page uses globalThis.MPPI. Node uses require('./mppi.js').
| Name | Signature | Result |
|---|---|---|
createPlanner | (seed) | Planner with plan U, noise generator, and buffers |
mppiStep | (P, s, env, tr, {K, sigma, lambda, rollout}) | Updates P.U. Returns {cmin, best, ess, noiseMs, rolloutMs, avgMs}. |
applyAndShift | (P, s) | Flies the first step on state s, moves the plan forward |
outcome | (s, env) | 'crash', 'goal' or null |
rolloutJS | (s, goal, tr, V, K, costs) | Writes K costs into costs |
makeWasmRollout | (bytes) | A function with the same signature as rolloutJS |
packTrees | (trees) | Float64Array of cx, cy, rr per pillar |
trace | (s, ctrl) | Positions along a control sequence, for drawing |
deadAhead, forest | (), (seed) | Scenario objects {start, goal, trees} |
rng | (seed) | Seeded random function (mulberry32), values in [0, 1) |
| Constants | W, DT, T, DRONE_R, GOAL_R, HIT | See Configuration |