Bullet 2.74 Physics SDK Manual

This draft documentation is work-in-progress
Check out the Wiki
and forums at http://bulletphysics.com
© 2009 Erwin Coumans
All Rights Reserved.
Table of Contents
Step 4: Integrating Bullet physics in your application
Step 5 : Integrate only the Collision Detection Library
Step 6 : Use snippets only, like the GJK Closest Point calculation.
Basic Data Types and Math Library
Memory Management, Alignment, Containers
Timing and Performance Profiling
Registering custom collision shapes and algorithms
5 Collision Filtering (selective collisions)
Filtering collisions using masks
Filtering Collisions Using a Broadphase Filter Callback
Filtering Collisions Using a Custom NearCallback
Deriving your own class from btCollisionDispatcher
Static, Dynamic and Kinematic Rigid Bodies
Center of mass World Transform
Simulation frames and interpolation frames
8 Actions: Vehicles & Character Controller
Construction from a triangle mesh
Applying forces to a Soft body
11 Advanced Low Level Technical Demos
Avoid very small and very large collision shapes
Avoid large mass ratios (differences)
Combine multiple static triangle meshes into one
Use the default internal fixed timestep
For ragdolls use btConeTwistConstraint
Don’t set the collision margin to zero
Use less then 100 vertices in a convex mesh
Avoid huge or degenerate triangles in a triangle mesh
Per triangle friction and restitution value
13 Parallelism: SPU, CUDA, OpenCL
Cell SPU / SPURS optimized version
Win32 Threads, pthreads, sequential thread support
IBM Cell SDK 3.1, libspe2 SPU optimized version
14 Further documentation and references
Bullet Physics is a professional open source collision detection, rigid body and soft body dynamics library. The library is free for commercial use under the ZLib license from http://bulletphysics.com
· SIMD constraint optimizations and debug visualization of joint frame and limits. Also many bugfixes, improved COLLADA converter, Actions and single-shot contact generation
· OpenCL, CUDA and Larrabee optimizations, and fracture of rigid bodies. See also http://code.google.com/p/bullet/issues/list
· Open source C++ code under Zlib license and free for any commercial use on all platforms including PLAYSTATION 3, XBox 360, Wii, PC, Linux, Mac OSX and iPhone
· Discrete and continuous collision detection including ray and convex sweep test. Collision shapes include concave and convex meshes and all basic primitives
· Fast and stable rigid body dynamics constraint solver, vehicle dynamica, character controller and slider, hinge, generic 6DOF and cone twist constraint for ragdolls
· Soft Body dynamics for cloth, rope and deformable volumes with two-way interaction with rigid bodies, including constraint support
· Maya Dynamica plugin, Blender integration, COLLADA physics import/export support
· Public forum for support and feedback is available at http://bulletphysics.com
· PLAYSTATION 3 licensed developers can download an optimized version for Cell SPU through Sony PS3 Devnet from https://ps3.scedev.net/projects/spubullet
Windows developers should download the zipped sources from of Bullet from http://bulletphysics.com. Mac OS X, Linux and other developers should download the gzipped tar archive.
Bullet should compile out-of-the-box for all platforms, and includes all dependencies.
· Windows Visual Studio projectfiles for all versions are available in Bullet/msvc. The main Workspace/Solution is located in Bullet/msvc/8/wksbullet.sln
·
CMake adds support for many other build environments and
platforms, including XCode for Mac OSX, KDevelop for Linux and Unix Makefiles.
Download and install Cmake from http://www.cmake.org.
Run cmake without arguments to see the list of build system generators for your
platform. For example to generate Mac OSX Xcode project files , run
cmake . –G Xcode
or to generate Linux/Unix Makefiles, run
cmake . –G “Unix Makefiles”
or for Microsoft Visual Studio 8 2005, use
cmake . –G “Visual Studio 8 2005”
· Autoconf/automake generates both Makefile and Jamfile. Run ./autogen.sh, ./configure and then make or jam.
Try to run and experiment with Demos/AllBulletDemos executable as a starting point. Bullet can be used in several ways, as full rigid body simulation, as collision detector library or low level / snippets such as GJK closest point calculation. The dependencies can be seen in the doxygen documentation under ‘Directories’.
Step 4: Integrating Bullet physics in your application
Check out CcdPhysicsDemo how to create a btDiscreteDynamicsWorld , btCollisionShape, btMotionState and btRigidBody. Each frame call the stepSimulation on the dynamics world, and synchronize the world transform for your graphics object. Requirements:
· #include “btBulletDynamicsCommon.h” in your source file
· Required include path: Bullet/src folder
· Required libraries: libbulletdynamics, libbulletcollision, libbulletmath
Step 5 : Integrate only the Collision Detection Library
Bullet Collision Detection can also be used without the Dynamics/Extras. Check out the low level demo Collision Interface Demo, in particular the class CollisionWorld. Requirements:
· #include “btBulletCollisionCommon.h” at the top of your file
· Add include path: Bullet/src folder
· Add libraries: libbulletcollision, libbulletmath
Step 6 : Use snippets only, like the GJK Closest Point calculation.
Bullet has been designed in a modular way keeping dependencies to a minimum. The Demos/ConvexHullDistance demo demonstrates direct use of btGjkPairDetector.
The main task of a physics engine is to perform collision detection, resolve collisions and other constraints, and provide the updated world transform[1] for all the objects. This chapter will give a general overview of the rigid body dynamics pipeline as well as the basic data types and math library shared by all components.
Bullet has been designed to be customizable and modular. The developer can
· use only the collision detection component
· use the rigid body dynamics component without soft body dynamics component
· use only small parts of a the library and extend the library in many ways
· choose to use a single precision or double precision version of the library
· use a custom memory allocator, hook up own performance profiler or debug drawer
The main components are organized as follows:
Before going into detail, the following diagram shows the most important data structures and computation stages in the Bullet physics pipeline. This pipeline is executed from left to right, starting by applying gravity, and ending by position integration, updating the world transform.
The entire physics pipeline computation and its data structures are represented in Bullet by a dynamics world. When performing ‘stepSimulation’ on the dynamics world, all the above stages are executed. The default dynamics world implementation is the btDiscreteDynamicsWorld.
Bullet let’s the developer choose several parts of the dynamics world explicitly, such as broadphase collision detection, narrowphase collision detection (dispatcher) and constraint solver.
If you want to use Bullet in your own 3D application, it is best to follow the steps in the HelloWorld demo, located in Bullet/Demos/HelloWorld. In a nutshell:
· Create a btDiscreteDynamicsWorld or btSoftRigidDynamicsWorld
These classes, derived from btDynamicsWorld , provide a high level interface that manages your physics objects and constraints. It also implements the update of all objects each frame.
· Create a btRigidBody and add it to the btDynamicsWorld
To construct a btRigidBody or btCollisionObject, you need to provide:
· Mass, positive for dynamics moving objects and 0 for static objects
· CollisionShape, like a Box, Sphere, Cone, Convex Hull or Triangle Mesh
· Material properties like friction and restitution
Update the simulation each frame:
· stepSimulation
Call the stepSimulation on the dynamics world. The btDiscreteDynamicsWorld automatically takes into account variable timestep by performing interpolation instead of simulation for small timesteps. It uses an internal fixed timestep of 60 Hertz. stepSimulation will perform collision detection and physics simulation. It updates the world transform for active objecs by calling the btMotionState’s setWorldTransform.
The next chapters will provide more information about collision detection and rigid body dynamics. A lot of the details are demonstrated in the Bullet/Demos. If you can’t find certain functionality, please visit the physics forum on the Bullet website at http://bulletphysics.com
Basic Data Types and Math Library
The basic data types, memory management and containers are located in Bullet/src/LinearMath.
· btScalar
A btScalar is a posh word for a floating point number. In order to allow to compile the library in single floating point precision and double precision, we use the btScalar data type throughout the library. By default, btScalar is a typedef to float. It can be double by defining BT_USE_DOUBLE_PRECISION either in your build system, or at the top of the file Bullet/src/LinearMath/btScalar.h.
· btVector3
3D positions and vectors can be represented using btVector3. btVector3 has 3 scalar x,y,z components. It has, however, a 4th unused w component for alignment and SIMD compatibility reasons. Many operations can be performed on a btVector3, such as add subtract and taking the length of a vector.
· btQuaternion and btMatrix3x3
3D orientations and rotations can be represented using either btQuaternion or btMatrix3x3.
· btTransform
btTransform is a combination of a position and an orientation. It can be used to transform points and vectors from one coordinate space into the other. No scaling or shearing is allowed.
Bullet uses a right-handed coordinate system:

Figure 1 Right-handed coordinate system
btTransformUtil, btAabbUtil provide common utility functions for transforms and AABBs.
Memory Management, Alignment, Containers
Often it is important that data is 16-byte aligned, for example when using SIMD or DMA transfers on Cell SPU. Bullet provides default memory allocators that handle alignment, and developers can provide their own memory allocator. All memory allocations in Bullet use:
· btAlignedAlloc, which allows to specify size and alignment
· btAlignedFree, free the memory allocated by btAlignedAlloc.
To override the default memory allocator, you can choose between:
· btAlignedAllocSetCustom is used when your custom allocator doesn’t support alignment
· btAlignedAllocSetCustomAligned can be used to set your custom aligned memory allocator.
To assure that a structure or class will be automatically aligned, you can use this macro:
· ATTRIBUTE_ALIGNED16(type) variablename creates a 16-byte aligned variable
Often it is necessary to maintain an array of objects. Originally the Bullet library used a STL std::vector data structure for arrays, but for portability and compatibility reasons we switched to our own array class.
· btAlignedObjectArray closely resembles std::vector. It uses the aligned allocator to guarantee alignment. It has methods to sort the array using quick sort or heap sort.
To enable Microsoft Visual Studio Debugger to visualize btAlignedObjectArray and btVector3, follow the instructions in Bullet/msvc/autoexp_ext.txt

Figure 2 MSVC Debug Visualization
Timing and Performance Profiling
In order to locate bottlenecks in performance, Bullet uses macros for hierarchical performance measurement.
· btClock measures time using microsecond accuracy.
· BT_PROFILE(section_name) marks the start of a profiling section.
· CProfileManager::dumpAll(); dumps a hierarchical performance output in the console. Call this after stepping the simulation.
· CProfileIterator is a class that lets you iterate through the profiling tree.
The profiling feature can be switched off by defining #define BT_NO_PROFILE 1 in Bullet/src/LinearMath/btQuickProf.h
Visual debugging the simulation data structures can be helpful. For example, this allows you to verify that the physics simulation data matches the graphics data. Also scaling problems, bad constraint frames and limits show up.
· btIDebugDraw is the interface class used for debug drawing. Derive your own class and implement the ‘drawLine’ and other methods.
The collision detection provides algorithms and acceleration structures for closest point (distance and penetration) queries as well as ray and convex sweep tests. The main data structures are:
· btCollisionObject is the object that has a world transform and a collision shape.
· btCollisionShape describes the collision shape of a collision object, such as box, sphere, convex hull or triangle mesh. A single collision shape can be shared among multiple collision objects.
· btGhostObject is a special btCollisionObject, useful for fast localized collision queries.
· btCollisionWorld stores all btCollisionObjects and provides an interface to perform queries.
The broadphase collision detection provides acceleration structure to quickly reject pairs of objects based on axis aligned bounding box (AABB) overlap. Several different broadphase acceleration structures are available:
· btDbvtBroadphase uses a fast dynamic bounding volume hierarchy based on AABB tree
· btAxisSweep3 and bt32BitAxisSweep3 implement incremental 3d sweep and prune
· btCudaBroadphase implements a fast uniform grid using GPU graphics hardware
The broadphase adds and removes overlapping pairs from a pair cache. The developer can choose the type of pair cache.
A collision dispatcher iterates over each pair, searches for a matching collision algorithm based on the types of objects involved and executes the collision algorithm computing contact points.
· btPersistentManifold is a contact point cache to store contact points for a given pair of objects.
Bullet supports a large variety of different collision shapes, and it is possible to add your own. For best performance and quality it is important to choose the collision shape that suits your purpose. The following diagram can help making a decision:

Most primitive shapes are centered around the origin of their local coordinate frame:
btBoxShape : Box defined by the half extents (half length) of its sides
btSphereShape : Sphere defined by its radius
btCapsuleShape: Capsule around the Y axis. Also btCapsuleShapeX/Z
btCylinderShape : Cylinder around the Y axis. Also btCylinderShapeX/Z.
btConeShape : Cone around the Y axis. Also btConeShapeX/Z.
btMultiSphereShape : Convex hull of multiple spheres, that can be used to create a Capsule (by passing 2 spheres) or other convex shapes.
Multiple convex shapes can be combined into a composite or compound shape, using the btCompoundShape. This is a concave shape made out of convex sub parts, called child shapes. Each child shape has its own local offset transform, relative to the btCompoundShape.
Bullet supports several ways to represent a convex triangle meshes. The easiest way is to create a btConvexHullShape and pass in an array of vertices. In many cases the graphics mesh contains too many vertices to be used directly as btConvexHullShape. ddsa
For static world environment, a very efficient way to represent static triangle meshes is to use a btBvhTriangleMeshShape. This collision shape builds an internal acceleration structure from a btTriangleMesh or btStridingMeshInterface. Instead of building the tree at run-time, it is also possible to serialize the binary tree to disc. See Demos/ConcaveDemo how to save and load this btOptimizedBvh tree acceleration structure. When you have several instances of the same triangle mesh, but with different scaling, you can instance a btBvhTriangleMeshShape multiple times using the btScaledBvhTriangleMeshShape.
Ideally, concave meshes should only be used for static artwork. Otherwise its convex hull should be used by passing the mesh to btConvexHullShape. If a single convex shape is not detailed enough, multiple convex parts can be combined into a composite object called btCompoundShape. Convex decomposition can be used to decompose the concave mesh into several convex parts. See the Demos/ConvexDecompositionDemo for an automatic way of doing convex decomposition.
Bullet provides support for the special case of a flat 2D concave terrain through the btHeightfieldTerrainShape. See Demos/TerrainDemo for its usage.
As the name suggests, the btStaticPlaneShape can represent an infinite plane or half space. This shape can only be used for static, non-moving objects.
Some collision shapes can have local scaling applied. Use btCollisionShape::setScaling(vector3). Non uniform scaling with different scaling values for each axis, can be used for btBoxShape, btMultiSphereShape, btConvexShape, btTriangleMeshShape. Uniform scaling, using x value for all axis, can be used for btSphereShape. Note that a non-uniform scaled sphere can be created by using a btMultiSphereShape with 1 sphere. As mentioned before, the btScaledBvhTriangleMeshShape allows to instantiate a btBvhTriangleMeshShape at different non-uniform scale factors. The btUniformScalingShape allows to instantiate convex shapes at different scales, reducing the amount of memory.
Bullet uses a small collision margin for collision shapes, to improve performance and reliability of the collision detection. It is best not to modify the default collision margin, and if you do use a positive value: zero margin might introduce problems. By default this collision margin is set to 0.04, which is 4 centimeter if your units are in meters (recommended).
Dependent on which collision shapes, the margin has different meaning. Generally the collision margin will expand the object. This will create a small gap. To compensate for this, some shapes will subtract the margin from the actual size. For example, the btBoxShape subtracts the collision margin from the half extents. For a btSphereShape, the entire radius is collision margin so no gap will occur. Don’t override the collision margin for spheres. For convex hulls, cylinders and cones, the margin is added to the extents of the object, so a gap will occur, unless you adjust the graphics mesh or collision size. For convex hull objects, there is a method to remove the gap introduced by the margin, by shrinking the object. See the Demos/BspDemo for this advanced use.
For each pair of shape types, Bullet will dispatch a certain collision algorithm, by using the dispatcher. By default, the entire matrix is filled with the following algorithms. Note that Convex represents convex polyhedron, cylinder, cone and capsule and other GJK compatible primitives. GJK stands for Gilbert, Johnson and Keerthi, the people behind this convex distance calculation algorithm. It is combined with EPA for penetration depth calculation. EPA stands for Expanding Polythope Algorithm by Gino van den Bergen. Bullet has its own free implementation of GJK and EPA.
Registering custom collision shapes and algorithms
The user can register a custom collision detection algorithm and override any entry in this Collision Matrix by using the btDispatcher::registerCollisionAlgorithm. See Demos/UserCollisionAlgorithm for an example, that registers a SphereSphere collision algorithm.
Bullet provides three easy ways to ensure that only certain objects collide with each other: masks, broadphase filter callbacks and nearcallbacks. It is worth noting that mask-based collision selection happens a lot further up the toolchain than the callback do. In short, if masks are sufficient for your purposes, use them; they perform better and are a lot simpler to use.
Of course, don't try to shoehorn something into a mask-based selection system that clearly doesn't fit there just because performance may be a little better.
Filtering collisions using masks
Bullet supports bitwise masks as a way of deciding whether or not things should collide with other things, or receive collisions.
For example, in a spaceship game, you could have your spaceships ignore collisions with other spaceships [the spaceships would just fly through each other], but always collide with walls [the spaceships always bounce off walls].
Your spaceship needs a callback when it collides with a wall [for example, to produce a “plink” sound], but the walls do nothing when you collide with them so they do not need to receive callbacks.
A third type of object, “powerup”, collides with walls and spaceships. Spaceships do not receive collisions from them, since we don't want the trajectory of the spaceship changed by collecting a powerup. The powerup object modifies the spaceship from its own collision callback.
In order to do this, you need a bit mask for the walls, spaceships, and powerups:
#define BIT(x) (1<<(x))enum collisiontypes { COL_NOTHING = 0, //<Collide with nothing COL_SHIP = BIT(1), //<Collide with ships COL_WALL = BIT(2), //<Collide with walls COL_POWERUP = BIT(3) //<Collide with powerups} int shipCollidesWith = COL_WALL;int wallCollidesWith = COL_NOTHING;int powerupCollidesWith = COL_SHIP | COL_WALL;
After setting these up, simply add your body objects to the world as normal, except as the second and third parameters pass your collision type for that body, and the collision mask.
btRigidBody ship; // Set up the other ship stuffbtRigidBody wall; // Set up the other wall stuffbtRigidBody powerup; // Set up the other powerup stuff mWorld->addRigidBody(ship, COL_SHIP, shipCollidesWith);mWorld->addRigidBody(wall, COL_WALL, wallCollidesWith);mWorld->addRigidBody(powerup, COL_POWERUP, powerupCollidesWith);It's worth noting that if you are using masks, and they're sufficient for your needs, then you do not need a custom collision filtering.
If you have more types of objects than bits available to you in the masks above, or some collisions are enabled or disabled based on other factors, then there are several ways to register callbacks to that implements custom logic and only passes on collisions that are the ones you want:
Filtering Collisions Using a Broadphase Filter Callback
One efficient way is to register a broadphase filter callback. This callback is called at a very early stage in the collision pipeline, and prevents collision pairs from being generated.
struct YourOwnFilterCallback : public btOverlapFilterCallback{ // return true when pairs need collision virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const { bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0; collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask); //add some additional logic here that modified 'collides' return collides; }};And then create an object of this class and register this callback using:
btOverlapFilterCallback * filterCallback = new YourOwnFilterCallback();dynamicsWorld->getPairCache()->setOverlapFilterCallback(filterCallback);Filtering Collisions Using a Custom NearCallback
Another callback can be registered during the narrowphase, when all pairs are generated by the broadphase. The btCollisionDispatcher::dispatchAllCollisionPairs calls this narrowphase nearcallback for each pair that passes the 'btCollisionDispatcher::needsCollision' test. You can customize this nearcallback:
void MyNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo) { // Do your collision logic here // Only dispatch the Bullet collision information if you want the physics to continue dispatcher.defaultNearCallback(collisionPair, dispatcher, dispatchInfo);} mDispatcher->setNearCallback(MyNearCallback);Deriving your own class from btCollisionDispatcher
For even more fine grain control over the collision dispatch, you can derive your own class from btCollisionDispatcher and override one or more of the following methods:
virtual bool needsCollision(btCollisionObject* body0,btCollisionObject* body1);
virtual bool needsResponse(btCollisionObject* body0,btCollisionObject* body1); virtual void dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,const btDispatcherInfo& dispatchInfo,btDispatcher* dispatcher) ;The rigid body dynamics is implemented on top of the collision detection module. It adds forces, mass, inertia, velocity and constraints.
· btRigidBody is the main rigid body object, moving objects have non-zero mass and inertia. btRigidBody is derived from btCollisionObject, so it inherits its world transform, friction and restitution and adds linear and angular velocity.
· btTypedConstraint is the base class for rigid body constraints, including btHingeConstraint, btPoint2PointConstraint, btConeTwistConstraint, btSliderConstraint and btGeneric6DOFconstraint.
· btDiscreteDynamicsWorld is derived from btCollisionWorld, and is a container for rigid bodies and constraints. It provides the stepSimulation to proceed.
Static, Dynamic and Kinematic Rigid Bodies
There are 3 different types of objects in Bullet:
· Dynamic (moving) rigidbodies
Ø positive mass
Ø every simulation frame the dynamics will update its world transform
· Static rigidbodies
Ø zero mass
Ø cannot move but just collide
· Kinematic rigidbodies
Ø zero mass
Ø can be animated by the user, but there will be only one-way interaction: dynamic objects will be pushed away but there is no influence from dynamics objects
All of them need to be added to the dynamics world. The rigid body can be assigned a collision shape. This shape can be used to calculate the distribution of mass, also called inertia tensor.
Center of mass World Transform
The world transform of a rigid body is in Bullet always equal to its center of mass, and its basis also defines its local frame for inertia. The local inertia tensor depends on the shape, and the btCollisionShape class provides a method to calculate the local inertia, given a mass.
This world transform has to be a rigid body transform, which means it should contain no scaling, shear etc. If you want an object to be scaled, you can scale the collision shape. Other transformation, such as shear, can be applied (baked) into the vertices of a triangle mesh if necessary.
In case the collision shape is not aligned with the center of mass transform, it can be shifted to match. For this, you can use a btCompoundShape, and use the child transform to shift the child collision shape.
MotionStates are a way for Bullet to do all the hard work for you getting the world transform of objects being simulated into the rendering part of your program.
In most situations, your game loop would iterate through all the objects you're simulating before each frame rander. For each object, you would update the position of the render object from the physics body. Bullet uses something called MotionStates to save you this effort.
There are multiple other benefits of MotionStates:
· Computation involved in moving bodies around is only done for bodies that have moved; no point updating the position of a render object every frame if it isn't moving.
· You don't just have to do render stuff in them. They could be effective for notifying network code that a body has moved and needs to be updated across the network.
· Interpolation is usually only meaningful in the context of something visible on-screen. Bullet manages body interpolation through MotionStates.
· You can keep track of a shift between graphics object and center of mass transform.
· They're easy
Bullet knows how to interpolate body movement for you. As mentioned, implemention of interpolation is handled through MotionStates.
If you attempt to ask a body for its position through btCollisionObject::getWorldTransform or btRigidBody::getCenterOfMassTransform, it will return the position at the end of the last physics tick. That's useful for many things, but for rendering you will want some interpolation. Bullet interpolates the transform of the body before passing the value to setWorldTransform.
If you want the non-interpolated position of a body [which will be the position as it was calculated at the end of the last physics tick], use btRigidBody::getWorldTransform() and query the body directly.
MotionStates are used in two places in Bullet.
The first is when the body is first created. Bullet grabs the initial position of the body from the motionstate when the body enters the simulation
Bullet calls getWorldTransform with a reference to the variable it wants you to fill with transform information
Bullet also calls getWorldTransform on kinematic bodies. Please see the section below
After the first update, during simulation Bullet will call the motionstate for a body to move that body around
Bullet calls setWorldTransform with the transform of the body, for you to update your object appropriately
To implement one, simply inherit btMotionState and override getWorldTransform and setWorldTransform.
Although recommended, it is not necessary to derive your own motionstate from btMotionState interface. Bullet provides a default motionstate that you can use for this. Simply construct it with the default transform of your body:
btDefaultMotionState* ms =new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,10,0)));
/* The constructor has default parameters that are the identity.
If you just want to create a body, you can construct a btDefaultMotionState with no parameters*/
Ogre3d Motion State example
Since Ogre3d seems popular, here's a full implementation of a motionstate for Bullet. Instantiate it with a the initial position of a body and a pointer to your Ogre SceneNode that represents that body. As a bonus, it provides the ability to set the SceneNode much later. This is useful if you want an object in your simulation, but not actively visible, or if your application archictecture calls for delayed creation of visible objects.
class MyMotionState : public btMotionState {
public:
MyMotionState(const btTransform &initialpos, Ogre::SceneNode *node) {
mVisibleobj = node;
mPos1 = initialpos;
}
virtual ~MyMotionState() { }
void setNode(Ogre::SceneNode *node) {
mVisibleobj = node;
}
virtual void getWorldTransform(btTransform &worldTrans) const {
worldTrans = mPos1;
}
virtual void setWorldTransform(const btTransform &worldTrans) {
if(NULL == mVisibleobj) return; // silently return before we set a node
btQuaternion rot = worldTrans.getRotation();
mVisibleobj->setOrientation(rot.w(), rot.x(), rot.y(), rot.z());
btVector3 pos = worldTrans.getOrigin();
mVisibleobj->setPosition(pos.x(), pos.y(), pos.z());
}
protected:
Ogre::SceneNode *mVisibleobj;
btTransform mPos1;
};
If you plan to animate or move static objects, you should flag them as kinematic. Also disable the sleeping/deactivation for them during the animation. This means Bullet dynamics world will get the new worldtransform from the btMotionState every simulation frame.
body->setCollisionFlags( body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
body->setActivationState(DISABLE_DEACTIVATION);
If you are using kinematic bodies, then getWorldTransform is called every simulation step. This means that your kinematic body's motionstate should have a mechanism to push the current position of the kinematic body into the motionstate.
Simulation frames and interpolation frames
By default, Bullet physics simulation runs at an internal fixed framerate of 60 Hertz (0.01666). The game or application might have a different or even variable framerate. To decouple the application framerate from the simulation framerate, an automatic interpolation method is built into stepSimulation: when the application delta time, is smaller then the internal fixed timestep, Bullet will interpolate the world transform, and send the interpolated worldtransform to the btMotionState, without performing physics simulation. If the application timestep is larger then 60 hertz, more then 1 simulation step can be performed during each ‘stepSimulation’ call. The user can limit the maximum number of simulation steps by passing a maximum value as second argument.
When rigidbodies are created, they will retrieve the initial worldtransform from the btMotionState, using btMotionState::getWorldTransform. When the simulation is running, using stepSimulation, the new worldtransform is updated for active rigidbodies using the btMotionState::setWorldTransform.
Dynamic rigidbodies have a positive mass, and their motion is determined by the simulation. Static and kinematic rigidbodies have zero mass. Static objects should never be moved by the user.
There are several constraints implemented in Bullet. See Demos/ConstraintDemo for an example of each of them. All constraints including the btRaycastVehicle are derived from btTypedConstraint. Constraint act between two rigidbodies, where at least one of them needs to be dynamic.
Point to point constraint, also known as ball socket joint limits the translation so that the local pivot points of 2 rigidbodies match in worldspace. A chain of rigidbodies can be connected using this constraint.
btPoint2PointConstraint(btRigidBody&
rbA,const btVector3& pivotInA);
btPoint2PointConstraint(btRigidBody& rbA,btRigidBody& rbB, const
btVector3& pivotInA,const btVector3& pivotInB);

Figure 3 Point to point constraint
Hinge constraint, or revolute joint restricts two additional angular degrees of freedom, so the body can only rotate around one axis, the hinge axis. This can be useful to represent doors or wheels rotating around one axis. The user can specify limits and motor for the hinge.
btHingeConstraint(btRigidBody& rbA,const btTransform& rbAFrame, bool useReferenceFrameA = false);
btHingeConstraint(btRigidBody& rbA,const btVector3& pivotInA,btVector3& axisInA, bool useReferenceFrameA = false);
btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3&
pivotInB, btVector3& axisInA,btVector3& axisInB, bool useReferenceFrameA = false);
btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btTransform& rbAFrame, const btTransform& rbBFrame, bool useReferenceFrameA = false);

Figure 4 Hinge Constraint
The slider constraint allows the body to rotate around one axis and translate along this axis.
btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA);

Figure 5 Slider Constraint
To create ragdolls, the conve twist constraint is very useful for limbs like the upper arm. It is a special point to point constraint that adds cone and twist axis limits. The x-axis serves as twist axis.
btConeTwistConstraint(btRigidBody& rbA,const btTransform& rbAFrame);
btConeTwistConstraint(btRigidBody& rbA,btRigidBody& rbB,const btTransform& rbAFrame, const btTransform& rbBFrame);
This generic constraint can emulate a variety of standard constraints, by configuring each of the 6 degrees of freedom (dof). The first 3 dof axis are linear axis, which represent translation of rigidbodies, and the latter 3 dof axis represent the angular motion. Each axis can be either locked, free or limited. On construction of a new btGeneric6DofConstraint, all axis are locked. Afterwards the axis can be reconfigured. Note that several combinations that include free and/or limited angular degrees of freedom are undefined.
btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA);
Following is convention:
btVector3 lowerSliderLimit = btVector3(-10,0,0);
btVector3 hiSliderLimit = btVector3(10,0,0);
btGeneric6DofConstraint* slider = new btGeneric6DofConstraint(*d6body0,*fixedBody1,frameInA,frameInB);
slider->setLinearLowerLimit(lowerSliderLimit);
slider->setLinearUpperLimit(hiSliderLimit);
For each axis:
· Lowerlimit == Upperlimit -> axis is locked.
· Lowerlimit > Upperlimit -> axis is free
· Lowerlimit < Upperlimit -> axis it limited in that range
In certain cases it is useful to process some custom physics game code inside the physics pipeline. Although it is possible to use a tick callback, when there are several objects to be updated, it can be more convenient to derive your custom class from btActionInterface. And implement the btActionInterface::updateAction(btCollisionWorld* world, btScalar deltaTime); There are built-in examples, btRaycastVehicle and btKinematicCharacterController, that are using this btActionInterace.
For most vehicle simulations, it is recommended to use the simplified Bullet vehicle model as provided in btRaycastVehicle. Instead of simulation each wheel and chassis as separate rigid bodies, connected by constraints, it uses a simplified model. This simplified model has many benefits, and is widely used in commercial driving games.
The entire vehicle is represented as a single rigidbody, the chassis. The collision detection of the wheels is approximated by ray casts, and the tire friction is a basic anisotropic friction model.
See src/BulletDynamics/Vehicle and Demos/VehicleDemo for more details, or check the Bullet forums.
Changing the up axis of a vehicle., see #define FORCE_ZAXIS_UP in VehiceDemo.
A basic player or NPC character can be constructed using a capsule shape, sphere or other shape. To avoid rotation, you can set the ‘angular factor’ to zero, which disables the angular rotation effect during collisions and other constraints. See btRigidBody::setAngularFactor. Other options (that are less recommended) include setting the inverse inertia tensor to zero for the up axis, or using a angular-only hinge constraint.
btKinematicCharacterController
is a class dedicated to character control. It uses a btGhostShape to perform collision queries
to create a character that can climb stairs, slide smoothly along walls etc. See
src/BulletDynamics/Character and Demos/CharacterDemo for its usage.
Soft
Body Dynamics
Preliminary documentation
The soft body dynamics provides rope, cloth simulation and volumetric soft bodies, on top of the existing rigid body dynamics. There is two-way interaction between soft bodies, rigid bodies and collision objects.
· btSoftBody is the main soft body object. It is derived from btCollisionObject. Unlike rigid bodies, soft bodies don’t have a single world transform: each node/vertex is specified in world coordinate.
· btSoftRigidDynamicsWorld is the container for soft bodies, rigid bodies and collision objects.
It is best to learn from Demos/SoftBodyDemo how to use soft body simulation.
Here are some basic guidelines in a nutshell:
Construction from a triangle mesh
The btSoftBodyHelpers::CreateFromTriMesh can automatically create a soft body from a triangle mesh.
By default, soft bodies perform collision detection using between vertices (nodes) and triangles (faces). This requires a dense tessellation, otherwise collisions might be missed. An improved method uses automatic decomposition into convex deformable clusters. To enable collision clusters, use:
psb->generateClusters(numSubdivisions);
//enable cluster collision between soft body and rigid body
psb->m_cfg.collisions += btSoftBody::fCollision::CL_RS;
//enable cluster collision between soft body and soft body
psb->m_cfg.collisions += btSoftBody::fCollision::CL_SS;
The Softbody and AllBulletDemos has a debug option to visualize the convex collision clusters.
Applying forces to a Soft body
There are methods to apply a force to each vertex (node) or at an individual node:
softbody ->addForce(const btVector3& forceVector);
softbody ->addForce(const btVector3& forceVector,int node);
It is possible to fix one or more vertices (nodes), making it immovable:
softbody->setMass(node,0.f);
or to attach one or more vertices of a soft body to a rigid body:
softbody->appendAnchor(int node,btRigidBody* rigidbody, bool disableCollisionBetweenLinkedBodies=false);
It is also possible to attach two soft bodies using constraints, see Bullet/Demos/SoftBody.
Bullet includes several demos. They are tested on several platforms and use OpenGL graphics and Glut. Some shared functionality like mouse picking and text rendering is provided in the Demos/OpenGL support folder. This is implemented in the DemoApplication class. Each demo derives a class from DemoApplication and implements its own initialization of the physics in the ‘initPhysics’ method.
This is a combination of several demos. It includes demonstrations of a fork lift, ragdolls, cloth and soft bodies and several performance benchmarks.
This is a that shows how to setup a physics simulation, add some objects, and step the simulation. It shows stable stacking, and allows mouse picking and shooting boxes to collapse the wall. The shooting speed of the box can be changed, and for high velocities, the CCD feature can be enabled to avoid missing collisions. Try out advanced features using the #defines at the top of Demos/CcdPhysicsDemo/CcdPhysicsDemo.cpp
Imports and exports COLLADA Physics files. It uses the included libxml and COLLADA-DOM library.
The COLLADA-DOM imports a .dae xml file that is generated by tools and plugins for popular 3D modelers. Dynamica Maya plugin, Blender and other software can export/import this standard physics file format. The Extras/BulletColladaConverter class can be used as example for other COLLADA physics integrations.
Import a Quake .bsp files and convert the brushes into convex objects. This performs better then using triangles.
This demo shows the use of the build-in vehicle. The wheels are approximated by ray casts. This approximation works very well for fast moving vehicles.
A demo that shows how to use constraints like hinge and slider constraint to build a fork lift vehicle.
This demo shows how to use Bullet collision detection without the dynamics. It uses the btCollisionWorld class, and fills this will btCollisionObjects. The performDiscreteCollisionDetection method is called and the demo shows how to gather the contact points.
This demo is more low level then previous Collision Interfacing Demo. It directly uses the btGJKPairDetector to query the closest points between two objects.
Shows how you can register your own collision detection algorithm that handles the collision detection for a certain pair of collision types. A simple sphere-sphere case overides the default GJK detection.
This demo show how to performs a linear sweep between to collision objects and returns the time of impact. This can be useful to avoid penetrations in camera and character control.
Shows time of impact query using continuous collision detection, between two rotating and translating objects. It uses Bullet’s implementation of Conservative Advancement.
This shows the use of CCD ray casting on collision shapes. It implements a ray tracer that can accurately visualize the implicit representation of collision shapes. This includes the collision margin, convex hulls of implicit objects, minkowski sums and other shapes that are hard to visualize otherwise.
This is a very low level demo testing the inner workings of
the GJK sub distance algorithm. This calculates the distance between a simplex
and the origin, which is drawn with a red line. A simplex contains 1 up to 4
points, the demo shows the 4 point case, a tetrahedron. The Voronoi simplex
solver is used, as described by Christer Ericson in his collision detection
book.
General Tips
Avoid very small and very large collision shapes
The minimum object size for moving objects is about 0.1 units. When using default gravity of 9.8, those units are in meters so don’t create objects smaller then 10 centimeter. It is recommended to keep the maximum size of moving objects smaller then about 5 units/meters.
Avoid large mass ratios (differences)
Simulation becomes unstable when a heavy object is resting on a very light object. It is best to keep the mass around 1. This means accurate interaction between a tank and a very light object is not realistic.
Combine multiple static triangle meshes into one
Many small btBvhTriangleMeshShape pollute the broadphase. Better combine them.
Use the default internal fixed timestep
Bullet works best with a fixed internal timestep of at least 60 hertz (1/60 second).
For safety and stability, Bullet will automatically subdivide the variable timestep into fixed internal simulation substeps, up to a maximum number of substeps specified as second argument to stepSimulation. When the timestep is smaller then the internal substep, Bullet will interpolate the motion.
This safety mechanism can be disabled by passing 0 as maximum number of substeps (second argument to stepSimulation): the internal timestep and substeps are disabled, and the actual timestep is simulated. It is not recommended to disable this safety mechanism.
For ragdolls use btConeTwistConstraint
It is better to build a ragdoll out of btHingeConstraint and/or btConeTwistLimit for knees, elbows and arms.
Don’t set the collision margin to zero
Collision detection system needs some margin for performance and stability. If the gap is noticeable, please compensate the graphics representation.
Use less then 100 vertices in a convex mesh
It is best to keep the number of vertices in a btConvexHullShape limited. It is better for performance, and too many vertices might cause instability. Use the btShapeHull utility to simplify convex hulls.
Avoid huge or degenerate triangles in a triangle mesh
Keep the size of triangles reasonable, say below 10
units/meters. Also degenerate triangles with large size ratios between each
sides or close to zero area can better be avoided.
Advanced Topics
Per triangle friction and restitution value
By default, there is only one friction value for one rigidbody. You can achieve per shape or per triangle friction for more detail. See the Demos/ConcaveDemo how to set the friction per triangle. Basically, add CF_CUSTOM_MATERIAL_CALLBACK to the collision flags or the rigidbody, and register a global material callback function. To identify the triangle in the mesh, both triangleID and partId of the mesh is passed to the material callback. This matches the triangleId/partId of the striding mesh interface.
An easier way is to use the btMultimaterialTriangleMeshShape. See the Demos/MultiMaterialDemo for usage.
Bullet uses its btSequentialImpulseConstraintSolver by default. You can use a different constraint solver, by passing it into the constructor of your btDynamicsWorld. For comparison you can use the Extras/quickstep solver from ODE.
If you want to have a different friction model for certain types of objects, you can register a friction function in the constraint solver for certain body types. This feature is not compatible with the cache friendly constraint solver setting.
See #define USER_DEFINED_FRICTION_MODEL
in Demos/CcdPhysicsDemo.cpp.
Parallelism: SPU, CUDA, OpenCL
Cell SPU / SPURS optimized version
Bullet collision detection and physics have been optimized for Cell SPU. This means collision code has been refactored to run on multiple parallel SPU processors. The collision detection code and data have been refactored to make it suitable for 256kb local store SPU memory. The user can activate the parallel optimizations by using a special collision dispatcher (SpuGatheringCollisionDispatcher) that dispatches the work to SPU. The shared public implementation is located in Bullet/src/BulletMultiThreaded.
Please contact Sony developer support on PS3 Devnet for a Playstation 3 optimized version of Bullet.
Efforts have been made to make it possible to re-use the SPU parallel version in other multi threading environments, including multi core processors. This allows more effective debugging of SPU code under Windows, as well as utilizing multi core processors. For non-SPU multi threading, the implementation performs fake DMA transfers using a memcpy, and each thread gets its own 256kb ‘local store’ working memory allocated.
Win32 Threads, pthreads, sequential thread support
Basic Win32 Threads, pthreads and sequential thread support is available to execute the SPU tasks. Some demos show this preliminary work in action. See #define USE_PARALLEL_DISPATCHER in Demos/ConcaveDemo and ConvexDecompositionDemo.
IBM Cell SDK 3.1, libspe2 SPU optimized version
IBM provides a Cell SDK with access to SPU through libspe2 for Cell Blade and PS3 Linux platforms. Libspe2 thread support is available through SpuLibspe2Support.
To compile the libspe2 version, first run make in the Bullet/src/ibmsdk directory. Then run
make –f Makefile.original spu ppu in the Bullet/src/BulletMultiThreaded directory, and then run make in the Bullet/Demos/CellSpuDemo/ibmsdk directory.
We are doing some research and development in using CUDA and OpenCL to accelerate parts of the physics pipeline. You can check Extras/CUDA and Extras/CDTestFramework for early results.
Visit the Bullet Physics website at http://bulletphysics.com for a discussion forum, a wiki with frequently asked questions and tips and download of the most recent version
· Dynamica Maya plugin, COLLADA-DOM, libxml are included in Bullet/Extras folder.
· Nima Maya plugin, COLLADA export: http://sourceforge.net/projects/nimaplugin
· Blender 3D modeler includes Bullet and COLLADA physics support: http://www.blender.org
· COLLADA physics standard: http://www.khronos.org/collada
·
Realtime Collision Detection, Christer Ericson
http://www.realtimecollisiondetection.net/
Bullet uses the discussed voronoi simplex solver for GJK
·
Collision Detection in Interactive 3D Environments, Gino van den Bergen
http://www.dtecta.com also website for
Solid collision detection library
Discusses GJK and other algorithms, very useful to understand Bullet
·
Physics Based Animation, Kenny Erleben
http://www.diku.dk/~kenny/
Very useful to understand Bullet Dynamics and constraints
The Bullet Physics library is under active development in collaboration with many professional game developers, movie studios, as well as academia, students and enthusiasts.
Main author and project lead is Erwin Coumans, former Havok employee and now working on this project at Sony Computer Entertainment America US R&D.
Some people that contributed source code to Bullet:
Roman Ponomarev, SCEA, constraints and CUDA implementation
John McCutchan, SCEA, ray cast, character control, several improvements
Nathanael Presson, Havok: initial author of Bullet soft body dynamics and EPA
Gino van den Bergen, Dtecta: LinearMath classes, various collision detection ideas
Christer Ericson, SCEA: voronoi simplex solver
Phil Knight, Disney Avalanche Studios: multiplatform compatibility, BVH serialization
Ole Kniemeyer, Maxon: various general patches
Simon Hobbs, SCEE: 3d axis sweep and prune: and Extras/SATCollision
Dirk Gregorius, Factor 5 : discussion and assistance with constraints
Erin Catto, Blizzard: accumulated impulse in sequential impulse
Francisco Leon : GIMPACT Concave Concave collision
Eric Sunshine: jam + msvcgen buildsystem
Steve Baker: GPU physics and general implementation improvements
Jay Lee, TrionWorld: double precision support
KleMiX, aka Vsevolod Klementjev, managed version, C# port to XNA
Marten Svanfeldt, Starbreeze: parallel constraint solver and other improvements and optimizations
Marcus Hennix, Starbreeze: btConeTwistConstaint etc.
Arthur Shek, Nicola Candussi, Lawrence Chai, Disney Animation: Dynamica Maya Plugin
Many more people have contributed to Bullet, thanks to everyone on the Bullet forums.