ftvs
November 4, 2026, 10:16am
1
The latest Box2D supports multithreaded physics calculation, but I could not find information on whether this is supported in Defold without diving into the source code.
Potential use case could be physics-heavy games, which would be enabled by this.
It will be in Defold 1.14.2:
dev ← physics-threading-support
opened 09:58AM - 01 Nov 26 UTC
Adds optional worker threads for **Box2D 3.x**, allowing physics stepping and ba… tched contact processing to use multiple CPU cores. Each physics tick finishes before gameplay continues, preserving synchronous queries and main-thread callback delivery.
Set **Box2D → Worker Count** in the project settings, or add this to `game.project`:
```ini
[box2d]
worker_count = 3
```
The default is `0`. The setting selects 0–31 background workers per physics world, with the main thread also participating, and is read at startup. Unsupported targets use the calling thread. Profile with threading enabled and disabled: small workloads can be slower because of scheduling overhead.
Fixes https://github.com/defold/defold/issues/10415
### Technical changes
- Give each Box2D world a scheduler using `dmThread` for worker creation and joining. Box2D retains its task scheduling, atomics, timers and semaphores. World/context destruction releases the scheduler and joins its workers.
- Gather contacts into reusable per-world buffers on workers for deferred, batched listeners, then deliver them in the original order on the calling thread. Immediate callbacks retain serial collection so their mutations remain visible to subsequent callbacks. Jobs finish inside `dmPhysics::StepWorld2D`; transforms and Lua callbacks remain on the game thread.
- Cache object ID hash userdata in a bounded, 256-slot cache while building each Lua event batch. Full 64-bit keys handle bucket collisions; retained events remain valid across later batches and garbage collection. Event tables, vectors and listener APIs keep their existing format and ownership. This shared Lua optimization also applies to the other physics backends.
- Preserve the `dmThread` scheduler adapter in `external/box2d/patch_3.2.0`. Applying the patch to the original archive reproduces all 85 vendored files byte for byte.
- Add a Lua integration regression with 0/3 workers and two 30 Hz physics ticks per 15 Hz game update. It checks event delivery between ticks, immediate raycasts after listener mutations, and the mutation taking effect in the next tick.
- Document the setting in the companion manual update: https://github.com/defold/doc/pull/695 (draft; merge with the engine feature).
#### Performance
Box2D 3.2, four substeps, Apple M5 Max, arm64 macOS 27.0.1, Apple Clang 21 / Xcode 27.1, `-O2`, headless. Off = 0 background workers; On = 3 background workers plus main. Both columns were measured at `7f23809a75` and include the Lua ID cache, so these isolate enabling threading rather than the full PR versus dev. Timings were not rerun for the subsequent correctness fixes and regression-test additions.
Three shuffled runs per configuration, each with three simulated seconds of warmup and five measured seconds. Values are medians of run means. Recorded frame deltas and spawn/delete commands match within each scene/schedule; physics states and event counts match with threading Off/On. Active Pile has 2500 awake dynamic bodies; Merge & Rain starts with 800 bodies and enables merging, rain and sleep.
**Box2D step (ms per physics tick)**
| Scene | Game / Physics update | Off | On | Change % | Speedup |
| --- | --- | ---: | ---: | ---: | ---: |
| Merge & Rain | Variable / Variable | 0.022 | 0.033 | +48.7% | 0.67× |
| Merge & Rain | Variable / 30 Hz | 0.078 | 0.069 | -10.8% | 1.12× |
| Merge & Rain | Variable / 60 Hz | 0.056 | 0.053 | -4.9% | 1.05× |
| Merge & Rain | 15 Hz / 30 Hz | 0.268 | 0.180 | -32.9% | 1.49× |
| Active Pile | Variable / Variable | 0.523 | 0.306 | -41.5% | 1.71× |
| Active Pile | Variable / 30 Hz | 0.689 | 0.422 | -38.8% | 1.63× |
| Active Pile | Variable / 60 Hz | 0.497 | 0.293 | -41.0% | 1.70× |
| Active Pile | 15 Hz / 30 Hz | 1.018 | 0.661 | -35.1% | 1.54× |
**CPU frame (ms per game update)**
| Scene | Game / Physics update | Off | On | Change % | Speedup |
| --- | --- | ---: | ---: | ---: | ---: |
| Merge & Rain | Variable / Variable | 0.304 | 0.324 | +6.6% | 0.94× |
| Merge & Rain | Variable / 30 Hz | 0.199 | 0.200 | +0.5% | 0.99× |
| Merge & Rain | Variable / 60 Hz | 0.200 | 0.202 | +1.1% | 0.99× |
| Merge & Rain | 15 Hz / 30 Hz | 3.673 | 3.485 | -5.1% | 1.05× |
| Active Pile | Variable / Variable | 4.773 | 4.220 | -11.6% | 1.13× |
| Active Pile | Variable / 30 Hz | 0.451 | 0.440 | -2.6% | 1.03× |
| Active Pile | Variable / 60 Hz | 0.535 | 0.516 | -3.7% | 1.04× |
| Active Pile | 15 Hz / 30 Hz | 18.846 | 17.511 | -7.1% | 1.08× |
Change = `(On / Off − 1) × 100`; speedup = `Off / On`. CPU frame excludes frame pacing and GPU work. Fixed-rate rows average all game frames, including frames without a physics tick. The 15/30 Hz case exercises multiple physics ticks per game update. Small differences are noisy with three runs. Small worlds can spend more on scheduling than they save, which is why threading remains opt-in.
#### Validation
- 251 tests passed across seven native/game-system suites on arm64 macOS: Box2D v2/v3, Bullet, Lua physics events and threading. The game-system suite includes both new worker/Lua integration cases.
- UBSan and TSan each passed 146 tests across Box2D, game-system physics, thread, condition-variable and JobSystem suites. ASan passed 145; `Bullet3DComponentTest.Bullet3DWorldQueryApiTest` reports the same Bullet/LuaJIT stack-use-after-scope already reproduced on the PR merge base. Both new integration cases pass all three sanitizers. Engine code and the Box2D scheduler were instrumented; packaged LuaJIT/Bullet dependencies were not rebuilt with sanitizers.
- Tests cover worker settings and platform fallback, scheduler ownership/reuse, calling-thread participation, ordered callbacks and transforms, synchronous queries, callback cancellation across solid contacts and sensors, immediate callback mutations, and retained Lua IDs through cache collisions and GC. Windows has a worker-handle create/destroy regression.
- The Windows engine CI job passed on `1b8b8c8406`: https://github.com/defold/defold/actions/runs/41300211321/job/124829402182. CI for this update runs separately; this does not claim results for the new head.
- `clang-format` 23.1.4 and Uncrustify 0.83.0 checked all 14 changed C/C++ files. Existing alignment and third-party style were preserved. Source whitespace checks passed; patch-file checks account for required unified-diff context whitespace.
- Manual spellcheck, frontmatter and Markdown structure checks passed. The Box2D vendor patch reproduces the checked-in source tree.
- Lower-performance hardware measurements and console worker support remain unvalidated. The serial fallback remains in place on unsupported targets.
A serial contact-gathering cutoff below 1,024 bodies was already tested and rejected: in Merge & Rain, median collection time rose from approximately 0.00393 to 0.00805 ms per tick, with no full-frame improvement. No speculative cutoff is included.
#### PR checklist
- [x] Engine unit tests added and passing, including worker/Lua integration coverage.
- [x] Code style, ownership and required comments checked.
- [x] Configuration help, editor labels and native API comments updated.
- [x] Separate manual update prepared in https://github.com/defold/doc/pull/695 (draft).
- [x] User-facing description and release-note title prepared.
- [x] Related issue linked.
6 Likes
ftvs
November 4, 2026, 10:23am
3
Thank you very much. Great to hear.
2 Likes