Home > Articles > Programming > Graphic Programming

📄 Contents

  1. Getting Started
  2. Moving Bullet to iOS
  3. Using Bullet in Your iOS Application
Like this article? We recommend

Using Bullet in Your iOS Application

All that remains is to build an application that actually uses Bullet and displays 3D objects. Apple's GLKit framework makes it relatively easy.

Make the view controller class generated by Xcode's Single View Application template into a subclass of GLKViewController instead of UIViewCintroller. The PViewController.h file in the tutorial sample code contains the following lines:

#import <GLKit/GLKit.h>
@interface PViewController : GLKViewController

Next, edit the MainStoryboard.storyboard file generated by Xcode's Single View Application template. Set the class of the generated view to GLKView using Xcode's Identity inspector, shown in Figure 12.

Figure 12 Setting the view's class to GLKView

Add the GLKit and OpenGLES frameworks to the project. The easiest way is to edit the project's Build Phases, as shown in Figure 13. Press the + button in the Link Binary with Libraries section to add frameworks.

Figure 13 GLKit and OpenGLES frameworks added to the project

If you build and run the tutorial project now, you should see a black screen. The next step is to create a physics simulation and draw something more interesting.

The tutorial source code includes a file named PAppDelegate.mm. The .mm extension tells Xcode to compile the file as Objective-C++ code intermixing C++ and Objective-C. The following code declares instance variables to store Bullet physics objects:

#import "PAppDelegate.h"
#include "btBulletDynamicsCommon.h"
#include <map>


typedef std::map<PPhysicsObject *, btCollisionObject*> 
   GModelShapeMap;


@interface PAppDelegate ()
{
   btDefaultCollisionConfiguration *collisionConfiguration;
   btCollisionDispatcher *dispatcher;
   btBroadphaseInterface *overlappingPairCache;
   btSequentialImpulseConstraintSolver *solver;
   btDiscreteDynamicsWorld *dynamicsWorld;
   btAlignedObjectArray<btCollisionShape*> collisionShapes;
   
   GModelShapeMap modelShapeMap;
}

@end

The GModelShapeMap modelShapeMap variable is used to store the relationships between Objective-C objects representing boxes and spheres and the corresponding shapes simulated by Bullet. A C++ map is a standard class similar in function to Cocoa Touch's NSDictionary class.

The physics simulation is initialized in PAppDelegate's -application:didFinishLaunchingWithOptions: method that's part of the Cocoa Touch standard application delegate protocol. The simulation is configured to use Earth's gravitational acceleration of -9.81 meters per second2. Comments explain the steps needed to initialize Bullet. Don't worry if it doesn't make much sense to you. It's boilerplate code.

/////////////////////////////////////////////////////////////////
// Creates needed physics simulation objects and configures
// properties such as the acceleration of gravity that seldom
// if ever change while the application executes.
- (BOOL)application:(UIApplication *)application 
   didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ///collision configuration contains default setup for memory, 
   // collision setup. Advanced users can create their own 
   // configuration.
    collisionConfiguration = new 
      btDefaultCollisionConfiguration();
   
    ///use the default collision dispatcher. For parallel 
   // processing you can use a diffent dispatcher 
   // (see Extras/BulletMultiThreaded)
    dispatcher = new	  
      btCollisionDispatcher(collisionConfiguration);
   
    ///btDbvtBroadphase is a good general purpose broadphase. You 
   // can also try out btAxis3Sweep.
    overlappingPairCache = new btDbvtBroadphase();
   
    ///the default constraint solver. For parallel processing you 
   // can use a different solver (see Extras/BulletMultiThreaded)
    solver = new btSequentialImpulseConstraintSolver;
   
    dynamicsWorld = 
      new btDiscreteDynamicsWorld(
         dispatcher,
         overlappingPairCache,
         solver,
         collisionConfiguration);
   
    dynamicsWorld->setGravity(btVector3(0,-9.81,0));
   
   return YES;
}

PAppDelegate's -applicationWillTerminate: method tears down the simulation built in -application:didFinishLaunchingWithOptions:. It's not necessary to implement -applicationWillTerminate: in the tutorial sample code because when the application terminates, iOS will automatically reclaim the memory and other resources consumed by the physics engine. The code is provided in PAppDelegate.mm as example to follow if you ever need to clean up the physics engine while the application continues to execute.

PAppDelegate provides the following -physicsUpdateWithElapsedTime: method. Call the method periodically to give the physics engine opportunities to recalculate object positions and orientations.

/////////////////////////////////////////////////////////////////
// Turn the crank on the physics simulation to calculate 
// positions and orientations of collision shapes if
// necessary. The simulation performs up to 32 interpolation
// steps depending on the amount of elapsed time, and each step
// represents 1/120 seconds of elapsed time.
- (void)physicsUpdateWithElapsedTime:(NSTimeInterval)seconds;
{
   dynamicsWorld->stepSimulation(seconds, 32, 1/120.0f);
}

That's all it takes to start using Bullet physics for iOS. The simulation doesn't produce any interesting results unless some objects are added and set in motion to collide with each other. It's time to create, register, and draw physics objects.

GLKit provides most of the features needed. The tutorial project includes files named sphere.h and cube.h containing data declarations for 3D shapes. The data consists of vertex positions and "normal" vectors. Each shape is drawn as a list of connected triangles. The normal vectors provide information used to calculate how much simulated light reflects from each triangle.

The PViewController class implements all of the drawing for the tutorial. The drawing code is suboptimal to keep the code simple, and it turns out not to matter at run time. Profiling the tutorial code reveals that less than 20% of the application's execution time is spent drawing. Even if the drawing code is removed entirely, the application only runs 20% faster.

PViewController declares the following properties. The baseEffect property stores an instance of GLKit's GLKBaseEffect class. Modern GPUs are programmable allowing almost unlimited flexibility when rendering 3D graphics. The programs running on the GPU are sometimes called effects. GLKBaseEffect encapsulates the GPU programs needed by simple applications so that you don't need to dive into GPU programming when getting started.

@interface PViewController ()

@property (strong, nonatomic, readwrite)
   GLKBaseEffect *baseEffect;
@property (strong, nonatomic, readwrite) 
   NSMutableArray *boxPhysicsObjects;
@property (strong, nonatomic, readwrite) 
   NSMutableArray *spherePhysicsObjects;
@property (strong, nonatomic, readwrite) 
   NSMutableArray *immovableBoxPhysicsObjects;
   
@end

Other than baseEffect, the other properties all store arrays of Objective-C objects representing spheres and boxes in the simulation. Bullet only recalculates positions for physics objects that have mass. Objects created with zero mass are therefore immovable within the simulation. They don't become displaced when other objects collide or fall in response to gravity. The immovableBoxPhysicsObjects property stores an array of zero mass boxes used to form a floor. Without a few immovable objects in the simulation, all of the other objects would quickly fall out of view as the result of simulated gravity.

Two GLKViewController methods provide the key to drawing with GLKit: -update and -glkView:drawInRect:. The –update method is called periodically in sync with the iOS device display refresh rate. The display always refreshes 60 times per second, but GLKViewController's default behavior is to call –update at 30Hz. In other words, –update is called once for every two display refreshes. GLKViewController can be configured to call –update at other rates, but 30 times per second works well for simulations. Right after calling –update, GLKViewController tells the view it controls to display, and the view calls back to GLKViewController's -glkView:drawInRect:. Therefore, you implement simulation update in –update and implement custom 3D drawing code in -glkView:drawInRect:.

/////////////////////////////////////////////////////////////////
// This method is called automatically at the update rate of the 
// receiver (default 30 Hz). This method is implemented to
// update the physics simulation and remove any simulated objects
// that have fallen out of view.
- (void)update
{
   PAppDelegate *appDelegate = 
      [[UIApplication sharedApplication] delegate];
   
   [appDelegate physicsUpdateWithElapsedTime:
      self.timeSinceLastUpdate];

   // Remove objects that have fallen out of view from the 
   // physics simulation
   [self removeOutOfViewObjects];
}

The following drawing code sets baseEffect properties to match the orientation of the iOS device, specifies perspective, positions a light, and prepares for drawing 3D objects. The aspect ratio is the ratio of a view's width to its height. The aspect ratio may change when an iOS device is rotated from portrait orientation to landscape and back. Perspective defines how much of the 3D scene is visible at once and how objects in the distance appear smaller than objects up close.

In the real world, we only see objects that reflect light into our eyes. We perceive the shape of objects because different amounts of light reflect for different parts of the objects. Setting the baseEffect's light position controls how OpenGL calculates the amount of simulated light reflected off each part of a virtual 3D object. Calling [self.baseEffect prepareToDraw] tells the base effect to prepare a suitable GPU program for execution.

/////////////////////////////////////////////////////////////////
// GLKView delegate method: Called by the view controller's view
// whenever Cocoa Touch asks the view controller's view to
// draw itself. (In this case, render into a frame buffer that
// shares memory with a Core Animation Layer)
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
   // Calculate the aspect ratio for the scene and setup a 
   // perspective projection
   const GLfloat  aspectRatio = 
   (GLfloat)view.drawableWidth / (GLfloat)view.drawableHeight;
   
   // Set the projection to match the aspect ratio
   self.baseEffect.transform.projectionMatrix = 
   GLKMatrix4MakePerspective(
      GLKMathDegreesToRadians(35.0f),// Standard field of view
      aspectRatio,
      0.2f,     // Don't make near plane too close
      200.0f); // Far arbitrarily far enough to contain scene
   
   // Configure a light
   self.baseEffect.light0.position = 
   GLKVector4Make(
      0.6f, 
      1.0f, 
      0.4f,  
      0.0f);// Directional light
      
   [self.baseEffect prepareToDraw];

   // Clear Frame Buffer (erase previous drawing)
   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
   
   [self drawPhysicsSphereObjects];
   [self drawPhysicsBoxObjects];      
}

OpenGL ES is a technology for controlling GPUs. Parts of OpenGL ES execute on the GPU itself, and other parts execute on the CPU. Programs call a library of C functions provided by OpenGL to tell OpenGL what to do. The glClear() function, called in the tutorial's -glkView:drawInRect:, erases previous drawing and discards previously calculated information about which 3D objects are in front of others.

PViewController's –drawPhysicsSphereObjects and –drawPhysicsBoxObjects methods draw spheres and boxes with positions and orientations calculated by the physics engine. Without going into a lot of detail, each of the methods calls OpenGL ES functions to specify where to find vertex data defining triangles. Then the triangles are drawn by calling code similar to the following:

      // Draw triangles using the first three vertices in the 
      // currently bound vertex buffer
      glDrawArrays(GL_TRIANGLES, 
         0,  // Start with first vertex in currently bound buffer
         sphereNumVerts);

OpenGL ES can only draw points, lines segments, and triangles. Complex shapes are composed of many triangles. The shapes in this tutorial are defined in sphere.h and cube.h. The shapes were initially drawn in a free open source 3D modeling application called Blender. Modeling is the term used by artists who create 3D shapes. The created models are exported from Blender in .obj file format and then converted into C header files suitable for direct use with OpenGL. Conversion is performed by an open source Perl language script.

It takes a little more work to setup GLKit. PViewController's -viewDidLoad method shows representative boilerplate code. This article glosses over methods like PViewController's –addRandomPhysicsObject. The code for adding physics objects is straightforward and particular to this tutorial. You'll most likely add different objects with different logic in your physics simulation projects.

Conclusion

The simulation provides remarkably complex and varied interaction between objects. The downloadable code is available in two variants. The Physics zip file (3dphyslibios_physics.zip) contains a Physics folder with an Xcode project. If you have built the Bullet demo applications for Mac OS X, you can copy the Physics folder into your bullet-2.80-rev2531 folder, double-click the Physics.xcodeproj file and press Run. A separate larger PhysicsPlusBullet zip file (3dphyslibios_physicsplusbullet.zip) contains the tutorial example and the needed Bullet source code combined. As always with open source, it's better to get the source code directly from the maintainers instead of grabbing a snapshot preserved in a tutorial's .zip file. Nevertheless, if you're impatient, the PhysicsPlusBullet zip file will get you up and running quickly.

This article provided a whirlwind tour of two large and powerful frameworks, Bullet and GLKit. It's not difficult to combine the two technologies in iOS applications. Like many open source libraries, Bullet is relatively easy to compile for iOS in spite of quirks related to the tools and coding style used by the library's authors. GLKit enables development of interesting and visually complex 3D applications with very little code. The tutorial implements all of its drawing in about 200 lines of code including comments and blank lines.

If you are interested in a more thorough introduction to 3D graphics concepts and GLKit, my new book, Learning OpenGL ES for iOS: A Hands-on Guide to Modern 3D Graphics Programming, is complete and available now as a Rough Cut electronic edition. Look for the title at your favorite bookstore in the fall. Free sample code from the book is available.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020