Chapter 8
Bullet Physics and the Blender Game Engine
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
- Use the appropriate collision bounds for what you need
- Experiment with cutting-edge physics features
- Take ragdoll physics to the next level with Bullet integration
Physics in the BGE
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.
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.
Getting Started with the Blender Game Engine
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:
1. Add a plane and scale up as shown in .
2. Translate the plane downward along the z-axis, as shown in .
3. Enter Blender Game render mode, as shown in . This is necessary to access the appropriate physics settings in the Physics properties area and other game-related settings.
4. With the cube selected, enter the Physics properties area in the Properties window. This is the same area you worked with in the previous two chapters. However, now that you are in Blender Game render mode, the options are different. Choose Rigid Body from the Physics Type drop-down menu, as shown in . Set the parameters of that panel as shown in . Select Rigid Body, and select Box from the Bounds drop-down menu. You have now activated the cube as a physical object in BGE.
5. Press the P key to run the game engine. You should see the cube fall and bounce against the plane, following a trajectory similar to what’s shown in . The angle you view this from will depend on the angle you’re viewing the scene from when you press P. After the cube has come to rest, press Esc to halt the game engine.
6. You can now begin setting up some basic game logic. Enter the Game Logic properties area by selecting Logic Editor from the drop-down menu shown in . Game logic is the main way to define what events or actions lead to others inside the game environment. Interactive controls are set up here. To set up the game logic, begin by adding a sensor. Select Keyboard from the Add Sensor menu, as shown in .
7. The game action you’re setting up will be triggered by pressing the spacebar. To determine this, click the field to the right of the Key label shown in . When prompted to press a key, press the spacebar.
8. A sensor registers the event that will trigger an action. An actuator defines the resultant action. In order to connect these two things, you need to create a controller. Do this by clicking Add Controller under the Controllers (middle) column. Link the sensor to an And controller by pressing the LMB and dragging the mouse between the two logic connectors, as indicated in .
9. Add a Motion actuator, and connect the controller and the actuator in the same way you connected the sensor and the controller (see ). Set the value for the middle column of the Loc row to 0.10.
10. In the 3D viewport, press P again to enter game play mode. This time, try pressing the spacebar while in game play mode. You should now have some control over the movement of the cube. Giving the spacebar a good press will send the cube flying off the plane as in . Press Esc to get out of this mode.
11. You can minimize and maximize the view of logic blocks by clicking the triangle in the upper-right corner of the logic block. In , the blocks you just created are minimized, and two new sensors, two new controllers, and two new actuators have been added. The sensors are for the right-arrow and left-arrow keys, and the actuators represent right and left rotation around the local z-axis, with –0.10 and 0.10 values, respectively, in the third column of the Rot rows. Set up these logic blocks as they are shown in .
12. Add an Icosphere next to the cube, as shown in . Using the Logic buttons, set the sphere as an actor with the same parameters as you set for the cube, except with Sphere selected under Bounds, as shown in .
13. Press P again. Notice how the sphere and the cube interact. You can now drive the cube around by rotating right and left with the arrow keys and moving forward with the spacebar. Try pushing the sphere off the plane as in . Press Esc to get out of this. Experiment with adding more objects with and without Actor enabled and playing around with the angle and shape of the plane.
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.
Using Actions in BGE
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:
1. Start a fresh session of Blender and key the location and rotation of the default cube at frame 1.
2. Advance to frame 31 (click the Up button three times), move the cube up along the z-axis, and rotate it slightly to the left. Key this location and rotation as shown in . Note that the figure shows the keyframe view in the F-Curve Editor, the Action Editor, and the 3D window.
3. In the Logic buttons area, with the cube selected, set up a sensor, controller, and Ipo actuator as in . In the setup, I have the sensor selected as Always, with the left pulse button activated. This sends a pulse message repeatedly from the sensor. The Action actuator type is Play. The start and end frames of the Ipo to be played, in the Start Fram and End Fram fields, are 1 and 30. When you press P, the cube will go through the motion of the action from frame 1 to 30 repeatedly. If you use a different sensor type, such as a keyboard action sensor, the action will be triggered when you press a key. Also, if you change the start and end frames of the Action actuator, a different (potentially longer or shorter) section of the action will be played. Other Action actuator types can also be selected besides Play. (See if you can guess what the Ping Pong and Flipper types do.)
4. Experiment with combining this setup with the setup from the previous section. Try to set up a flipper-style controller to swing at a falling cube, knocking it into space before it hits the plane. Note how the cube interacts with Rigid Body objects such as the sphere from the previous section’s example.
Rigid Body Simulation and F-Curves
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.
Baking Game F-Curves
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.
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.
After you’ve selected Record Animation, a check mark will appear beside the option, and it will remain active until you deselect it. This means that every time you press P to enter game play mode, the game physics Ipos will be overwritten, so be careful. If you want to run a simulation and record it to a different action than a previous simulation, select the object, and in the Action Editor window click the X beside the drop-down menu where the action you want to save is shown. This disconnects the action from the object, so that a new game physics action object can be written without overwriting what you already have. Remember to give the unused action a fake user by clicking the F to the right of the action’s name, if you want to save the action for later use! In a design change between versions 2.62 and 2.63, actions are no longer given fake users by default, resulting in them being deleted from the blend file whenever the file is closed.
Frame Rate and Simulation Speed
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 .
Recording Physics and Animation
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:
1. Set up a scene as shown in , with the default cube in its original position. Add the following objects at the original cursor location, and move them along the z-axis while holding down the Ctrl key:
- A second cube located 6 Blender Units (BUs) under the first on the z-axis
- A floor plane scaled up to about 14 times its original size and located 8 BUs beneath the first cube on the z-axis
- An Icosphere located 3 BUs above the cube
2. Add an armature at the original cube’s location, as in . In Object mode, translate the Armature object 3 BUs down the z-axis, as shown in . In Edit mode, translate the tip of the armature downward to the middle of the second cube, as shown in .
3. Bone-parent the cube to the bone. To do this, select the armature in Object mode and change to Pose mode. Select the cube (you will return to Object mode automatically). Hold down the Shift key and select the armature so that both the Cube object and the armature are selected in Pose mode. Press Ctrl+P and select Bone.
4. Key the motion of the topmost cube and the plane. The topmost cube will rotate counterclockwise. Key the rotation at frame 1, and then go to frame 11, rotate the cube to an angle of –45 degrees around the y-axis, and key the rotation at that frame. In the Graph Editor, choose Channel > Extrapolation Mode > Linear Extrapolation for the Ipo curve. For the plane, key its rotation at frame 61, and then advance to frame 81, rotate the plane around the y-axis 25 degrees, and key the rotation. Leave the curve’s Extend mode at Constant. In the Logic window, give this cube the Always-And-Action logic setup described earlier, so its animation will play in the game engine.
5. Select the Icosphere. Go into the Physics properties area and make the sphere an actor with Rigid Body selected, as shown in . Under Bounds, select Sphere. Next, select each of the Cube objects in the 3D viewport, go into the Physics buttons, and activate Collision Bounds set to Box. You do not need to make the Cube objects actors. I also added a level 2 Subsurf modifier to the sphere and chose Set Smooth. This is not necessary, but it will make your scene look a bit nicer.
6. Choose Record Animation from the Game options and press P to run the game. Press Esc when the simulation has run its course. After this finishes, you can press Alt+A to run the animation. You’ll see that it looks something like .
7. As you can see, the sphere comes to rest against the second cube at about frame 131. Knowing this, it is possible to key the motion of the armature so that the second cube will “kick” the sphere at exactly the right moment. To do that, key the beginning and ending of the kicking movement about 20 frames before and after the point where the cube should impact the sphere, around frames 111 and 151, as shown in . As you did with the starting cube, set up the armature’s logic to play the animation in the game engine.
8. Run the game again, then run the animation with Alt+A again. The first part of the simulation will be the same, but instead of coming to rest, the sphere will be kicked off the plane as in . If your sphere’s in the wrong place because of the animation being baked, so it starts wrong when you hit P, go to frame 1, clear its transforms, and move it above the first cube again before hitting P.
Actor Parameters, Boundaries, and Hull Types
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:
Actor Actor enables the rest of the buttons so that physics parameters can be set for an object. If this is not selected, the object will be evaluated only as an obstacle. You can still set the collision bounds for a nonactor.
Ghost Ghost enables in-game objects to not have physical interactions with others, so that they can be passed through like a ghost. Because ordinary animation does not have physics calculated automatically, this option is not usually needed in nongame simulations.
Dynamic Dynamic enables the object to be moved by physical forces. Only objects with this option selected will have Ipos generated for them during a simulation.
Rigid Body Rigid Body enables spring-based collision behavior and rolling. This is a necessary option for convincing physical simulation of multiobject interaction.
No Sleeping No Sleeping disables BGE’s default behavior of turning off physics on objects that have not been moved or touched for some time. If you find that an object is becoming unresponsive over the course of a long simulation, select this option. Don’t select it if it is not necessary.
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.
Collision Boundary Types
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:
Box Box calculates the collision boundary as a cube-shaped box. If your object is a cube shape, this is the fastest and most accurate option.
Sphere Sphere calculates the collision boundary as a sphere. If your object is a sphere, this is the fastest and most accurate option.
Cylinder Cylinder calculates the collision boundary as a cylinder. If your object is a cylinder, use this.
Cone Cone calculates the collision boundary as a cone. If your object is a cone, use this.
Convex Hull Convex Hull calculates a “convex hull” around the shape of the object, yielding an accurate collision boundary for many complex shapes. There are two important qualities to note about the Convex Hull. The first is that it can represent only convex shapes; concavities, such as the inside of a cup or a bell, are not accurately simulated. The second point is that it must be a low poly mesh. Meshes of more than about 100 vertices should not be used as Convex Hulls. Ideally, Convex Hull meshes should be between 4 and 30 vertices.
Triangle Mesh Triangle Meshes simulate highly accurate, high-poly shapes, including concavities. There are also two notable qualities of Triangle Meshes. The first is that they can be used only for static (nonmoving) objects. Such objects cannot move on their own; however, a static object can move as the child of a dynamic object. Because they are static, Triangle Mesh bounded objects will not receive Ipos from the physics simulation. The second notable quality is that two static Triangle Meshes will not collide with each other. Rather, Triangle Meshes will collide only with dynamic objects.
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.
Example: Glass and Ball
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 .
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.
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.
1. To create the special collision meshes, select the vertices of the cup shown in . Duplicate these vertices by pressing Shift+D, and then press P and choose Selected to create a new object with these vertices. You can see the new object in Edit mode in . Note the four vertices around the lip of the cup.
2. Eventually, this new collision mesh will use the Convex Hull collision bounds. (Another quality of Convex Hull is that only vertices that are part of faces contribute to the collision boundaries.) So to make this collision mesh work, it is necessary to fill in some triangular faces between the vertices, as shown in . Do this by pressing the F key while in Edit mode. Turn off subsurfing for this object. You can also delete the extra edges, because they don’t do anything.
3. Because the model is subsurfaced, making its visible outline smaller than the actual mesh, the collision mesh should be reduced in size slightly. Reduce it along the x- and y-axes (see ) by pressing the S key followed by Shift+Z. Then reduce it slightly less along the z-axis (see ) by pressing S followed by Z.
4. Now, separate each of the four corner segments of the mesh, one by one, by selecting their vertices, pressing P, and choosing Selection (see ). You should wind up with four objects. Name these objects hull1, hull2, hull3, and hull4. It doesn’t matter which is which.
5. The object called hull1 is going to be the parent object for the compound Rigid Body object. In order for that to happen, each of the other objects (the other three hull objects and the glass mesh) all need to be parented to hull1. Furthermore, they need to be parented in a slightly special way. Parent each of the objects one by one to hull1 by selecting the child-to-be object, selecting hull1, pressing Ctrl+P, and selecting Set Parent To Object (see ).
6. Immediately after parenting each object, press Alt+P and select Clear Parent Inverse (see ). This step is easy to overlook, but it’s necessary to make this setup work properly. Do this for each hull object and for the glass mesh.
7. After you have parented all the objects, set their boundary types. First, set hull1 as a Dynamic Rigid Body actor with boundary type Convex Hull and with Compound enabled (see ). Set hull2, hull3, and hull4 to have Convex Hull bounds. Finally, set the glass object to be a Static Triangle Mesh.
8. After you’ve set these values, set up your ball and glass where you want them at the beginning of the simulation. Use hull1 to move the glass object around. You can preview the simulation in the game engine quickly by pressing P and record the animation in the ordinary way.
9. Because you won’t be rendering the Convex Hull collision meshes, either place them on an inactive layer or set them to not be renderable in the Outliner window, as shown in .
If some of your objects seem to go crazy after you record the animation, you may have inadvertently left a shared action between the parent object and one or more of the children objects. Make sure that this is not the case. If there are shared actions, disconnect them from the child objects by clicking X next to the action name in the Action drop-down menu.
General Tips on Working with Bullet
There are several further points to keep in mind when working with Bullet:
- Avoid scaling rigid bodies. If you need to scale an object, disable the rigid body, scale the object, and apply the scale and rotation by pressing Ctrl+A, or scale from Edit mode.
- Avoid very small (<0.2 Blender Units in any direction) or very large rigid bodies.
- Avoid large mass ratios. Keep the ratio of masses between interacting rigid bodies less than 1:100.
- Avoid degenerate triangles. Degenerate triangles are extremely long, thin sliver-like triangles. Bullet will not handle these well.
- Make sure the center of the object is in the middle of the mesh.
- Don’t make child objects in a Compound object dynamic.
Using Physics Visualization
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.
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.
Joints, Ragdolls, and Robots
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.
Using Rigid Body Joint Constraints
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.
1. With the new cube selected, select the Rigid Body Joint constraint from the Add Constraint drop-down menu, as shown in .
2. The options for the type of joint are Ball, Hinge, and Generic. Ball and Hinge are ball-and-socket joints and hinges (respectively) along the lines of the earlier diagrams. The Generic joint option enables you to set numerical restrictions on six degrees of freedom, three axes of rotation, and three axes of translation. This enables you to not only represent slider joints but also to lock or restrict movement to a specified range for each degree of freedom. For this example, select Hinge.
3. Set the Hinge parameters as shown in . The Target field is for the object that the hinge attaches to, in this case the first cube. Display Pivot makes the constraint’s pivot point visible in the 3D viewport. Pivot X, Pivot Y, and Pivot Z locate the pivot in space with relation to the object’s center (measured in Blender Units). The Axis X, Axis Y, and Axis Z rotate the constraint. The Hinge constraint rotates around its own x-axis; therefore, to line the hinge up along the bottom edges of the cube, enter a Pivot X value of –1, a Pivot Z value of –1, and an Axis Z value of 90.
4. In the Logic buttons, set Cube.001 to be a Dynamic Rigid Body actor. Leave Cube as it is. Generate a simulation action by running the game engine with Record Animation. When you play back the animation, it should look something like .
As an experiment, try switching the joint type to Ball and baking the Ipos again to see how the two joints behave differently.
Using Generic 6 DoF Joints
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.
Setting Up a Ragdoll Armature
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.
1. Compose a ragdoll of 11 separate Cube objects, scaled and positioned as shown in . Rename these objects Head, Torso, Midriff, UArm.L, UArm.R, LArm.L, LArm.R, ULeg.L, ULeg.R, LLeg.L, and LLeg.R. When you have the objects scaled and placed as you want them, press Ctrl+A on each object to apply scale and rotation.
2. The shoulders, elbows, and knees of this ragdoll should now be joined by Hinge constraints. The constraints themselves have no built-in restrictions, but by placing the hinges correctly, it is possible to make the meshes restrict the way the joints bend. Begin with the left upper arm, object UArm.L. Add a constraint of type Hinge with a Target value of Torso. Set the values as shown in so that the pivot is visible and positioned as in .
The only way to adjust the positioning of the pivots is through these numerical values. If you need to use slightly different values to get your pivot positioned correctly, that’s no problem.
3. Set the right shoulder pivot up as a mirror image of the left shoulder by following the same steps and setting the values as shown in .
4. Create an elbow joint by adding a Hinge constraint on LArm.L targeted to UArm.L, as shown in . Do the same on the right side.
5. To see the constraints in action, go to the Logic buttons and set Torso, UArm.L, UArm.R, LArm.L, and LArm.R as actors. Make them Dynamic Rigid Body objects and set their Bounds to Box. You can tell which objects are enabled as actors in the 3D viewport by whether their bounds radius is visible, as shown in .
6. Make sure that Record Animation is not selected, and press P to take a look at the ragdoll physics so far. You should see the arms and torso dangle freely, as in . They do not fall down, because they are being supported by nondynamic objects below the torso.
7. Now set up the rest of the ragdoll. In this example, the head will not move freely—it will be fixed to Torso by parenting. To do this, parent Head to Torso as shown in . Be sure to select Compound for the Torso Bounds.
8. Place the hinges at the hips flush with the front faces of the legs, so that the hinges bend forward, as shown in .
9. Place the knee constraints flush with the back faces of the legs, as shown in , so that the knees bend in the opposite direction.
Note that all of these constraints are hinges. In real life, the human hip is a restricted ball-and-socket joint, but I’m opting for simplicity in this example.
10. Add a Hinge constraint from Midriff to Torso, as shown in . This will enable the body to bend slightly at the middle. Again, the movement will be much more restricted than in a real human body, but this will be plenty for now.
11. Finally, in the Physics Properties area, set the rest of the objects up as Dynamic Rigid Body actors. If you press P now, your ragdoll should fall straight down into oblivion. If it does not, double-check to make sure that all the objects are set as Dynamic Rigid Body objects. If parts of the body separate from others, double-check that the correct constraints are present and that they are targeted to the correct objects. If parts go haywire, make sure there are no parent-child relationships between meshes that are not part of Compound dynamic objects. Only Torso should be a Compound object.
12. Falling straight into oblivion isn’t very interesting. To liven things up, add a plane below the ragdoll and tilt it to one direction so that the ragdoll falls onto the plane and slides off. You can press P with Record Animation selected to see the action and record the animation. After you render the ragdoll with some camera motion, you should see it take a tumble along the lines of .
For slightly more realistic motion, you can adjust the masses of the various parts of the body to have more accurate relative masses.
Controlling an Armature
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.
1. The first thing to do is to add empties to key points, where the tips of the bones will be, as shown in . Parent the “hand” and “foot” empties to the lower arms and legs, respectively, the knee empties to the upper legs, the elbow empties to the upper arms, and the hip empties both to Midriff.
An easy way to position empties is to select the vertices around where the empty should go and snap the cursor to selection by pressing Shift+S (as shown in for positioning the 3D cursor at the end of the left arm), and then add the empty in Object mode () and parent it to the body part that should control it ().
2. Now for the armature. In Object mode, select the Midriff object and snap the cursor to the selection. Add an Armature object and edit it as shown in . Snap the bone tips to the empties you just added.
3. Finally, enter Pose mode and set up IK constraints on each of the bones shown in yellow in . Enter the name of the empty at the bone’s tip as the IK target, and make sure that chain length is set to 1 for each bone.
4. Record the animation in the game engine and run the animation again to see the ragdoll armature in action, as in .
You’ll find the full .blend file for this ragdoll (ragdoll.blend) on the website that accompanies this book.
A Passive-Walking Robot
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 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.
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.
You can watch the movie of the robot walking as it should online at the following site:
Further Resources
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 Bottom Line
Use the appropriate collision bounds for what you need. Bullet enables a variety of different collision bound types, which vary in how quickly they can be calculated for real-time interaction and in how accurate and realistic the collisions are that they can produce.
Master It Create a rigid body simulation consisting of a ball, a plane, and a torus. Make the torus and the ball drop onto the plane such that they both exhibit realistic rigid body behavior and the ball drops into the hole in the torus.
Experiment with cutting-edge physics features. When doing paid work or other mission-critical projects, it’s safest to work with a single official release of Blender from the beginning of the project to the end. However, a lot of times you may find yourself wanting or needing to work with developmental features. This is fine, but it requires some caution. Try to stay abreast of development notes and always keep your work safely backed up. Keeping some backup files “quarantined” by not opening them with development builds will ensure that you never lose an unacceptable amount of work because of development bugs.
That said, for the purposes of learning, there’s no reason not to work with the most bleeding-edge builds available. Learning new things incrementally is much easier than having to relearn Blender from scratch every few years. If you haven’t done so already, you should download a copy of the Bullet integration branch from Graphicall.org and familiarize yourself with its features.
Master It Set up a rigid body simulation with animated parts, along the lines of the one in the second section of this chapter, using the most recent Bullet integration development build for your system from Graphicall.org. Run the simulation without using the game engine.
Take ragdoll physics to the next level with Bullet integration. Bullet integration will be a welcome development for a variety of reasons. One thing that it enables is integration of ragdoll physics with keyframed character animation, making ragdoll simulation much more interesting.
Master It Using a simple ragdoll setup such as the one described in this chapter, create an animation in which a character is struck by a heavy flying object while walking along and then picks himself up off the floor.