MPPI drone demo: technical documentation

Last updated: 2026-12-04. Project folder: drone-mppi.

1. Overview

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.

Canvas view. The quadcopter drone is at the left. A green pillar is in the center, a green goal ring at the right. A thick blue plan curves below the pillar toward the goal.
Figure 1. λ = 1, first planning step. The thick blue line is the plan. It already passes below the pillar.

2. The MPPI algorithm

Each step below matches a numbered comment in mppiStep() in mppi.js.

2.1 Model

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

2.2 One iteration

  1. Plan. The plan U holds 30 accelerations. 30 steps of 0.05 s give a horizon of 1.5 s. The plan starts at zero.
  2. Noise. The controller makes K noise sequences, one per sample. Each noise value has a standard deviation σ per step and per axis.
  3. Rollout. The controller simulates each perturbed control sequence Vk = clamp(U + εk) through the model. This gives K futures.
  4. Cost. The controller adds a cost for each step of each future (see 2.3).
  5. Weights. The controller turns each cost into a weight: wk = exp(-(ck - cmin) / λ). Then it normalizes the weights so that they sum to 1.
  6. Average. The new plan is the weighted average: U ← Σ wk Vk. This is equal to the old plan plus the weighted average of the noise.
  7. Receding horizon. The drone flies only the first step of the plan. The controller moves the plan forward by one step and sets the last step to zero. The next iteration starts from this plan. This is a warm start.

Steps 3 and 4 are independent for each sample. Thus the work can run in parallel.

2.3 Cost function

TermValue per stepEffect
Distance to goalEuclidean distance, mPulls the drone toward the goal. Typical values: 1 to 15.
Pillar contact1000 (HIT)Added for each step where the drone centre is closer than pillar radius + 0.3 m.
Off the map1000 (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.

2.4 Why the code subtracts the minimum cost

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).

2.5 Smooth noise

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.

2.6 Effective sample size

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.

3. Architecture

The project has three runtime files. index.html loads two classic scripts, then runs the user interface.

index.htmlsliders, canvas mppi.js: mppiStep() 1-2 noise 3-4 rollout 5-6 weights, avg rolloutJS kernel.wat kernel.wasm.jsbase64 bytes 7 applyAndShiftstate update outcome() draw()
Figure 2. Data flow for one control step. The rollout uses JavaScript or WebAssembly. Both give identical costs.

3.1 Components

ComponentFileJob
User interfaceindex.htmlReads the sliders. Runs the control loop at 20 Hz. Draws the canvas and the statistics.
MPPI coremppi.jsModel, cost, noise, weights, plan update, scenarios. It has no DOM code. The page and Node both load it.
JS rolloutrolloutJS() in mppi.jsSimulates K futures and writes K costs.
WASM rolloutkernel.watThe same rollout in hand-written WebAssembly text. It mirrors rolloutJS() operation for operation.
WASM loadermakeWasmRollout() in mppi.jsCopies trees and controls into WASM memory, calls the kernel, reads the costs back.
Build scriptbuild-wasm.jsAssembles kernel.wat into kernel.wasm.js.
Teststest.jsSix Node tests (see Tests).

3.2 Why it runs from file://

3.3 Control loop timing

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.

4. Requirements

UseRequirementVersion used for this document
Run the demoA browser with WebAssembly and canvas supportGoogle Chrome (headless, for screenshots)
Run the testsNode.js with node:test and global performanceNode v26.14.0
Rebuild the WASM kernelnpm package wabt1.0.39 (pinned in package.json)

The demo needs no server, no network, and no npm packages to run.

5. Installation

5.1 Run the demo

To run the demo without a download, open the live demo. To run it from the local disk, do these steps:

  1. Open the folder drone-mppi.
  2. Double-click index.html.

The page opens in the default browser. The drone starts to fly at once.

5.2 Run the tests

  1. Open a terminal in the project folder.
  2. Run the tests:
    npm test

The output shows pass 6 and fail 0.

5.3 Rebuild the WASM kernel

Do this only after you change kernel.wat. The project includes a built kernel.wasm.js.

  1. Install the build tool:
    npm install
  2. Assemble the kernel:
    npm run build
  3. Make sure that the output shows the byte count, for example kernel.wasm.js: 376 bytes of wasm.
  4. Run npm test. The bit-identical test must pass.

Do not edit kernel.wasm.js by hand. The build overwrites it.

6. Usage

6.1 Screen

Item on the canvasMeaning
Quadcopter frameThe 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 droneVelocity. Length = distance flown in 0.3 s.
Green discsPillars (trees)
Green ringGoal. Radius 0.5 m.
Grey linesSampled futures. A darker line has a larger weight.
Red linesSampled futures that hit a pillar or left the map
Orange lineThe future with the lowest cost
Thick blue lineThe new plan (the weighted average)
Red flash / green flashCrash / 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.

6.2 Mouse actions

ActionResult
Click an empty pointAdds a pillar with radius 0.6 m
Click a pillarRemoves the pillar
Shift + clickMoves the goal to that point

6.3 Buttons

ButtonResult
Scenario listSelects "Pillar dead ahead" or "Forest". The drone goes back to the start.
ResetPuts the drone at the start and clears the plan. The pillars you added stay.
Pause / PlayStops or starts the simulation
New forestMakes a new random forest with the next seed

6.4 Procedure: see the effect of λ

  1. Select the scenario "Pillar dead ahead".
  2. Set λ to 1.
  3. Watch the drone. It goes around the pillar and reaches the goal.
  4. Set λ to about 300.
  5. Click Pause.
  6. Click Reset.
  7. Examine the canvas. Two groups of grey futures go left and right. The blue plan points between them, at the pillar.
  8. Click Play. The drone swerves to one side but does not reach the goal.
  9. Set λ to 105.
  10. Watch the drone. It flies into the pillar.
Canvas view at lambda 300. Black futures fan out above and below the pillar. Red futures pass through it. The blue plan goes almost straight into the pillar.
Figure 3. λ = 300, first planning step. Safe futures pass on both sides. Their average, the blue plan, points at the pillar.
Canvas view at lambda 100000. Many red futures pass through the pillar. The blue plan is a straight line through the pillar to the goal.
Figure 4. λ = 105. All futures have almost the same weight, crashed futures too. The plan stays straight.

7. Configuration

7.1 Page controls

ControlTypeRangeDefaultEffect
λ temperatureLog slider0.01 to 1071Low: the best futures win. High: all futures have an equal vote.
Samples KSlider, step 100100 to 20 0001000Number of futures per step
Noise σSlider, step 0.50.5 to 10 m/s²5Standard deviation of the noise
Rollout backendListJavaScript, WebAssemblyJavaScriptSelects the rollout code. The result is identical.
Futures drawnSlider, step 100 to 300120Number of sampled futures on the canvas. It does not change the control.

7.2 Constants in mppi.js

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.

NameTypeDefaultEffect
W, Hnumber20, 20 mMap size. Outside the map counts as a crash.
DTnumber0.05 sModel time step and control period
Tinteger30Steps in the plan. Horizon = T · DT = 1.5 s.
DRONE_Rnumber0.3 mDrone radius. Added to each pillar radius for collisions.
GOAL_Rnumber0.5 mDistance to the goal that counts as reached. Also the radius of the goal ring.
A_MAXnumber10 m/s²Acceleration limit per axis
HITnumber1000Cost per step inside a pillar or off the map
SMOOTHnumber0.9Noise correlation between steps. 0 gives white noise.

7.3 Scenarios

ScenarioStartGoalPillars
Pillar dead ahead (deadAhead())(2, 10) m, velocity 12 m/s toward the goal(18, 10) mOne pillar at (10, 10) m, radius 1.2 m
Forest (forest(seed))(1.5, 10) m, at rest(18.5, 10) m28 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.

Canvas view of the forest scenario. About 28 green pillars of different sizes. The quadcopter drone is at the left edge. Faint futures fan out from the drone. A blue plan goes up and to the right.
Figure 5. Forest scenario, seed 1, near the start. Grey futures go in all directions. The blue plan is their weighted average for this step.

8. Results

8.1 Effect of λ on the dead-ahead scenario

Conditions: K = 1000, σ = 5 m/s², planner seeds 1 to 5, at most 300 steps (15 s). One step is 0.05 s.

λResultCause
0.01 to 1Goal in about 1.5 s, all seedsA few futures have almost all the weight. The drone selects one side at once.
10 to 30Goal in 1.7 to 2.3 sThe average is softer but still selects a side.
100 to 1000No crash. No goal in 15 s.Crashed futures have no weight. The goal term is small relative to λ, so the goal pull averages away.
3000Crash in 4 of 5 seedsλ is larger than a few collision steps. Crashed futures start to get weight.
≥ 10 000Crash at about 0.55 s, all seedsAll futures have almost equal weight. The noise averages to about 0, so the plan stays straight.

8.2 Left and right futures

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".

8.3 Speed

Conditions: Node v26.14.0 (V8 engine), Apple arm64, forest seed 1 (28 pillars). Times are milliseconds per iteration.

KRollout, JS (ms)Rollout, WASM (ms)Full iteration, JS backend (ms)
1 0000.810.422.4 to 2.6
5 0004.231.9614.0
20 00016.88.057

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.

9. WebAssembly backend

The kernel in kernel.wat does the rollout and the cost. JavaScript still makes the noise and does the weights and the average.

9.1 Memory layout

All values are 64-bit floats (f64).

Byte offsetContentSize
0Pillars: 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 sampleK · T · 16 bytes
CTRL + K · T · 16Output costsK · 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.

9.2 Bit-identical results

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.

9.3 Effect

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.

10. GPU decision

The project does not use the GPU. The reasons:

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.

11. Tests

Run npm test. The tests use node:test and node:assert. The planner seed is 1, K = 1000, σ = 5.

TestWhat it examines
low lambdaAt λ = 1, the drone reaches the goal in "Pillar dead ahead".
tiny lambdaAt λ = 0.01, the drone reaches the goal. This test fails if the code does not subtract the minimum cost.
huge lambdaAt λ = 105, the drone crashes.
middle lambdaAt λ = 300, more than 25 safe futures pass on each side, and the drone does not crash.
forestAt λ = 1, the drone reaches the goal in forest seed 7.
WASM and JSThe two backends give identical costs for 2000 sequences, and the same flight result.

12. Troubleshooting

SymptomCauseFix
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 λ.

13. Limitations and next steps

14. Reference

14.1 Files

FileContent
index.htmlApplication page, canvas, controls
mppi.jsMPPI core, used by the page and by Node
kernel.watWebAssembly rollout source
kernel.wasm.jsGenerated. Assembled kernel as base64.
build-wasm.jsAssembles kernel.wat into kernel.wasm.js
test.jsNode tests
package.jsonScripts build and test. Development dependency wabt.
README.mdMarkdown write-up
docs/index.htmlThis document. GitHub Pages serves the repository root, so the app is at the site root and this document is at /docs/.

14.2 Commands

CommandResult
npm installInstalls wabt for the build
npm run buildRuns node build-wasm.js. Writes kernel.wasm.js.
npm testRuns node --test test.js

14.3 API of mppi.js

The page uses globalThis.MPPI. Node uses require('./mppi.js').

NameSignatureResult
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)
ConstantsW, DT, T, DRONE_R, GOAL_R, HITSee Configuration