Skip to content

Archive

Tag: Tutorial

The Bullet Physics Library is an open source (free for private and commercial use) physics engine mainly written by Erwin Coumans. After 8 years of development or more, it is a mature library. Integrations with Ogre, Irrlicht, Unity and other engines are available. It also integrates with content creation software, including Maya and Blender and has been used in a lot of games (wikipedia?)

After messing with the build a little (see my recent posts), we are ready for a friendly introduction.

How simple is simple?

Conceptually, this is how I want to setup a physics simulation:

  1. Create a container (‘physics world’).
  2. Add objects, aka ‘rigid bodies’.
  3. Step the simulation and enjoy the result.

That would be 3 lines of code, right? How about something like…

PhysicalWorld world=new PhysicalWorld();
world.addBody(new Ball());
for(int i=0;i<10;i++)world.step(10); // 10 milliseconds

There are countless assumptions underlying this code. Gravity. Friction. Flying cows. You name it. I’m not saying that a physics engine should provide this level of integration (who would ever need it?); definitely not saying that there shouldn’t be 3 or 4 additional constructors taking in quizzical parameters.

I know this: if a physics engine’s hello world program looked like this, countless school kids would try it out, feel an atavistic surge of adrenaline and dive into the gory details.

You won’t get away without reading the bullet hello world tutorial

Let’s see how Bullet lives up to the leap of faith. I simplified their hello world tutorial for you, but frankly I’m just trying to encourage you to read it. I also highlighted the key steps.

#include <btBulletDynamicsCommon.h>

int main (void){

 // create the 'physical world'
 //
        btBroadphaseInterface* broadphase =
            new btDbvtBroadphase();
        btDefaultCollisionConfiguration* collisionConfiguration =
            new btDefaultCollisionConfiguration();
        btCollisionDispatcher* dispatcher =
            new btCollisionDispatcher(collisionConfiguration);

        btSequentialImpulseConstraintSolver* solver =
            new btSequentialImpulseConstraintSolver;

        btDiscreteDynamicsWorld* dynamicsWorld = 
            new btDiscreteDynamicsWorld(
                  dispatcher,broadphase,solver,collisionConfiguration);
        dynamicsWorld->setGravity(btVector3(0,-10,0));

 // create the ball
 //
        btCollisionShape* shape = new btSphereShape(1);
        btDefaultMotionState* motionState =
                new btDefaultMotionState(
                      btTransform(btQuaternion(0,0,0,1),
                                  btVector3(0,50,0))
                );
        btScalar mass = 1;
        btVector3 inertia(0,0,0);
        shape->calculateLocalInertia(mass,inertia);
        btRigidBody::btRigidBodyConstructionInfo
             bodyDescriptor(mass,motionState,shape,inertia);
        btRigidBody* ball = new btRigidBody(bodyDescriptor);
        dynamicsWorld->addRigidBody(ball);

 // step the simulation (and enjoy the result)
 //
        for (int i=0 ; i<10 ; i++){
          dynamicsWorld->stepSimulation(1/60.0f,10);
        }

 // remove and delete the ball
 //
        dynamicsWorld->removeRigidBody(ball);
        delete ball->getMotionState();
        delete ball;
        delete shape;

 // delete the world
 //
        delete dynamicsWorld;
        delete solver;
        delete collisionConfiguration;
        delete dispatcher;
        delete broadphase;

        return 0;
}

Not self explanatory

To avoid plagiarism and rest my keyboard, I suggest you go and read that tutorial. It explains everything step by step. Aside, the original tutorial includes a ground plane and log output so you can ‘see the ball falling and bouncing’ (that is, read the log and observe that the height of the ball varies).

Seeing is believing. Testing is learning.

After pasting in the original tutorial, we have a choice:

  1. Plug graphic output of sorts and start hacking way
  2. Read on, write sample code and verify our assumptions using tests.

I’m totally against option 1.

  • If you haven’t got a system that produces graphic output yet, trying out everything at once will bring utter confusion.
  • If you do have a system that produces graphic output and attempt integrating right away, you’re burdening yourself with the need to match your transforms and rotations to bullet’s before learning anything physics related, which is somewhat demotivating; or…
  • …you are blissfully ignoring the fact that with screwed up transforms, the physics will appear to go awfully wrong. Then you’ll be asking around, complaining and imagining bugs that aren’t there.

Option 2 consists in getting a test framework up and running and writing innocuous simulations using the hello world tutorial as a starting point. Use console output; assert results; use breakpoints.

You can test without a test framework but you’ll end up with a mess of ‘little tests’ that only run when you ask them to. Lining up tests using a test framework is cleaner, faster and documents our learning process.

Outlook

This article is retrospective. I’m integrating bullet with my game engine and hope to get ‘all basic stuff’ sorted this weekend. Seven rough days in, I can build a ‘physics world’ that matches my game scenes, got the transforms sorted and can mix dynamic and kinematic objects.

In the next articles I will cover the following:

  • collision and contact
  • dynamics and kinematics (aka ‘the motion state’)
  • creating meshes and other objects
  • transforms and rendering.

haXe is a high level object idiom that:

  • Compiles to C++, AS3, AS2 and Neko (‘Haxe native’)
  • Exports to javascript and PHP
  • Compiles and exports to… other stuff.

Have a look at their site! I’m just getting started here.

Setting up

Creating and running a project

  • In FD3 Go to [Project > new], scroll down and select any HaXe target. I chose javascript. and typed trace(hi); and Lib.alert(“Hi”); in Main.hx’s main function (default project template).
  • Press the play button in FD3 and, well, check what happens…

Getting up to Speed

The Haxe website has got docs for all compile/export targets. There is also a very active blog dedicated to Haxe gaming (Going all the way to teaching you how to haXe your iPhone!)

Get Cocoa source code compiling and running on your iSomething in no more than 24 hours. Read this post.

I. Get a Mac, get a life

1) Register to the iPhone Developer program. it’s not free (~$100), but you won’t be able to put your app on the app store or even test on an actual device if you don’t.
Do this first, it may take up to 24 hours to complete. If your country doesn’t have an online apple store, consider getting remote help as offline registration may take up to 4 weeks to complete, including annoyances.

2) Get a Mac. If you don’t have a mac, you can’t do iPhone. Your mac should  be running Leopard 10.5 or higher. Before you head for the corner shop, download the iPhone/iTouch SDK. Avoid using a WiFi connection – download is about 1.2GB.
I got a ‘bigger’ Mac Mini for about $800. That works like a breeze. Rumour has it that the apple dev environment is a memory hog.

3) Install the SDK

4) Dump useless icons from the dock.

5) Download the MoveMe sample application

6) Start the apple dev environment, xcode and open the MoveMe project

7) Follow that tutorial (or just run the example)

II – wotf**k

You will use Objective-C and the Cocoa framework for development.
If you come frome Java, JavaScript, ActionScript, PHP, Python (or
like me, all of the above) you may experience some inconvenience.

The syntax of Objective-C will surprise you – different method calls, different
signatures, never mind using .h files.

There’s a couple of comprehensive tutorials I found useful:

If you haven’t done much programming, Objective-C is probably not the best place to start. On the other hand, stretching yourself a little might be rewarding as there are many things you can do with apple’s wysiwyg interface builder and not too much programming – either way, you’ve been warned.

I wrote a little note about how to send/view debug output in the console.

III – get your app running on your iPhone/iTouch

1) Follow this link and start the development provisioning assistant. Follow the steps… All this probably deserves an explanation but we’ll keep that for later

2) In xcode, set your environment (top left drop down) to iPhone Device 3.x (3.0, 3.1, …, or whatever works) and  hit Build & Run, then one of the following should occur:
- a. the app loads on your iPhone
- b. you get a quizzical exception
- c. you get a message suggesting the phone’s OS is too old.
At this stage, the easiest may be to upgrade the device OS. Obviously
it *should* be possible to build and run on an older target OS, but  for now, quickest and fastest. If you plugged your iPhone/iTouch, iTunes would normally offer to upgrade to the latest OS supported by your device.

That’s it. You’re now an iPhone developper :). Next time I’ll look into the Cocoa Touch MVC (Model View Controller) implementation and suggest ways you can design your application.

Classes to import
javax.swing
--JTextPane
javax.swing.text
--StyledDocument
--DefaultStyleDocument
--Style
--StyleContext
--StyleConstants

Text and style support in Swing is elaborate and complex. The Swing tutorial provides an example for creating editable styled text, but glosses over the details. In this tutorial I explain the basic classes and methods used to style editable text using java and Swing. This tutorial just shows how to create styles and apply them to a text document. If you want to know how to apply text styles interactively, well… just ask me.

1) Creating a styled document and a text pane

You may have used JTextArea before. Unfortunately JTextArea supports only plain text; another approach may consist in using HTML with a JTextPane to style our document, but results when editing an HTML styled document may be ‘surprising’.

The approach explained here uses JTextPane and StyledDocument. The styled document contains the actual text data, linked with logical styles. The JTextPane is used to display and edit our styled document.

StyledDocument doc=new DefaultStyledDocument();
JTextPane text=new JTextPane(doc); 

2) Defining logical styles

Before we apply logical styles, we need to define them. Swing allows defining logical style hierarchies similar to what you can do using OpenOffice or Word. The base style is obtained using a special technique:

Style base = StyleContext.
  getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);

Since Style is an interface, we never create style instances directly. Derived styles are factored indirectly from our StyledDocument instance.

Style emphasis = doc.addStyle(base,"emphasis");
StyledConstants.setItalic(emphasis,true);

Style doesn’t define standard style properties and attributes. To configure a style, we need to use StyledConstants. Fortunately, StyledConstants provides many many plain english methods, including font, font size, italic, bold, associating icons with style, etc…

3) Adding styled text and modifying text styles

We can insert a styled fragment directly in a document, as follows:

int offset=0;
String str="hello world";
Style em=doc.getStyle("emphasis")
doc.insertString(offset,str,em);

Most of the time, however, you’ll want to modify the style of an existing part of the document.

int offset=o;
int length=5;
Style em=doc.getStyle("emphasis");
boolean replace=true;
doc.setCharacterAttributes(offset,length,em,replace);

There’s not really a method to remove styles; instead, invoke setCharacterAttributes as above, passing the default style (in this example, base) as argument.

That’s it. Now we know how to created styled documents using Swing.