= Multithreading Bullet Physics in jme3
:author: 
:revnumber: 
:revdate: 2016/03/17 20:48
:keywords: documentation, physics, threading
:relfileprefix: ../../
:imagesdir: ../..
ifdef::env-github,env-browser[:outfilesuffix: .adoc]



== Introduction

Since bullet is not (yet) multithreaded or GPU accelerated, the jME3 implementation allows to run each physics space on a separate thread that is executed in parallel to rendering.


== How is it handled in jme3 and bullet?

A SimpleApplication with a BulletAppState allows setting the threading type via 

[source]
----
setThreadingType(ThreadingType type);
----

 where ThreadingType can be either SEQUENTIAL or PARALLEL. By default, it's SEQUENTIAL.

You can activate PARALLEL threading in the simpleInitApp() method:

[source,java]
----
bulletAppState = new BulletAppState();
bulletAppState.setThreadingType(BulletAppState.ThreadingType.PARALLEL);
stateManager.attach(bulletAppState);
----

Now the physics update happens in parallel to render(), that is, after the user's changes in the update() call have been applied. During update() the physics update loop pauses. This way the loop logic is still maintained: the user can set and change values in physics and scenegraph objects before render() and physicsUpdate() are called in parallel. This allows you to use physics methods in update() as if it was single-threaded.
[cols="2", options="header"]
|===

a|PARALLEL
a|SEQUENTIAL

a|1. update(), 2. render() and physics update().
<a|1. update(), 2. render(), 3. physics update().  

a|Physics Debug View is rendered inaccurately (out of sync)
a|Physics Debug View is rendered accurately.

|===


[TIP]
====
You can add more physics spaces by using multiple PARALLEL bulletAppStates. You would do that if you have sets physical objects that never collide (for example, underground bolders and flying cannon balls above ground), so you put those into separate physics spaces, which improves performances (less collisions to check!). 
====

