NewtonsCradle.cpp 13 KB

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