NewtonsCradle.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2015 Google Inc. http://bulletphysics.org
  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 "NewtonsCradle.h"
  14. #include <cmath>
  15. #include <iterator>
  16. #include <vector> // TODO: Should I use another data structure?
  17. #include "btBulletDynamicsCommon.h"
  18. #include "LinearMath/btVector3.h"
  19. #include "LinearMath/btAlignedObjectArray.h"
  20. #include "../CommonInterfaces/CommonRigidBodyBase.h"
  21. #include "../CommonInterfaces/CommonParameterInterface.h"
  22. static btScalar gPendulaQty = 5; // Number of pendula in newton's cradle
  23. //TODO: This would actually be an Integer, but the Slider does not like integers, so I floor it when changed
  24. static btScalar gDisplacedPendula = 1; // number of displaced pendula
  25. //TODO: This is an int as well
  26. static btScalar gPendulaRestitution = 1; // pendula restitution when hitting against each other
  27. static btScalar gSphereRadius = 1; // pendula radius
  28. static btScalar gCurrentPendulumLength = 8; // current pendula length
  29. static btScalar gInitialPendulumLength = 8; // default pendula length
  30. static btScalar gDisplacementForce = 30; // default force to displace the pendula
  31. static btScalar gForceScalar = 0; // default force scalar to apply a displacement
  32. struct NewtonsCradleExample : public CommonRigidBodyBase
  33. {
  34. NewtonsCradleExample(struct GUIHelperInterface* helper) : CommonRigidBodyBase(helper)
  35. {
  36. }
  37. virtual ~NewtonsCradleExample()
  38. {
  39. }
  40. virtual void initPhysics();
  41. virtual void renderScene();
  42. virtual void createPendulum(btSphereShape* colShape, const btVector3& position, btScalar length, btScalar mass);
  43. virtual void changePendulaLength(btScalar length);
  44. virtual void changePendulaRestitution(btScalar restitution);
  45. virtual void stepSimulation(float deltaTime);
  46. virtual bool keyboardCallback(int key, int state);
  47. virtual void applyPendulumForce(btScalar pendulumForce);
  48. void resetCamera()
  49. {
  50. float dist = 41;
  51. float pitch = -35;
  52. float yaw = 52;
  53. float targetPos[3] = {0, 0.46, 0};
  54. m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1],
  55. targetPos[2]);
  56. }
  57. std::vector<btSliderConstraint*> constraints; // keep a handle to the slider constraints
  58. std::vector<btRigidBody*> pendula; // keep a handle to the pendula
  59. };
  60. static NewtonsCradleExample* nex = NULL;
  61. void onPendulaLengthChanged(float pendulaLength, void* userPtr); // Change the pendula length
  62. void onPendulaRestitutionChanged(float pendulaRestitution, void* userPtr); // change the pendula restitution
  63. void applyForceWithForceScalar(float forceScalar);
  64. void NewtonsCradleExample::initPhysics()
  65. {
  66. { // create a slider to change the number of pendula
  67. SliderParams slider("Number of Pendula", &gPendulaQty);
  68. slider.m_minVal = 1;
  69. slider.m_maxVal = 50;
  70. slider.m_clampToIntegers = true;
  71. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  72. slider);
  73. }
  74. { // create a slider to change the number of displaced pendula
  75. SliderParams slider("Number of Displaced Pendula", &gDisplacedPendula);
  76. slider.m_minVal = 0;
  77. slider.m_maxVal = 49;
  78. slider.m_clampToIntegers = true;
  79. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  80. slider);
  81. }
  82. { // create a slider to change the pendula restitution
  83. SliderParams slider("Pendula Restitution", &gPendulaRestitution);
  84. slider.m_minVal = 0;
  85. slider.m_maxVal = 1;
  86. slider.m_clampToNotches = false;
  87. slider.m_callback = onPendulaRestitutionChanged;
  88. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  89. slider);
  90. }
  91. { // create a slider to change the pendulum length
  92. SliderParams slider("Pendula Length", &gCurrentPendulumLength);
  93. slider.m_minVal = 0;
  94. slider.m_maxVal = 49;
  95. slider.m_clampToNotches = false;
  96. slider.m_callback = onPendulaLengthChanged;
  97. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  98. slider);
  99. }
  100. { // create a slider to change the force to displace the lowest pendulum
  101. SliderParams slider("Displacement force", &gDisplacementForce);
  102. slider.m_minVal = 0.1;
  103. slider.m_maxVal = 200;
  104. slider.m_clampToNotches = false;
  105. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  106. slider);
  107. }
  108. { // create a slider to apply the force by slider
  109. SliderParams slider("Apply displacement force", &gForceScalar);
  110. slider.m_minVal = -1;
  111. slider.m_maxVal = 1;
  112. slider.m_clampToNotches = false;
  113. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  114. slider);
  115. }
  116. m_guiHelper->setUpAxis(1);
  117. createEmptyDynamicsWorld();
  118. // create a debug drawer
  119. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  120. if (m_dynamicsWorld->getDebugDrawer())
  121. m_dynamicsWorld->getDebugDrawer()->setDebugMode(
  122. btIDebugDraw::DBG_DrawWireframe + btIDebugDraw::DBG_DrawContactPoints + btIDebugDraw::DBG_DrawConstraints + btIDebugDraw::DBG_DrawConstraintLimits);
  123. { // create the pendula starting at the indicated position below and where each pendulum has the following mass
  124. btScalar pendulumMass(1.f);
  125. btVector3 position(0.0f, 15.0f, 0.0f); // initial left-most pendulum position
  126. btQuaternion orientation(0, 0, 0, 1); // orientation of the pendula
  127. // Re-using the same collision is better for memory usage and performance
  128. btSphereShape* pendulumShape = new btSphereShape(gSphereRadius);
  129. m_collisionShapes.push_back(pendulumShape);
  130. for (int i = 0; i < std::floor(gPendulaQty); i++)
  131. {
  132. // create pendulum
  133. createPendulum(pendulumShape, position, gInitialPendulumLength, pendulumMass);
  134. // displace the pendula 1.05 sphere size, so that they all nearly touch (small spacings in between
  135. position.setX(position.x() - 2.1f * gSphereRadius);
  136. }
  137. }
  138. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  139. }
  140. void NewtonsCradleExample::stepSimulation(float deltaTime)
  141. {
  142. applyForceWithForceScalar(gForceScalar); // apply force defined by apply force slider
  143. if (m_dynamicsWorld)
  144. {
  145. m_dynamicsWorld->stepSimulation(deltaTime);
  146. }
  147. }
  148. void NewtonsCradleExample::createPendulum(btSphereShape* colShape, const btVector3& position, btScalar length, btScalar mass)
  149. {
  150. // The pendulum looks like this (names when built):
  151. // O topSphere
  152. // |
  153. // O bottomSphere
  154. //create a dynamic pendulum
  155. btTransform startTransform;
  156. startTransform.setIdentity();
  157. // position the top sphere above ground with a moving x position
  158. startTransform.setOrigin(position);
  159. startTransform.setRotation(btQuaternion(0, 0, 0, 1)); // zero rotation
  160. btRigidBody* topSphere = createRigidBody(mass, startTransform, colShape);
  161. // position the bottom sphere below the top sphere
  162. startTransform.setOrigin(
  163. btVector3(position.x(), btScalar(position.y() - length),
  164. position.z()));
  165. startTransform.setRotation(btQuaternion(0, 0, 0, 1)); // zero rotation
  166. btRigidBody* bottomSphere = createRigidBody(mass, startTransform, colShape);
  167. bottomSphere->setFriction(0); // we do not need friction here
  168. pendula.push_back(bottomSphere);
  169. // disable the deactivation when objects do not move anymore
  170. topSphere->setActivationState(DISABLE_DEACTIVATION);
  171. bottomSphere->setActivationState(DISABLE_DEACTIVATION);
  172. bottomSphere->setRestitution(gPendulaRestitution); // set pendula restitution
  173. //make the top sphere position "fixed" to the world by attaching with a point to point constraint
  174. // The pivot is defined in the reference frame of topSphere, so the attachment is exactly at the center of the topSphere
  175. btVector3 constraintPivot(btVector3(0.0f, 0.0f, 0.0f));
  176. btPoint2PointConstraint* p2pconst = new btPoint2PointConstraint(*topSphere,
  177. constraintPivot);
  178. p2pconst->setDbgDrawSize(btScalar(5.f)); // set the size of the debug drawing
  179. // add the constraint to the world
  180. m_dynamicsWorld->addConstraint(p2pconst, true);
  181. //create constraint between spheres
  182. // this is represented by the constraint pivot in the local frames of reference of both constrained spheres
  183. // furthermore we need to rotate the constraint appropriately to orient it correctly in space
  184. btTransform constraintPivotInTopSphereRF, constraintPivotInBottomSphereRF;
  185. constraintPivotInTopSphereRF.setIdentity();
  186. constraintPivotInBottomSphereRF.setIdentity();
  187. // the slider constraint is x aligned per default, but we want it to be y aligned, therefore we rotate it
  188. btQuaternion qt;
  189. qt.setEuler(0, 0, -SIMD_HALF_PI);
  190. constraintPivotInTopSphereRF.setRotation(qt); //we use Y like up Axis
  191. constraintPivotInBottomSphereRF.setRotation(qt); //we use Y like up Axis
  192. //Obtain the position of topSphere in local reference frame of bottomSphere (the pivot is therefore in the center of topSphere)
  193. btVector3 topSphereInBottomSphereRF =
  194. (bottomSphere->getWorldTransform().inverse()(
  195. topSphere->getWorldTransform().getOrigin()));
  196. constraintPivotInBottomSphereRF.setOrigin(topSphereInBottomSphereRF);
  197. btSliderConstraint* sliderConst = new btSliderConstraint(*topSphere,
  198. *bottomSphere, constraintPivotInTopSphereRF, constraintPivotInBottomSphereRF, true);
  199. sliderConst->setDbgDrawSize(btScalar(5.f)); // set the size of the debug drawing
  200. // set limits
  201. // the initial setup of the constraint defines the origins of the limit dimensions,
  202. // therefore we set both limits directly to the current position of the topSphere
  203. sliderConst->setLowerLinLimit(btScalar(0));
  204. sliderConst->setUpperLinLimit(btScalar(0));
  205. sliderConst->setLowerAngLimit(btScalar(0));
  206. sliderConst->setUpperAngLimit(btScalar(0));
  207. constraints.push_back(sliderConst);
  208. // add the constraint to the world
  209. m_dynamicsWorld->addConstraint(sliderConst, true);
  210. }
  211. void NewtonsCradleExample::changePendulaLength(btScalar length)
  212. {
  213. btScalar lowerLimit = -gInitialPendulumLength;
  214. for (std::vector<btSliderConstraint*>::iterator sit = constraints.begin();
  215. sit != constraints.end(); sit++)
  216. {
  217. btAssert((*sit) && "Null constraint");
  218. //if the pendulum is being shortened beyond it's own length, we don't let the lower sphere to go past the upper one
  219. if (lowerLimit <= length)
  220. {
  221. (*sit)->setLowerLinLimit(length + lowerLimit);
  222. (*sit)->setUpperLinLimit(length + lowerLimit);
  223. }
  224. }
  225. }
  226. void NewtonsCradleExample::changePendulaRestitution(btScalar restitution)
  227. {
  228. for (std::vector<btRigidBody*>::iterator rit = pendula.begin();
  229. rit != pendula.end(); rit++)
  230. {
  231. btAssert((*rit) && "Null constraint");
  232. (*rit)->setRestitution(restitution);
  233. }
  234. }
  235. void NewtonsCradleExample::renderScene()
  236. {
  237. CommonRigidBodyBase::renderScene();
  238. }
  239. bool NewtonsCradleExample::keyboardCallback(int key, int state)
  240. {
  241. //b3Printf("Key pressed: %d in state %d \n",key,state);
  242. //key 1, key 2, key 3
  243. switch (key)
  244. {
  245. case '1' /*ASCII for 1*/:
  246. {
  247. //assumption: Sphere are aligned in Z axis
  248. btScalar newLimit = btScalar(gCurrentPendulumLength + 0.1);
  249. changePendulaLength(newLimit);
  250. gCurrentPendulumLength = newLimit;
  251. b3Printf("Increase pendulum length to %f", gCurrentPendulumLength);
  252. return true;
  253. }
  254. case '2' /*ASCII for 2*/:
  255. {
  256. //assumption: Sphere are aligned in Z axis
  257. btScalar newLimit = btScalar(gCurrentPendulumLength - 0.1);
  258. //is being shortened beyond it's own length, we don't let the lower sphere to go over the upper one
  259. if (0 <= newLimit)
  260. {
  261. changePendulaLength(newLimit);
  262. gCurrentPendulumLength = newLimit;
  263. }
  264. b3Printf("Decrease pendulum length to %f", gCurrentPendulumLength);
  265. return true;
  266. }
  267. case '3' /*ASCII for 3*/:
  268. {
  269. applyPendulumForce(gDisplacementForce);
  270. return true;
  271. }
  272. }
  273. return false;
  274. }
  275. void NewtonsCradleExample::applyPendulumForce(btScalar pendulumForce)
  276. {
  277. if (pendulumForce != 0)
  278. {
  279. b3Printf("Apply %f to pendulum", pendulumForce);
  280. for (int i = 0; i < gDisplacedPendula; i++)
  281. {
  282. if (gDisplacedPendula >= 0 && gDisplacedPendula <= gPendulaQty)
  283. pendula[i]->applyCentralForce(btVector3(pendulumForce, 0, 0));
  284. }
  285. }
  286. }
  287. // GUI parameter modifiers
  288. void onPendulaLengthChanged(float pendulaLength, void*)
  289. {
  290. if (nex)
  291. {
  292. nex->changePendulaLength(pendulaLength);
  293. //b3Printf("Pendula length changed to %f \n",sliderValue );
  294. }
  295. }
  296. void onPendulaRestitutionChanged(float pendulaRestitution, void*)
  297. {
  298. if (nex)
  299. {
  300. nex->changePendulaRestitution(pendulaRestitution);
  301. }
  302. }
  303. void applyForceWithForceScalar(float forceScalar)
  304. {
  305. if (nex)
  306. {
  307. btScalar appliedForce = forceScalar * gDisplacementForce;
  308. if (fabs(gForceScalar) < 0.2f)
  309. gForceScalar = 0;
  310. nex->applyPendulumForce(appliedForce);
  311. }
  312. }
  313. CommonExampleInterface* ET_NewtonsCradleCreateFunc(
  314. CommonExampleOptions& options)
  315. {
  316. nex = new NewtonsCradleExample(options.m_guiHelper);
  317. return nex;
  318. }