2 Bullet Continuous Collision Detection and Physics Library
3 Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
5 This software is provided 'as-is', without any express or implied warranty.
6 In no event will the authors be held liable for any damages arising from the use of this software.
7 Permission is granted to anyone to use this software for any purpose,
8 including commercial applications, and to alter it and redistribute it freely,
9 subject to the following restrictions:
11 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
12 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
13 3. This notice may not be removed or altered from any source distribution.
16 #include "btBulletDynamicsCommon.h"
17 #include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
18 #include "BulletCollision/CollisionDispatch/btGhostObject.h"
20 #include "GLDebugDrawer.h"
21 #include <stdio.h> //printf debugging
23 #include "GL_ShapeDrawer.h"
25 #include "GlutStuff.h"
26 #include "CharacterDemo.h"
27 #ifdef DYNAMIC_CHARACTER_CONTROLLER
28 #include "DynamicCharacterController.h"
30 #include "BulletDynamics/Character/btKinematicCharacterController.h"
33 const int maxProxies = 32766;
34 const int maxOverlap = 65535;
36 static int gForward = 0;
37 static int gBackward = 0;
39 static int gRight = 0;
45 CharacterDemo::CharacterDemo()
47 m_indexVertexArrays(0),
50 m_minCameraDistance(3.f),
51 m_maxCameraDistance(10.f)
54 m_cameraPosition = btVector3(30,30,30);
58 void CharacterDemo::initPhysics()
60 btCollisionShape* groundShape = new btBoxShape(btVector3(50,3,50));
61 m_collisionShapes.push_back(groundShape);
62 m_collisionConfiguration = new btDefaultCollisionConfiguration();
63 m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
64 btVector3 worldMin(-1000,-1000,-1000);
65 btVector3 worldMax(1000,1000,1000);
66 btAxisSweep3* sweepBP = new btAxisSweep3(worldMin,worldMax);
67 m_overlappingPairCache = sweepBP;
69 m_constraintSolver = new btSequentialImpulseConstraintSolver();
70 m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_overlappingPairCache,m_constraintSolver,m_collisionConfiguration);
71 m_dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration=0.0001f;
73 #ifdef DYNAMIC_CHARACTER_CONTROLLER
74 m_character = new DynamicCharacterController ();
77 btTransform startTransform;
78 startTransform.setIdentity ();
79 //startTransform.setOrigin (btVector3(0.0, 4.0, 0.0));
80 startTransform.setOrigin (btVector3(10.210098,-1.6433364,16.453260));
83 m_ghostObject = new btPairCachingGhostObject();
84 m_ghostObject->setWorldTransform(startTransform);
85 sweepBP->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
86 btScalar characterHeight=1.75;
87 btScalar characterWidth =1.75;
88 btConvexShape* capsule = new btCapsuleShape(characterWidth,characterHeight);
89 m_ghostObject->setCollisionShape (capsule);
90 m_ghostObject->setCollisionFlags (btCollisionObject::CF_CHARACTER_OBJECT);
92 btScalar stepHeight = btScalar(0.35);
93 m_character = new btKinematicCharacterController (m_ghostObject,capsule,stepHeight);
98 /// Create some basic environment from a Quake level
100 //m_dynamicsWorld->setGravity(btVector3(0,0,0));
104 const char* bspfilename = "BspDemo.bsp";
105 void* memoryBuffer = 0;
107 FILE* file = fopen(bspfilename,"r");
110 //cmake generated visual studio projects need 4 levels back
111 bspfilename = "../../../../BspDemo.bsp";
112 file = fopen(bspfilename,"r");
116 //visual studio leaves the current working directory in the projectfiles folder
117 bspfilename = "../../BspDemo.bsp";
118 file = fopen(bspfilename,"r");
122 //visual studio leaves the current working directory in the projectfiles folder
123 bspfilename = "BspDemo.bsp";
124 file = fopen(bspfilename,"r");
131 if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET)) { /* File operations denied? ok, just close and return failure */
132 printf("Error: cannot get filesize from %s\n", bspfilename);
135 //how to detect file size?
136 memoryBuffer = malloc(size+1);
137 fread(memoryBuffer,1,size,file);
138 bspLoader.loadBSPFile( memoryBuffer);
140 BspToBulletConverter bsp2bullet(this);
141 float bspScaling = 0.1f;
142 bsp2bullet.convertBsp(bspLoader,bspScaling);
148 ///only collide with static for now (no interaction with dynamic objects)
149 m_dynamicsWorld->addCollisionObject(m_ghostObject,btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter|btBroadphaseProxy::DefaultFilter);
151 m_dynamicsWorld->addAction(m_character);
158 setCameraDistance(56.f);
163 //to be implemented by the demo
164 void CharacterDemo::renderme()
168 DemoApplication::renderme();
173 void CharacterDemo::debugDrawContacts()
175 // printf("numPairs = %d\n",m_customPairCallback->getOverlappingPairArray().size());
177 btManifoldArray manifoldArray;
178 btBroadphasePairArray& pairArray = m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray();
179 int numPairs = pairArray.size();
181 for (int i=0;i<numPairs;i++)
183 manifoldArray.clear();
185 const btBroadphasePair& pair = pairArray[i];
187 btBroadphasePair* collisionPair = m_overlappingPairCache->getOverlappingPairCache()->findPair(pair.m_pProxy0,pair.m_pProxy1);
191 if (collisionPair->m_algorithm)
192 collisionPair->m_algorithm->getAllContactManifolds(manifoldArray);
194 for (int j=0;j<manifoldArray.size();j++)
196 btPersistentManifold* manifold = manifoldArray[j];
197 for (int p=0;p<manifold->getNumContacts();p++)
199 const btManifoldPoint&pt = manifold->getContactPoint(p);
201 btVector3 color(255,255,255);
202 m_dynamicsWorld->getDebugDrawer()->drawContactPoint(pt.getPositionWorldOnB(),pt.m_normalWorldOnB,pt.getDistance(),pt.getLifeTime(),color);
210 void CharacterDemo::clientMoveAndDisplay()
213 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
215 float dt = getDeltaTimeMicroseconds() * 0.000001f;
217 /* Character stuff &*/
228 //during idle mode, just run 1 simulation step maximum
229 int maxSimSubSteps = m_idle ? 1 : 2;
233 ///set walkDirection for our character
235 xform = m_ghostObject->getWorldTransform ();
237 btVector3 forwardDir = xform.getBasis()[2];
238 // printf("forwardDir=%f,%f,%f\n",forwardDir[0],forwardDir[1],forwardDir[2]);
239 btVector3 upDir = xform.getBasis()[1];
240 btVector3 strafeDir = xform.getBasis()[0];
241 forwardDir.normalize ();
243 strafeDir.normalize ();
245 btVector3 walkDirection = btVector3(0.0, 0.0, 0.0);
246 btScalar walkVelocity = btScalar(1.1) * 4.0; // 4 km/h -> 1.1 m/s
247 btScalar walkSpeed = walkVelocity * dt;
252 btMatrix3x3 orn = m_ghostObject->getWorldTransform().getBasis();
253 orn *= btMatrix3x3(btQuaternion(btVector3(0,1,0),0.01));
254 m_ghostObject->getWorldTransform ().setBasis(orn);
259 btMatrix3x3 orn = m_ghostObject->getWorldTransform().getBasis();
260 orn *= btMatrix3x3(btQuaternion(btVector3(0,1,0),-0.01));
261 m_ghostObject->getWorldTransform ().setBasis(orn);
265 walkDirection += forwardDir;
268 walkDirection -= forwardDir;
271 m_character->setWalkDirection(walkDirection*walkSpeed);
274 int numSimSteps = m_dynamicsWorld->stepSimulation(dt,maxSimSubSteps);
276 //optional but useful: debug drawing
278 m_dynamicsWorld->debugDrawWorld();
280 //#define VERBOSE_FEEDBACK
281 #ifdef VERBOSE_FEEDBACK
283 printf("Interpolated transforms\n");
286 if (numSimSteps > maxSimSubSteps)
288 //detect dropping frames
289 printf("Dropped (%i) simulation steps out of %i\n",numSimSteps - maxSimSubSteps,numSimSteps);
292 printf("Simulated (%i) steps\n",numSimSteps);
295 #endif //VERBOSE_FEEDBACK
306 btProfiler::beginBlock("render");
307 #endif //USE_QUICKPROF
313 btProfiler::endBlock("render");
324 void CharacterDemo::displayCallback(void)
326 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
330 //optional but useful: debug drawing
332 m_dynamicsWorld->debugDrawWorld();
340 void CharacterDemo::clientResetScene()
342 m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(m_ghostObject->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher());
344 m_character->reset ();
346 m_character->warp (btVector3(10.210001,-2.0306311,16.576973));
350 void CharacterDemo::specialKeyboardUp(int key, int x, int y)
375 DemoApplication::specialKeyboardUp(key,x,y);
381 void CharacterDemo::specialKeyboard(int key, int x, int y)
384 // printf("key = %i x=%i y=%i\n",key,x,y);
410 if (m_character && m_character->canJump())
415 DemoApplication::specialKeyboard(key,x,y);
419 // glutPostRedisplay();
424 void CharacterDemo::updateCamera()
427 //#define DISABLE_CAMERA 1
428 #ifdef DISABLE_CAMERA
429 DemoApplication::updateCamera();
431 #endif //DISABLE_CAMERA
433 glMatrixMode(GL_PROJECTION);
436 btTransform characterWorldTrans;
438 //look at the vehicle
439 characterWorldTrans = m_ghostObject->getWorldTransform();
440 btVector3 up = characterWorldTrans.getBasis()[1];
441 btVector3 backward = -characterWorldTrans.getBasis()[2];
443 backward.normalize ();
445 m_cameraTargetPosition = characterWorldTrans.getOrigin();
446 m_cameraPosition = m_cameraTargetPosition + up * 10.0 + backward * 12.0;
448 //use the convex sweep test to find a safe position for the camera (not blocked by static geometry)
449 btSphereShape cameraSphere(0.2f);
450 btTransform cameraFrom,cameraTo;
451 cameraFrom.setIdentity();
452 cameraFrom.setOrigin(characterWorldTrans.getOrigin());
453 cameraTo.setIdentity();
454 cameraTo.setOrigin(m_cameraPosition);
456 btCollisionWorld::ClosestConvexResultCallback cb( characterWorldTrans.getOrigin(), cameraTo.getOrigin() );
457 cb.m_collisionFilterMask = btBroadphaseProxy::StaticFilter;
459 m_dynamicsWorld->convexSweepTest(&cameraSphere,cameraFrom,cameraTo,cb);
463 btScalar minFraction = cb.m_closestHitFraction;//btMax(btScalar(0.3),cb.m_closestHitFraction);
464 m_cameraPosition.setInterpolate3(cameraFrom.getOrigin(),cameraTo.getOrigin(),minFraction);
470 //update OpenGL camera settings
471 glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10000.0);
473 glMatrixMode(GL_MODELVIEW);
476 gluLookAt(m_cameraPosition[0],m_cameraPosition[1],m_cameraPosition[2],
477 m_cameraTargetPosition[0],m_cameraTargetPosition[1], m_cameraTargetPosition[2],
478 m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ());
485 CharacterDemo::~CharacterDemo()
487 //cleanup in the reverse order of creation/initialization
490 m_dynamicsWorld->removeCollisionObject(m_ghostObject);
492 //remove the rigidbodies from the dynamics world and delete them
494 for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
496 btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
497 btRigidBody* body = btRigidBody::upcast(obj);
498 if (body && body->getMotionState())
500 delete body->getMotionState();
502 m_dynamicsWorld->removeCollisionObject( obj );
506 //delete collision shapes
507 for (int j=0;j<m_collisionShapes.size();j++)
509 btCollisionShape* shape = m_collisionShapes[j];
513 delete m_indexVertexArrays;
516 //delete dynamics world
517 delete m_dynamicsWorld;
520 delete m_constraintSolver;
523 delete m_overlappingPairCache;
528 delete m_collisionConfiguration;