Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

BtPhysTest.cpp 14 KiB

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