Blender is a unique 3D animation suite in that it contains a full-featured game engine for the creation of games and other free-standing interactive content. Nevertheless, in spite of its core of devoted fans, the game engine is an all-too-often overlooked feature of Blender.
In this chapter, you’ll learn the basics of working with Bullet Physics in the BGE to the point that you can easily create dynamic rigid body animations, which can then be used in the Blender animation environment you’re accustomed to. If you are new to BGE, you will be surprised by how much amazing functionality it will open up for you. If not, this chapter should provide some interesting ideas for how to integrate real-time generated physics simulations with rendered animations.
In this chapter, you will learn to
It goes without saying that for people who are mainly interested in creating games, the game engine is one of Blender’s major attractions. The BGE is widely used by hobbyist game creators and as a basis for real-time, interactive visualization.
As everybody who’s ever played a game knows, game worlds can be pretty rough-and-tumble places. Cars crash, walls crumble, and bad guys go flying across rooms. This is all made possible by physics simulation, and any quality game-creation tool these days needs a good real-time Newtonian physics library. For Blender, this is the open-source Bullet Physics Library. Indeed, Blender is not alone in this; the Bullet Physics Library, authored by Erwin Coumans, simulation lead at Sony Computer Entertainment America, is being used by professional game developers with parallel optimizations for PlayStation 3 and Xbox 360. The companies that use Bullet are able to contribute back to Bullet under the zlib license.
Bullet was showcased in an entertaining way in the Bullet Physics Contest 2007, in which contestants competed to create the most impressive Rube Goldberg machine in BGE. Some stills from Christopher Plush’s winning machine can be seen in . Since then, a variety of improvements and additions have been introduced to the Bullet library.
Stills from Christopher Plush’s winning Bullet Rube Goldberg machine
This chapter shows you how to access the features of this powerful library for use in your own animation work.
At the time of this writing, the Google Summer of Code 2012 is in full swing. One of the projects currently ongoing is Sergej Reich’s Bullet integration project, which aims to fully integrate the Bullet library’s physics simulations into Blender’s standard animation environment, similarly to the way particles, fluid simulation, and forces are currently integrated. Test builds for this project are already available at . However, this project is not at a stable point at present, and as with all developmental functionality, it's unwise to place bets on when it will be fully completed. In the meantime, Bullet functionality must be accessed in the way it has traditionally been in Blender, through the Blender Game Engine (BGE). Rest assured, however, that once you understand the way Bullet settings, collision boundaries, and rigid body constraints work, you will have an easy time adapting to the integrated interface when it becomes available.
For the sake of broad accessibility, I’m going to assume that you’ve never touched BGE. For a lot of animators and illustrators, the little Joystick icon in the corner of the Properties window area is ignored and slightly intimidating, and pressing P by accident can yield a nasty surprise. If that sounds like you, then it’s time to change that. If you do have experience with BGE, you might want to skim this section. On the other hand, if you want to get more in depth about using the BGE to create actual games, you should study Part V of this book, which deals exclusively with the BGE. The goal here is to get comfortable enough with BGE to make full use of its physics simulation functionality.
To get started, fire up a session of Blender. In the top view (NUM7), do the following:
Add a plane and scale up.
Translate downward.
Switching to Blender Game render mode
Enabling the cube as a Rigid Body object in BGE
Actor parameters
The cube bounces against the plane.
Selecting Game Logic properties
Setting a keyboard action sensor
Click the Key field, and then press the spacebar when prompted.
Connecting the sensor to the controller
Adding an actuator
Enjoying an exciting game of “Push the Cube into the Abyss”
More controls
Add an Icosphere.
Parameters for the sphere
An even more exciting game of “Push the Sphere into the Abyss with the Cube”
For the purposes of this chapter, only minimal interactive logic is necessary, so this is all the detail I’m going to cover here. Much of the time, no interaction will be necessary—you’ll just set up a physical situation and let the simulator take over. However, sometimes using interactive triggers can be very handy to get the effect you want. For more information about working with interactive content in the game engine, you can refer to Part V of this book.
For people designing games, it’s important to be able to have animated objects and armature motions accessible to the game logic. Mostly, animators are best off doing sophisticated animation in the ordinary Blender animation environment—animation in the game engine is far more restrictive than it is in Blender itself. Nevertheless, there are times when you will want to simulate physical reactions to hand-keyed animation. To do this with BGE, you use actions in the game-play environment, as follows:
Keyed location and rotation at frame 31
Sensor, controller, and Ipo actuator setup
You now know how to set up basic physics simulations in BGE. But if you’re reading this book, chances are you’re most interested in using these simulations in your rendered animations. For this, real-time simulation in the game play mode of the game engine is not sufficient. You need a way to run the simulation in Blender’s animation system.
The traditional way to do this in Blender has been to bake game engine animations to F-Curves. Over the years and versions, various tools have come and gone to make this easier and less unwieldy, but as of the current version of Blender (2.64 is in pre-release testing as I write this), this is still the only way to do rigid body simulation for animation in Blender.
This is likely to change in the near future. As I write this, Sergej Reich has successfully passed the midpoint of his Google Summer of Code 2012 project, which involves full Bullet integration into the Blender animation system. This system is currently very much in development on a branch of its own and has not yet been merged with the Blender trunk. As is always the case, large new features can be unpredictable in terms of when they are stable enough to be merged with main Blender development. You can look for versions of this on by searching for builds of the Bullet integration branch.
You can save the movements of Dynamic objects in BGE by selecting Record Animation from the Game menu in the User Preferences/Information header at the top of your Blender workspace, as shown in . After you exit from game play mode by pressing Esc, animation F-Curves will be associated with whatever objects were enabled as Dynamic objects in the physics simulation. You can press Alt+A or click the Play button on the timeline and play the animation like any other animation, and you can render it as you would anything else in Blender.
Record Animation menu option
The animated shot shown in was created in this way. Six cubes were created and set up vertically in space along the lines of the first image in the sequence. Each cube was enabled as an actor and made dynamic. Rigid Body was selected to enable the blocks to roll and tumble. Another cube was scaled to the shape of a book, and under that a shadow-only plane was added for the blocks to land on. After baking the F-Curve from BGE, some image textures were added to the objects, a sky map was applied, and the animation was rendered with the Blender Internal renderer using ray shadows.
Rigid body blocks in a rendered animation
If you try this with the first example of this chapter or with an example of your own, you will surely notice that when you press Alt+A or render your animation to a movie, the resulting simulation is in slow motion. This occurs because the game engine uses a default frame rate of 60 frames per second (fps). This is desirable for real-time graphics for several reasons, but it is much faster than is necessary for animated movies, which are usually either 24 fps or 30 fps. This means that when you record actions from the game engine, the resulting actions will be normal speed when played back at 60 fps but will be slower than half speed when played back at 24 fps. Furthermore, if you use hand-keyed actions in the animation in the form of Action actuators, as described in the second example in this chapter, you’ll find that the resulting baked physics actions do not sync up properly with the hand-keyed actions in the animation because of mismatched frame rates.
To correct this in the game engine, you need to reset the BGE frame rate to match the frame rate of the animation you want to create, such as 24 fps. This is done in the FPS field in the World properties area, shown in .
Setting the frame rate in World properties
In this section, you’ll set up a complete rigid body simulation from scratch that includes both actions and physics. The completed simulation can be found on the website for this book in the file ballandcubes.blend.
Follow these steps to put the elements in place and run the simulation:
Setting up the rigid body scene
Add an armature.
Translate the armature downward.
Translate the tip in Edit mode.
Making the sphere a Rigid Body object
The animated simulation
Keying the “kick”
The sphere kicked off the plane
Objects need to have several qualities in order to behave naturally in physics simulations. You’ve already come across several of these as you’ve been setting up objects for Bullet simulations. Now I’ll discuss what the terms mean in a little more detail. The rigid body physics settings in the Physics properties area contain the following options:
In the next row in the panel are the Mass and Radius parameters. The Mass value determines the mass of the object relative to other objects in the simulation. When an object with a greater mass collides with an object with less mass, the trajectory of the object with less mass is more affected. As in the real world, objects with greater mass have greater inertia. This means that they require more force to get moving and also that they are more difficult to slow down when they are moving, making them less subject to damping in the physics engine. Because of current limitations in the Bullet physics engine (and in fact all physics engines), simulations become unstable when objects with extremely different masses interact in certain ways. Objects in constraint chains should be within a few kilograms of each other, and very heavy objects should not be placed on top of very light objects. These kinds of interactions between objects with extreme differences in mass should probably be keyed by hand or simulated in another way, such as with particles.
The Radius parameter indicates the size of the sphere collision bounds. When you enable an object as a dynamic actor, the sphere is displayed as a dotted line representing the default collision boundary for the object (as shown in ). This is accurate only if your object is a sphere. If not, you will need to select a more-appropriate collision boundary type, and Radius is not pertinent (although the dotted circle will continue to display).
In the area below the Mass and Radius fields are the damping fields. Damping for both Translation and Rotation remove motion energy from the object over time—Damp from Translation and RotDamp from Rotation. When these values are zero, no damping occurs and the movement of the object is unimpeded. With higher values, movement and rotation are diminished to mimic the effects of air friction.
Radius values of 1.0 (default), 2.0, and 0.5
By default, a Rigid Body object behaves like a sphere, rolling on the boundary defined by its Radius value. For most shapes, this is not what you want. In order to have Bullet calculate the collision boundaries accurately for the object, you must select a collision boundary type by clicking Bounds and selecting one of the following options from the drop-down menu:
It is worth noting that there is no visual feedback for these boundary types. Regardless of which you choose, the dotted sphere will be shown. To the right of the drop-down menu is the Compound button. This button must be selected if the object has children. When you select this, the object and its children will be considered collectively as a single compound object. The Compound option enables you to add multiple collision shapes in a single Rigid Body object. The secret of doing more advanced physics simulations is cleverly combining Convex Hull and Triangle Mesh bound objects as Compound objects in such a way that all the objects appear to interact with each other in an accurate way.
In this example, the solution uses several boundary types together. The goal is to create a rigid body simulation with a ball and a glass, in which the ball can fall into the glass in a natural way and the glass can interact with both the ball and the floor plane correctly, as shown in .
The ball interacting with the glass and the floor
As you’ve seen in previous examples, the floor and the ball are simple to set up. The difficulty here is the glass. The glass must be a dynamic Rigid Body object in order to fall and tumble naturally, so simply making it a Triangle Mesh is not an option. It does not fit into one of the predefined shapes such as sphere or box, so those are also out. Finally, using a Convex Hull boundary is also not possible, because this boundary type cannot represent concavities. If the glass is a Convex Hull, the ball will settle on top of the glass, rather than falling into the mouth of the glass, as shown in . To get around these problems, it will be necessary to create a Compound object for the cup composed of several component objects of different boundary types.
To see how this can be done, first model a glass with geometry as shown in , or else append the object glass from the .blend file glassandball.blend, found on the website for this book. Before beginning the following process, make sure that any object-level rotation or scaling has been applied with Ctrl+A and any translations cleared with Alt+G. Also make sure that any Ipos associated with the object at this point are disconnected by clicking the X button to the right of the Ipo drop-down menu in the Ipo Editor header.
If the glass is a Convex Hull, the ball sits on top.
Model the glass with this geometry.
As mentioned earlier, it is possible to have a Triangle Mesh move if it is parented to a moving object. This means that it is possible to have the glass itself be a Triangle Mesh in order to interact correctly with the ball. However, if this is the case, the glass cannot collide with the ground; two Triangle Meshes do not collide with each other. It is necessary to create a set of special collision meshes to do this.
Separating the vertices
The separated collision mesh in Edit mode
Filling in faces between vertices in the collision mesh
Scaling down along the x- and y-axes
Scaling down along the z-axis
Separating one corner segment into its own object
Parenting hull objects
Clear Parent Inverse
Settings for hull1, for hulls 2 through 4, and for glass
Setting the collision meshes not to render
There are several further points to keep in mind when working with Bullet:
You can see more information about how the physics is working by selecting Show Physics Visualization in the Game drop-down of the Information window header, shown in . When this is selected, color-coded physics information will be visible in game play mode when you press P.
The example in shows a small chain of three objects that are constrained to each other by rigid body joins. The leftmost cube is not dynamic; the other two objects are Rigid Body objects.
Show Physics Visualization
Objects with Rigid Body constraints
When P is pressed, the Rigid Body objects fall in a chain and their physics is highlighted, as shown in . Bounding boxes are shown in red. Physics is calculated on the structures displayed in white, which indicate the Rigid Body object’s center of gravity, and when the simulation reaches a state of equilibrium, those structures turn green, indicating that the Rigid Body object is “sleeping.” Sleeping increases the efficiency of the simulation and reduces the possibility of jitter for motionless objects. Physics visualization is helpful for seeing how objects are colliding with each other and also to make sure that Compound objects are set up correctly.
In 3D, as in the real world, joints are mechanisms that hold two solid objects together, allow certain freedoms in how the objects move in relation to each other, and restrict other kinds of movements. In 3D there are usually considered to be three fundamental types of joints that differ in the kinds of movement they allow. These are hinges, ball-and-socket joints, and slider joints.
illustrates the different ways that these joints behave. The hinge allows the objects to rotate on a specific axis around a common point with respect to each other. The ball-and-socket joint allows combinations of rotation around all three axes. The slider joint allows the objects not to rotate but to translate (move) along an axis with respect to each other.
Visualizing the simulation in action and sleeping
Hinge, ball-and-socket, and slider joints
In Blender, you can set up joints by using the Rigid Body Joint constraint found in the Constraints tab of the Object Properties area. To get an idea of these, start up a fresh session of Blender, duplicate the default cube, and move the new copy, Cube.001, along the x-axis so that it is next to the original cube with a small space between them.
Rigid Body Joint constraint
Hinge parameters
Hinge in action
By default, all six degrees of freedom in the Generic joint are unconstrained, which means that when you first set the joint, it has no effect at all. If you took the next logical step in the preceding example and experimented with switching the joint type to Generic 6 DoF, you may have gotten a bit of a surprise when Cube.001 just dropped into oblivion with no apparent connection to Cube at all. To constrain them, click the button corresponding to the degree of freedom you want to constrain, and set minimum and maximum values for its range. If you leave the default values of 0 and 0, the object will be fully constrained in that degree of freedom. For linear values, the units are Blender Units. For rotation values, the possible range is from –5 (representing a 180-degree counterclockwise rotation) to 5 (representing a 180-degree clockwise rotation). For example, in the settings shown in , all the buttons are depressed, so the object would be prevented from moving in any degree of freedom except rotating 36 degrees in either direction around the x-axis.
Generic constraint settings
Animators and game creators spend a lot of time with human figures, and for this reason a complete discussion of physics should touch on how to make it act on the human form. This approach to treating the human body as a purely physical collection of parts connected by joints is referred to as ragdoll physics.
In this section, you’ll see how to use ragdoll physics to control a simple armature. In this way, you can use ragdoll physics to control the movements of mesh characters. If you don’t yet know the basics of working with armatures and using them to deform meshes, you can find out everything you need to know in my book Introducing Character Animation with Blender, 2nd Ed. (Sybex, 2011).
Ragdolls can be simple or complex. Likewise, they can be more or less restricted in their range of motions. A less-restricted ragdoll can more accurately mimic the range of positions of a human, but it is also more likely to get into impossible positions. Setting up a ragdoll is similar in some ways to setting up an armature but with an important difference: An armature is intended to be posed by hand, so if it is more flexible than necessary, this is not usually a problem. A ragdoll is intended to be “posed” only by the forces that act on it; therefore, it must be very carefully constrained so as to avoid getting into unnatural positions. At present, constructing a very sophisticated ragdoll like this in Blender is a painstaking and difficult process, so we’ll work with a very simple ragdoll. When you create your own ragdoll, you can use whatever shapes you like: cylinders, spheres, or other convex polyhedrons. Don’t use objects that are too small, though, because this can cause instability in the simulation. In this example, because I am using mainly the mesh objects to control the movement of empties and an armature, we will use the simplest possible construction of just boxes, most of which are approximately the scale of the default cube.
The objects that compose the ragdoll
Hinge constraint values
Position of the shoulder pivot
Right shoulder pivot
Left elbow
Torso, UArm.L, UArm.R, LArm.L, and LArm.R set as dynamic objects
Ragdoll physics for the arms and torso
Parent Head to Torso.
Hip joint placement
Hips and knees in relation to each other
Midriff connected to Torso with a hinge
For slightly more realistic motion, you can adjust the masses of the various parts of the body to have more accurate relative masses.
It would be nice to be able to use ragdoll physics to control an armature, in order to deform a mesh for animation. In this section, I’ll show you a simple way to do this. The example is a little backward; ordinarily you would begin with a mesh character, create a ragdoll armature to fit the character, and then set up the ragdoll as in the previous section, so that the ragdoll’s shape matches the character. In this case, the ragdoll came first. Nevertheless, the way to control the armature is the same.
The ragdoll takes a fall.
Placing empties at key posing points
Snapping to a face
Add an empty.
Parent the empty to the object.
The armature
IK setup
Ragdoll armature in action
You’ll find the full .blend file for this ragdoll (ragdoll.blend) on the website that accompanies this book.
A current area of robotics research is passive walking. This is the study of the way that walking can be accomplished by means of a repetition of “controlled falls,” where the walker simply follows the forces of physics at certain points in the walk cycle and then exerts itself at key points to adjust its balance and ensure that it is in the right position to take the next step. In fact, this kind of passive walking is an important part of how humans actually walk and a big reason why human walking is so fluid and smooth when compared to the way most current robots walk. Rather than controlling every movement with our muscles, a lot of what we do is to allow the forces of physics to work for us.
Passive walking is closely related to ragdoll behavior, and it is possible to construct ragdoll-like walkers that can carry out passive walking in Blender. Yuta Fuji (Hans), a researcher who studies passive walking, has done just this with his intriguing Bullet/Blender passive-walking robot.
This visualization uses a three-legged robot, as shown in . As you can see in the figure, the robot’s natural joints are represented by Hinge constraints, just as they were in the ragdoll example in the previous section.
The passive-walking robot
The artist uses constraints in a few other interesting ways. The robot’s right leg is made to follow its left leg’s motion by means of two orthogonal Hinge constraints, as shown in . The left leg is also constrained by a Generic constraint with no target, set to be unrestricted on all degrees of freedom except Y rotation, which it constrains fully (0 min, 0 max), as shown in . This ensures that the object can move and rotate freely in any direction except twisting.
Hinge constraints
The robot is designed to walk as in . The walker is extremely sensitive to changes in any aspect of the environment; mass of objects, speed, relative distances, and the slope of the walking surface all need to be set just right, and slight changes in the Bullet library and the Blender game engine may render it unstable. It may also be unstable on operating systems other than Windows. On my Mac Pro using Blender 2.44, the robot stumbles at about the 4 marker.
An untargeted Generic constraint
You can watch the movie of the robot walking as it should online at the following site:
You can find out much more about the Bullet Physics Library at the project’s website at . Documentation for new features and a forum devoted to Bullet can be found there. For general user support, go to the Game Engine forum at .
The walking robot in action