You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

470 line
12 KiB

  1. //
  2. // BtPhysTest
  3. //
  4. // Copyright: (c) 2009-2012 Benjamin Huet <huet.benjamin@gmail.com>
  5. // (c) 2012 Sam Hocevar <sam@hocevar.net>
  6. //
  7. #if defined HAVE_CONFIG_H
  8. # include "config.h"
  9. #endif
  10. #if defined _WIN32
  11. # include <direct.h>
  12. #endif
  13. #if defined _XBOX
  14. # define _USE_MATH_DEFINES /* for M_PI */
  15. # include <xtl.h>
  16. # undef near /* Fuck Microsoft */
  17. # undef far /* Fuck Microsoft again */
  18. #elif defined _WIN32
  19. # define _USE_MATH_DEFINES /* for M_PI */
  20. # define WIN32_LEAN_AND_MEAN
  21. # include <windows.h>
  22. # undef near /* Fuck Microsoft */
  23. # undef far /* Fuck Microsoft again */
  24. #else
  25. # include <cmath>
  26. #endif
  27. #if USE_SDL && defined __APPLE__
  28. # include <SDL_main.h>
  29. #endif
  30. #include "core.h"
  31. #include "loldebug.h"
  32. using namespace lol;
  33. #ifndef HAVE_PHYS_USE_BULLET
  34. #define HAVE_PHYS_USE_BULLET
  35. #endif /* HAVE_PHYS_USE_BULLET */
  36. #include "Physics/LolPhysics.h"
  37. #include "Physics/EasyPhysics.h"
  38. #include "PhysicObject.h"
  39. #include "BtPhysTest.h"
  40. using namespace lol::phys;
  41. #define CUBE_HALF_EXTENTS .5f
  42. #define EXTRA_HEIGHT 1.f
  43. int gNumObjects = 64;
  44. BtPhysTest::BtPhysTest(bool editor)
  45. {
  46. /* Create a camera that matches the settings of XNA BtPhysTest */
  47. m_camera = new Camera(vec3(0.f, 600.f, 0.f),
  48. vec3(0.f, 0.f, 0.f),
  49. vec3(0, 1, 0));
  50. m_camera->SetRotation(quat::fromeuler_xyz(0.f, 0.f, 0.f));
  51. m_camera->SetPerspective(45.f, 1280.f, 960.f, .1f, 1000.f);
  52. //m_camera->SetOrtho(1280.f / 6, 960.f / 6, -1000.f, 1000.f);
  53. Ticker::Ref(m_camera);
  54. m_ready = false;
  55. m_simulation = new Simulation();
  56. m_simulation->InitContext();
  57. vec3 NewGravity = vec3(.0f, -10.0f, .0f);
  58. m_simulation->SetGravity(NewGravity);
  59. m_simulation->SetContinuousDetection(true);
  60. float offset = 29.5f;
  61. vec3 pos_offset = vec3(.0f, 30.f, .0f);
  62. for (int i=0; i < 6; i++)
  63. {
  64. vec3 NewPosition = vec3(.0f);
  65. quat NewRotation = quat(1.f);
  66. PhysicsObject* NewPhyobj = new PhysicsObject(m_simulation, NewPosition, NewRotation);
  67. int idx = i/2;
  68. NewPosition = pos_offset;
  69. NewPosition[idx] += offset;
  70. offset *= -1.f;
  71. if (idx != 1)
  72. {
  73. vec3 axis = vec3(.0f);
  74. axis[2 - idx] = 1;
  75. NewRotation = quat::rotate(90.f, axis);
  76. }
  77. NewPhyobj->SetTransform(NewPosition, NewRotation);
  78. Ticker::Ref(NewPhyobj);
  79. m_ground_list << NewPhyobj;
  80. }
  81. for (int x=0; x < 6; x++)
  82. {
  83. for (int y=0; y < 6; y++)
  84. {
  85. for (int z=0; z < 5; z++)
  86. {
  87. PhysicsObject* new_physobj = new PhysicsObject(m_simulation, 1000.f,
  88. vec3(-20.f, 15.f, -20.f) +
  89. vec3(8.f * (float)x, 8.f * (float)y, 8.f * (float)z));
  90. m_physobj_list << new_physobj;
  91. Ticker::Ref(new_physobj);
  92. }
  93. }
  94. }
  95. #if 0
  96. //init Physics
  97. {
  98. m_bt_ccd_mode = USE_CCD;
  99. //collision configuration contains default setup for memory, collision setup
  100. m_bt_collision_config = new btDefaultCollisionConfiguration();
  101. //use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
  102. m_bt_dispatcher = new btCollisionDispatcher(m_bt_collision_config);
  103. m_bt_dispatcher->registerCollisionCreateFunc(BOX_SHAPE_PROXYTYPE,
  104. BOX_SHAPE_PROXYTYPE,
  105. m_bt_collision_config->getCollisionAlgorithmCreateFunc(CONVEX_SHAPE_PROXYTYPE,
  106. CONVEX_SHAPE_PROXYTYPE));
  107. m_bt_broadphase = new btDbvtBroadphase();
  108. ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
  109. m_bt_solver = new btSequentialImpulseConstraintSolver;
  110. m_bt_world = new btDiscreteDynamicsWorld(m_bt_dispatcher, m_bt_broadphase, m_bt_solver, m_bt_collision_config);
  111. //m_bt_world->setDebugDrawer(&sDebugDrawer);
  112. m_bt_world->getSolverInfo().m_splitImpulse = true;
  113. m_bt_world->getSolverInfo().m_numIterations = 20;
  114. m_bt_world->getDispatchInfo().m_useContinuous = (m_bt_ccd_mode == USE_CCD);
  115. m_bt_world->setGravity(btVector3(0,-10,0));
  116. ///create a few basic rigid bodies
  117. btBoxShape* box = new btBoxShape(btVector3(btScalar(110.),btScalar(1.),btScalar(110.)));
  118. btCollisionShape* groundShape = box;
  119. m_bt_collision_shapes << groundShape;
  120. m_ground_mesh.Compile("[sc#ddd afcb220 2 220 -1]");
  121. //m_bt_collision_shapes << new btCylinderShape(btVector3(.5f,.5f,.5f));
  122. btTransform groundTransform;
  123. groundTransform.setIdentity();
  124. //We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here:
  125. {
  126. btScalar mass(0.);
  127. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  128. bool isDynamic = (mass != 0.f);
  129. btVector3 localInertia(0,0,0);
  130. if (isDynamic)
  131. groundShape->calculateLocalInertia(mass,localInertia);
  132. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  133. btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
  134. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia);
  135. btRigidBody* body = new btRigidBody(rbInfo);
  136. //add the body to the dynamics world
  137. m_bt_world->addRigidBody(body);
  138. }
  139. //Adding Shapes
  140. {
  141. //create a few dynamic rigidbodies
  142. // Re-using the same collision is better for memory usage and performance
  143. btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1));
  144. m_rigid_mesh[0].Compile("[sc#add afcb2 2 2 -.1]");
  145. m_rigid_mesh[1].Compile("[sc#dad afcb2 2 2 -.1]");
  146. m_rigid_mesh[2].Compile("[sc#dda afcb2 2 2 -.1]");
  147. m_rigid_mesh[3].Compile("[sc#daa afcb2 2 2 -.1]");
  148. m_rigid_mesh[4].Compile("[sc#ada afcb2 2 2 -.1]");
  149. m_rigid_mesh[5].Compile("[sc#aad afcb2 2 2 -.1]");
  150. m_bt_collision_shapes << colShape;
  151. m_bt_dynamic_shapes << colShape;
  152. /// Create Dynamic Objects
  153. btTransform startTransform;
  154. startTransform.setIdentity();
  155. btScalar mass(1.f);
  156. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  157. bool isDynamic = (mass != 0.f);
  158. btVector3 localInertia(0,0,0);
  159. if (isDynamic)
  160. colShape->calculateLocalInertia(mass,localInertia);
  161. int i;
  162. for (i=0;i<gNumObjects;i++)
  163. {
  164. btCollisionShape* shape = colShape;
  165. btTransform trans;
  166. trans.setIdentity();
  167. //stack them
  168. int colsize = 10;
  169. int row = int(((float)i*CUBE_HALF_EXTENTS*2.0f)/((float)colsize*2.0f*CUBE_HALF_EXTENTS));
  170. int row2 = row;
  171. int col = (i)%(colsize)-colsize/2;
  172. if (col>3)
  173. {
  174. col=11;
  175. row2 |=1;
  176. }
  177. btVector3 pos(((row+col+row2) % 4)*CUBE_HALF_EXTENTS,
  178. 20.0f + row*8*CUBE_HALF_EXTENTS+CUBE_HALF_EXTENTS+EXTRA_HEIGHT,
  179. col*8*CUBE_HALF_EXTENTS + 2 * (row2%2)*CUBE_HALF_EXTENTS);
  180. trans.setOrigin(pos);
  181. float mass = 1.f;
  182. btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE));
  183. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  184. bool isDynamic = (mass != 0.f);
  185. btVector3 localInertia(0,0,0);
  186. if (isDynamic)
  187. shape->calculateLocalInertia(mass,localInertia);
  188. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  189. btDefaultMotionState* myMotionState = new btDefaultMotionState(trans);
  190. btRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia);
  191. btRigidBody* body = new btRigidBody(cInfo);
  192. body->setContactProcessingThreshold(BT_LARGE_FLOAT);
  193. m_bt_world->addRigidBody(body);
  194. ///when using m_ccdMode
  195. if (m_bt_ccd_mode == USE_CCD)
  196. {
  197. body->setCcdMotionThreshold(CUBE_HALF_EXTENTS);
  198. body->setCcdSweptSphereRadius(0.9*CUBE_HALF_EXTENTS);
  199. }
  200. }
  201. }
  202. }
  203. #endif
  204. }
  205. void BtPhysTest::TickGame(float seconds)
  206. {
  207. WorldEntity::TickGame(seconds);
  208. if (Input::GetButtonState(27 /*SDLK_ESCAPE*/))
  209. Ticker::Shutdown();
  210. m_simulation->TickContext(seconds);
  211. vec3 GroundBarycenter = vec3(.0f);
  212. vec3 PhysObjBarycenter = vec3(.0f);
  213. float factor = .0f;
  214. for (int i = 0; i < m_ground_list.Count(); i++)
  215. {
  216. PhysicsObject* PhysObj = m_ground_list[i];
  217. mat4 GroundMat = PhysObj->GetTransform();
  218. GroundBarycenter += GroundMat.v3.xyz;
  219. factor += 1.f;
  220. }
  221. GroundBarycenter /= factor;
  222. for (int i = 0; i < m_ground_list.Count(); i++)
  223. {
  224. PhysicsObject* PhysObj = m_ground_list[i];
  225. mat4 GroundMat = PhysObj->GetTransform();
  226. vec3 CenterToGround = GroundMat.v3.xyz - GroundBarycenter;
  227. vec3 CenterToCam = m_camera->m_position - GroundBarycenter;
  228. if (dot(normalize(CenterToCam - CenterToGround),
  229. normalize(CenterToGround)) > 0.f)
  230. PhysObj->SetRender(false);
  231. else
  232. PhysObj->SetRender(true);
  233. }
  234. for (int i = 0; i < m_ground_list.Count(); i++)
  235. {
  236. PhysicsObject* PhysObj = m_ground_list[i];
  237. mat4 GroundMat = PhysObj->GetTransform();
  238. mat4 CenterMx = mat4::translate(GroundBarycenter);
  239. GroundMat = inverse(CenterMx) * GroundMat;
  240. GroundMat = CenterMx *
  241. mat4(quat::fromeuler_xyz(vec3(.0f, 20.f, 20.0f) * seconds))
  242. * GroundMat;
  243. PhysObj->SetTransform(GroundMat.v3.xyz, quat(GroundMat));
  244. }
  245. PhysObjBarycenter = vec3(.0f);
  246. for (int i = 0; i < m_physobj_list.Count(); i++)
  247. {
  248. PhysicsObject* PhysObj = m_physobj_list[i];
  249. mat4 GroundMat = PhysObj->GetTransform();
  250. PhysObjBarycenter += GroundMat.v3.xyz;
  251. factor += 1.f;
  252. }
  253. PhysObjBarycenter /= factor;
  254. m_camera->SetTarget(PhysObjBarycenter);
  255. m_camera->SetPosition(GroundBarycenter + normalize(GroundBarycenter - PhysObjBarycenter) * 60.0f);
  256. #if 0
  257. ///step the simulation
  258. if (m_bt_world)
  259. {
  260. //int steps = (int)(seconds / 0.005f);
  261. //for (int i = 0; i < steps; i++)
  262. m_bt_world->stepSimulation(seconds /*/ steps*/);
  263. //optional but useful: debug drawing
  264. //m_bt_world->debugDrawWorld();
  265. }
  266. #endif
  267. }
  268. void BtPhysTest::TickDraw(float seconds)
  269. {
  270. WorldEntity::TickDraw(seconds);
  271. if (!m_ready)
  272. {
  273. #if 0
  274. m_ground_mesh.MeshConvert();
  275. m_rigid_mesh[0].MeshConvert();
  276. m_rigid_mesh[1].MeshConvert();
  277. m_rigid_mesh[2].MeshConvert();
  278. m_rigid_mesh[3].MeshConvert();
  279. m_rigid_mesh[4].MeshConvert();
  280. m_rigid_mesh[5].MeshConvert();
  281. #endif
  282. /* FIXME: this object never cleans up */
  283. m_ready = true;
  284. }
  285. Video::SetClearColor(vec4(0.0f, 0.0f, 0.12f, 1.0f));
  286. #if 0
  287. vec3 BarycenterLocation = vec3(.0f);
  288. float BarycenterFactor = 0.0f;
  289. for(int i=0;i<gNumObjects;i++)
  290. {
  291. mat4 m(1.0f);
  292. btMatrix3x3 rot; rot.setIdentity();
  293. btCollisionObject* colObj = m_bt_world->getCollisionObjectArray()[i];
  294. btRigidBody* body = btRigidBody::upcast(colObj);
  295. if(body && body->getMotionState())
  296. {
  297. btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
  298. myMotionState->m_graphicsWorldTrans.getOpenGLMatrix(&m[0][0]);
  299. rot = myMotionState->m_graphicsWorldTrans.getBasis();
  300. }
  301. else
  302. {
  303. colObj->getWorldTransform().getOpenGLMatrix(&m[0][0]);
  304. rot = colObj->getWorldTransform().getBasis();
  305. }
  306. if (i > 0)
  307. {
  308. BarycenterLocation += m.v3.xyz;
  309. BarycenterFactor += 1.0f;
  310. }
  311. if (i == 0)
  312. m_ground_mesh.Render(m);
  313. else
  314. m_rigid_mesh[i % 6].Render(m);
  315. }
  316. if (BarycenterFactor > .0f)
  317. {
  318. BarycenterLocation /= BarycenterFactor;
  319. m_camera->SetTarget(BarycenterLocation);
  320. m_camera->SetPosition(BarycenterLocation + vec3(-20.0f, 8.0f, .0f));
  321. }
  322. #endif
  323. }
  324. BtPhysTest::~BtPhysTest()
  325. {
  326. Ticker::Unref(m_camera);
  327. while (m_ground_list.Count())
  328. {
  329. PhysicsObject* CurPop = m_ground_list.Last();
  330. m_ground_list.Pop();
  331. Ticker::Unref(CurPop);
  332. }
  333. while (m_physobj_list.Count())
  334. {
  335. PhysicsObject* CurPop = m_physobj_list.Last();
  336. m_physobj_list.Pop();
  337. Ticker::Unref(CurPop);
  338. }
  339. #if 0
  340. //Exit Physics
  341. {
  342. //cleanup in the reverse order of creation/initialization
  343. //remove the rigidbodies from the dynamics world and delete them
  344. for (int i = m_bt_world->getNumCollisionObjects() - 1; i >= 0 ;i--)
  345. {
  346. btCollisionObject* obj = m_bt_world->getCollisionObjectArray()[i];
  347. btRigidBody* body = btRigidBody::upcast(obj);
  348. if (body && body->getMotionState())
  349. delete body->getMotionState();
  350. m_bt_world->removeCollisionObject(obj);
  351. delete obj;
  352. }
  353. //delete collision shapes
  354. for (int j = 0; j < m_bt_collision_shapes.Count(); j++)
  355. {
  356. btCollisionShape* shape = m_bt_collision_shapes[j];
  357. delete shape;
  358. }
  359. m_bt_collision_shapes.Empty();
  360. delete m_bt_world;
  361. delete m_bt_solver;
  362. delete m_bt_broadphase;
  363. delete m_bt_dispatcher;
  364. delete m_bt_collision_config;
  365. }
  366. #endif
  367. }
  368. int main(int argc, char **argv)
  369. {
  370. Application app("BtPhysTest", ivec2(1280, 720), 60.0f);
  371. #if defined _MSC_VER && !defined _XBOX
  372. _chdir("..");
  373. #elif defined _WIN32 && !defined _XBOX
  374. _chdir("../..");
  375. #endif
  376. new BtPhysTest(argc > 1);
  377. app.ShowPointer(false);
  378. app.Run();
  379. return EXIT_SUCCESS;
  380. }