Running physics in a webworker

Hi, I’m optimising my game and want to run ammo.js physics in a separate thread via web workers.

Im not sure where to begin as I haven’t used web workers before. I’ve looked into physi.js which allows three.js and ammo.js to run in separate threads. But it looks like it would be easier to do it myself then try to make physi.js work with Babylon.

If anyone tried this before in Babylon I’d really appreciate some pointers to get me started :slight_smile:

1 Like

Update: After hunting around the internet I found an old blog post by Raanan Weber.
Unfortunately the git hub repos linked in the article are not there anymore :frowning: . But at least its a starting point.

@Raggar I noticed you mentioned using web workers for your physics. Can you please share some of your secrets o wise one?

We even have have an open issue for that: Physics in a separate worker process · Issue #6071 · BabylonJS/Babylon.js · GitHub

Well. Unfortunately I don’t have any simple examples at hand. Only bigger custom projects. I’ve had a hard time choosing whether or not to use workers for my physics. You see, first of all it adds some complexity to the code, but secondly, the messaging system between the main thread and workers isn’t as real-time as one would think. The transfer speed of messages is fast, but sending the message doesn’t seem to be instantaneous.
You can use interpolation between updates, but that just seems a bit wrong.
Use SharedArrayBuffers if supported, else use transferables if supported(remember to send this array back and forth to prevent recreation), else use normal cloning with postMessage.
Using object cloning and postMessage is perfectly fine for most things including sending inputs, corrections, new objects to be created etc. But any big arrays that might change every frame should if possible, use SharedArrayBuffers or transferables.

Make a PG so we can play around with it a little.

A simple test-PG using native Ammo.js and an inline worker:

It uses cloning of objects when sending through postMessage(Not even serializing it using JSON!)


Woot!!! This could be a HUGE addition to our physic system! Will love to merge such a PR :wink:

That’s magical.

That playground is awesome! thanks @Raggar your an absolute legend!