Description
I'm working on the WebAssembly port of Box2D 3, which you can find here: box2d3-wasm.
We're aiming to make it feature-complete and highly flexible for web users. One challenge I'm currently facing involves supporting the PreSolve callback in JavaScript.
Ideally, I want developers using the WASM build to be able to define a PreSolve callback directly in JavaScript, so they can make custom, real-time decisions on contact resolution.
Here's how I've set it up currently:
https://github.com/Birch-san/box2d3-wasm/blob/0a839337b041e1de851fc7be9e9a6aae6e4edc4e/box2d3-wasm/csrc/glue.cpp#L1562
This approach works perfectly in single-threaded builds and behaves exactly as intended. However, in multithreaded builds, I get the following runtime error:
Assertion failed: pthread_equal(thread, pthread_self()) && "val accessed from wrong thread"
Which makes sense, the callback is defined in JS, and Emscripten's val interface enforces that JavaScript calls only occur on the main thread for safety.
My question is: is there a known or recommended pattern for allowing JS-defined callbacks (like PreSolve) in a multithreaded Emscripten environment? Or is the best route simply to restrict this feature to single-threaded builds? ( I tinkered with proxying, but this resulted in a deadlock for me)
Any insights, suggestions, or pointers would be greatly appreciated!