Multithreaded Architecture? Best practice to interact with Physics from async game logic.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Jason Swearingen

Hello, I am prototyping a multithreaded “game logic engine” using 3D and Godot 3.2b5. I’m using C# but GDScript could do it the same way. Basically I want my AI/rules to run in a Task/Job parallel system and communicate changes back to the godot visual and physics systems/threads.

Is there a best practice for interacting with Physics from other threads?

I have read through the docs and given that it almost exclusively covers 2D, I am guessing that it’s discussing the home-grown physics engine, not Bullet (used for 3d)

This is what I am guessing at for engine requirements/limitations, so please let me know if I’m wrong or if there’s a better way:

  1. Highest performance is to use the PhysicsServer and VisualServer directly. (I can’t find any tutorials on this, so I’ll be considering this optimization after getting a basic workflow down using Nodes)
  2. node position/physics mutates through a frame, so you should (must?) read/write this during _PhysicsProcess() synchronization.
  3. As an extrapolation of #2, the _Process() function must run gated with the Physics system? (synchronized, physics paused). If not, does this mean Physics is thread safe, and/or that calls like _MoveAndSlide() from _Process() stall out the Physics system?

And, I will release my work open source, either as a “C# Perf” tutorial or (even better) as a logic engine asset. Though I haven’t started the Job system yet, still prototyping a PubSub workflow.

I can’t completely answer this question, but I’m dealing with similar questions. As far as my research went, you can’t (yet) interact with Bullet physics from another thread using the externally exposed API, but you can use PhysicsServer (and all other Global scope singletons, as it says in the docs). In fact, when you try using physics nodes from a thread, even if outside the scene tree (the scene tree is not thread safe in the first place), it gives me various errors on Godot 3.3 (rc8 right now).
So far, I only tested this with Bullet physics.

Hoimar | 2021-04-12 20:17