25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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