RaytestDemo.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 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.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #include "RaytestDemo.h"
  14. ///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
  15. #include "btBulletDynamicsCommon.h"
  16. #include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"
  17. #include "BulletCollision/Gimpact/btGImpactShape.h"
  18. #include <stdio.h> //printf debugging
  19. #include "LinearMath/btAlignedObjectArray.h"
  20. ///RaytestDemo shows how to use the btCollisionWorld::rayTest feature
  21. #include "../CommonInterfaces/CommonRigidBodyBase.h"
  22. class RaytestDemo : public CommonRigidBodyBase
  23. {
  24. public:
  25. RaytestDemo(struct GUIHelperInterface* helper)
  26. :CommonRigidBodyBase(helper)
  27. {
  28. }
  29. virtual ~RaytestDemo()
  30. {
  31. }
  32. virtual void initPhysics();
  33. virtual void exitPhysics();
  34. void castRays();
  35. virtual void stepSimulation(float deltaTime);
  36. virtual void resetCamera()
  37. {
  38. float dist = 18;
  39. float pitch = 129;
  40. float yaw = 30;
  41. float targetPos[3]={-4.6,-4.7,-5.75};
  42. m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]);
  43. }
  44. };
  45. void RaytestDemo::castRays()
  46. {
  47. static float up = 0.f;
  48. static float dir = 1.f;
  49. //add some simple animation
  50. //if (!m_idle)
  51. {
  52. up+=0.01*dir;
  53. if (btFabs(up)>2)
  54. {
  55. dir*=-1.f;
  56. }
  57. btTransform tr = m_dynamicsWorld->getCollisionObjectArray()[1]->getWorldTransform();
  58. static float angle = 0.f;
  59. angle+=0.01f;
  60. tr.setRotation(btQuaternion(btVector3(0,1,0),angle));
  61. m_dynamicsWorld->getCollisionObjectArray()[1]->setWorldTransform(tr);
  62. }
  63. ///step the simulation
  64. if (m_dynamicsWorld)
  65. {
  66. m_dynamicsWorld->updateAabbs();
  67. m_dynamicsWorld->computeOverlappingPairs();
  68. btVector3 red(1,0,0);
  69. btVector3 blue(0,0,1);
  70. ///all hits
  71. {
  72. btVector3 from(-30,1+up,0);
  73. btVector3 to(30,1,0);
  74. m_dynamicsWorld->getDebugDrawer()->drawLine(from,to,btVector4(0,0,0,1));
  75. btCollisionWorld::AllHitsRayResultCallback allResults(from,to);
  76. allResults.m_flags |= btTriangleRaycastCallback::kF_KeepUnflippedNormal;
  77. //kF_UseGjkConvexRaytest flag is now enabled by default, use the faster but more approximate algorithm
  78. //allResults.m_flags |= btTriangleRaycastCallback::kF_UseSubSimplexConvexCastRaytest;
  79. allResults.m_flags |= btTriangleRaycastCallback::kF_UseSubSimplexConvexCastRaytest;
  80. m_dynamicsWorld->rayTest(from,to,allResults);
  81. for (int i=0;i<allResults.m_hitFractions.size();i++)
  82. {
  83. btVector3 p = from.lerp(to,allResults.m_hitFractions[i]);
  84. m_dynamicsWorld->getDebugDrawer()->drawSphere(p,0.1,red);
  85. m_dynamicsWorld->getDebugDrawer()->drawLine(p,p+allResults.m_hitNormalWorld[i],red);
  86. }
  87. }
  88. ///first hit
  89. {
  90. btVector3 from(-30,1.2,0);
  91. btVector3 to(30,1.2,0);
  92. m_dynamicsWorld->getDebugDrawer()->drawLine(from,to,btVector4(0,0,1,1));
  93. btCollisionWorld::ClosestRayResultCallback closestResults(from,to);
  94. closestResults.m_flags |= btTriangleRaycastCallback::kF_FilterBackfaces;
  95. m_dynamicsWorld->rayTest(from,to,closestResults);
  96. if (closestResults.hasHit())
  97. {
  98. btVector3 p = from.lerp(to,closestResults.m_closestHitFraction);
  99. m_dynamicsWorld->getDebugDrawer()->drawSphere(p,0.1,blue);
  100. m_dynamicsWorld->getDebugDrawer()->drawLine(p,p+closestResults.m_hitNormalWorld,blue);
  101. }
  102. }
  103. }
  104. }
  105. void RaytestDemo::stepSimulation(float deltaTime)
  106. {
  107. castRays();
  108. CommonRigidBodyBase::stepSimulation(deltaTime);
  109. }
  110. void RaytestDemo::initPhysics()
  111. {
  112. m_guiHelper->setUpAxis(1);
  113. ///collision configuration contains default setup for memory, collision setup
  114. m_collisionConfiguration = new btDefaultCollisionConfiguration();
  115. //m_collisionConfiguration->setConvexConvexMultipointIterations();
  116. ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
  117. m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
  118. m_broadphase = new btDbvtBroadphase();
  119. ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
  120. btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
  121. m_solver = sol;
  122. m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
  123. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  124. m_dynamicsWorld->setGravity(btVector3(0,-10,0));
  125. ///create a few basic rigid bodies
  126. btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
  127. // btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
  128. m_collisionShapes.push_back(groundShape);
  129. btTransform groundTransform;
  130. groundTransform.setIdentity();
  131. groundTransform.setOrigin(btVector3(0,-50,0));
  132. //We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here:
  133. {
  134. btScalar mass(0.);
  135. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  136. bool isDynamic = (mass != 0.f);
  137. btVector3 localInertia(0,0,0);
  138. if (isDynamic)
  139. groundShape->calculateLocalInertia(mass,localInertia);
  140. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  141. btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
  142. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia);
  143. btRigidBody* body = new btRigidBody(rbInfo);
  144. body->setRollingFriction(1);
  145. body->setFriction(1);
  146. //add the body to the dynamics world
  147. m_dynamicsWorld->addRigidBody(body);
  148. }
  149. {
  150. btVector3 convexPoints[]={ btVector3(-1,-1,-1),btVector3(-1,-1,1),btVector3(-1,1,1),btVector3(-1,1,-1),
  151. btVector3(2,0,0)};
  152. btVector3 quad[] = {
  153. btVector3(0,1,-1),
  154. btVector3(0,1,1),
  155. btVector3(0,-1,1),
  156. btVector3(0,-1,-1)};
  157. btTriangleMesh* mesh = new btTriangleMesh();
  158. mesh->addTriangle(quad[0],quad[1],quad[2],true);
  159. mesh->addTriangle(quad[0],quad[2],quad[3],true);
  160. btBvhTriangleMeshShape* trimesh = new btBvhTriangleMeshShape(mesh,true,true);
  161. //btGImpactMeshShape * trimesh = new btGImpactMeshShape(mesh);
  162. //trimesh->updateBound();
  163. #define NUM_SHAPES 6
  164. btCollisionShape* colShapes[NUM_SHAPES] = {
  165. trimesh,
  166. new btConvexHullShape(&convexPoints[0].getX(),sizeof(convexPoints)/sizeof(btVector3),sizeof(btVector3)),
  167. new btSphereShape(1),
  168. new btCapsuleShape(0.2,1),
  169. new btCylinderShape(btVector3(0.2,1,0.2)),
  170. new btBoxShape(btVector3(1,1,1))
  171. };
  172. for (int i=0;i<NUM_SHAPES;i++)
  173. m_collisionShapes.push_back(colShapes[i]);
  174. for (int i=0;i<6;i++)
  175. {
  176. //create a few dynamic rigidbodies
  177. // Re-using the same collision is better for memory usage and performance
  178. /// Create Dynamic Objects
  179. btTransform startTransform;
  180. startTransform.setIdentity();
  181. startTransform.setOrigin(btVector3((i-3)*5,1,0));
  182. btScalar mass(1.f);
  183. if (!i)
  184. mass=0.f;
  185. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  186. bool isDynamic = (mass != 0.f);
  187. btVector3 localInertia(0,0,0);
  188. btCollisionShape* colShape = colShapes[i%NUM_SHAPES];
  189. if (isDynamic)
  190. colShape->calculateLocalInertia(mass,localInertia);
  191. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,0,colShape,localInertia);
  192. rbInfo.m_startWorldTransform = startTransform;
  193. btRigidBody* body = new btRigidBody(rbInfo);
  194. body->setRollingFriction(0.03);
  195. body->setFriction(1);
  196. body->setAnisotropicFriction(colShape->getAnisotropicRollingFrictionDirection(),btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
  197. m_dynamicsWorld->addRigidBody(body);
  198. }
  199. }
  200. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  201. }
  202. void RaytestDemo::exitPhysics()
  203. {
  204. //cleanup in the reverse order of creation/initialization
  205. //remove the rigidbodies from the dynamics world and delete them
  206. int i;
  207. for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
  208. {
  209. btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
  210. btRigidBody* body = btRigidBody::upcast(obj);
  211. if (body && body->getMotionState())
  212. {
  213. delete body->getMotionState();
  214. }
  215. m_dynamicsWorld->removeCollisionObject( obj );
  216. delete obj;
  217. }
  218. //delete collision shapes
  219. for (int j=0;j<m_collisionShapes.size();j++)
  220. {
  221. btCollisionShape* shape = m_collisionShapes[j];
  222. delete shape;
  223. }
  224. m_collisionShapes.clear();
  225. delete m_dynamicsWorld;
  226. m_dynamicsWorld = 0;
  227. delete m_solver;
  228. m_solver = 0;
  229. delete m_broadphase;
  230. m_broadphase = 0;
  231. delete m_dispatcher;
  232. m_dispatcher = 0;
  233. delete m_collisionConfiguration;
  234. m_collisionConfiguration = 0;
  235. }
  236. class CommonExampleInterface* RaytestCreateFunc(struct CommonExampleOptions& options)
  237. {
  238. return new RaytestDemo(options.m_guiHelper);
  239. }