NewtonsRopeCradle.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 "NewtonsRopeCradle.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 "BulletSoftBody/btSoftRigidDynamicsWorld.h"
  22. #include "BulletSoftBody/btSoftBodyHelpers.h"
  23. #include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
  24. #include "../CommonInterfaces/CommonParameterInterface.h"
  25. static btScalar gPendulaQty = 5; // Number of pendula in newton's cradle
  26. //TODO: This would actually be an Integer, but the Slider does not like integers, so I floor it when changed
  27. static btScalar gDisplacedPendula = 1; // number of displaced pendula
  28. //TODO: This is an int as well
  29. static btScalar gPendulaRestitution = 1; // pendula restition when hitting against each other
  30. static btScalar gSphereRadius = 1; // pendula radius
  31. static btScalar gInitialPendulumWidth = 4; // default pendula width
  32. static btScalar gInitialPendulumHeight = 8; // default pendula height
  33. static btScalar gRopeResolution = 1; // default rope resolution (number of links as in a chain)
  34. static btScalar gDisplacementForce = 30; // default force to displace the pendula
  35. static btScalar gForceScalar = 0; // default force scalar to apply a displacement
  36. struct NewtonsRopeCradleExample : public CommonRigidBodyBase
  37. {
  38. NewtonsRopeCradleExample(struct GUIHelperInterface* helper) : CommonRigidBodyBase(helper)
  39. {
  40. }
  41. virtual ~NewtonsRopeCradleExample() {}
  42. virtual void initPhysics();
  43. virtual void stepSimulation(float deltaTime);
  44. virtual void renderScene();
  45. virtual void applyPendulumForce(btScalar pendulumForce);
  46. void createEmptyDynamicsWorld()
  47. {
  48. m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration();
  49. m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
  50. m_broadphase = new btDbvtBroadphase();
  51. m_solver = new btSequentialImpulseConstraintSolver;
  52. m_dynamicsWorld = new btSoftRigidDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
  53. m_dynamicsWorld->setGravity(btVector3(0, -10, 0));
  54. softBodyWorldInfo.m_broadphase = m_broadphase;
  55. softBodyWorldInfo.m_dispatcher = m_dispatcher;
  56. softBodyWorldInfo.m_gravity = m_dynamicsWorld->getGravity();
  57. softBodyWorldInfo.m_sparsesdf.Initialize();
  58. }
  59. virtual void createRopePendulum(btSphereShape* colShape,
  60. const btVector3& position, const btQuaternion& pendulumOrientation, btScalar width, btScalar height, btScalar mass);
  61. virtual void changePendulaRestitution(btScalar restitution);
  62. virtual void connectWithRope(btRigidBody* body1, btRigidBody* body2);
  63. virtual bool keyboardCallback(int key, int state);
  64. virtual btSoftRigidDynamicsWorld* getSoftDynamicsWorld()
  65. {
  66. ///just make it a btSoftRigidDynamicsWorld please
  67. ///or we will add type checking
  68. return (btSoftRigidDynamicsWorld*)m_dynamicsWorld;
  69. }
  70. void resetCamera()
  71. {
  72. float dist = 41;
  73. float pitch = -35;
  74. float yaw = 52;
  75. float targetPos[3] = {0, 0.46, 0};
  76. m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]);
  77. }
  78. std::vector<btSliderConstraint*> constraints;
  79. std::vector<btRigidBody*> pendula;
  80. btSoftBodyWorldInfo softBodyWorldInfo;
  81. };
  82. static NewtonsRopeCradleExample* nex = NULL;
  83. void onRopePendulaRestitutionChanged(float pendulaRestitution, void*);
  84. void applyRForceWithForceScalar(float forceScalar);
  85. void NewtonsRopeCradleExample::initPhysics()
  86. {
  87. { // create a slider to change the number of pendula
  88. SliderParams slider("Number of Pendula", &gPendulaQty);
  89. slider.m_minVal = 1;
  90. slider.m_maxVal = 50;
  91. slider.m_clampToIntegers = true;
  92. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  93. slider);
  94. }
  95. { // create a slider to change the number of displaced pendula
  96. SliderParams slider("Number of Displaced Pendula", &gDisplacedPendula);
  97. slider.m_minVal = 0;
  98. slider.m_maxVal = 49;
  99. slider.m_clampToIntegers = true;
  100. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  101. slider);
  102. }
  103. { // create a slider to change the pendula restitution
  104. SliderParams slider("Pendula Restitution", &gPendulaRestitution);
  105. slider.m_minVal = 0;
  106. slider.m_maxVal = 1;
  107. slider.m_clampToNotches = false;
  108. slider.m_callback = onRopePendulaRestitutionChanged;
  109. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  110. slider);
  111. }
  112. { // create a slider to change the rope resolution
  113. SliderParams slider("Rope Resolution", &gRopeResolution);
  114. slider.m_minVal = 1;
  115. slider.m_maxVal = 20;
  116. slider.m_clampToIntegers = true;
  117. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  118. slider);
  119. }
  120. { // create a slider to change the pendulum width
  121. SliderParams slider("Pendulum Width", &gInitialPendulumWidth);
  122. slider.m_minVal = 0;
  123. slider.m_maxVal = 40;
  124. slider.m_clampToNotches = false;
  125. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  126. slider);
  127. }
  128. { // create a slider to change the pendulum height
  129. SliderParams slider("Pendulum Height", &gInitialPendulumHeight);
  130. slider.m_minVal = 0;
  131. slider.m_maxVal = 40;
  132. slider.m_clampToNotches = false;
  133. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  134. slider);
  135. }
  136. { // create a slider to change the force to displace the lowest pendulum
  137. SliderParams slider("Displacement force", &gDisplacementForce);
  138. slider.m_minVal = 0.1;
  139. slider.m_maxVal = 200;
  140. slider.m_clampToNotches = false;
  141. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  142. slider);
  143. }
  144. { // create a slider to apply the force by slider
  145. SliderParams slider("Apply displacement force", &gForceScalar);
  146. slider.m_minVal = -1;
  147. slider.m_maxVal = 1;
  148. slider.m_clampToNotches = false;
  149. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(
  150. slider);
  151. }
  152. m_guiHelper->setUpAxis(1);
  153. createEmptyDynamicsWorld();
  154. // create a debug drawer
  155. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  156. if (m_dynamicsWorld->getDebugDrawer())
  157. m_dynamicsWorld->getDebugDrawer()->setDebugMode(
  158. btIDebugDraw::DBG_DrawWireframe + btIDebugDraw::DBG_DrawContactPoints + btIDebugDraw::DBG_DrawConstraints + btIDebugDraw::DBG_DrawConstraintLimits);
  159. { // create the pendula starting at the indicated position below and where each pendulum has the following mass
  160. btScalar pendulumMass(1.0f);
  161. btVector3 position(0.0f, 15.0f, 0.0f); // initial left-most pendulum position
  162. btQuaternion orientation(0, 0, 0, 1); // orientation of the pendula
  163. // Re-using the same collision is better for memory usage and performance
  164. btSphereShape* pendulumShape = new btSphereShape(gSphereRadius);
  165. m_collisionShapes.push_back(pendulumShape);
  166. for (int i = 0; i < std::floor(gPendulaQty); i++)
  167. {
  168. // create pendulum
  169. createRopePendulum(pendulumShape, position, orientation, gInitialPendulumWidth,
  170. gInitialPendulumHeight, pendulumMass);
  171. // displace the pendula 1.05 sphere size, so that they all nearly touch (small spacings in between)
  172. position.setX(position.x() - 2.1f * gSphereRadius);
  173. }
  174. }
  175. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  176. }
  177. void NewtonsRopeCradleExample::connectWithRope(btRigidBody* body1, btRigidBody* body2)
  178. {
  179. btSoftBody* softBodyRope0 = btSoftBodyHelpers::CreateRope(softBodyWorldInfo, body1->getWorldTransform().getOrigin(), body2->getWorldTransform().getOrigin(), gRopeResolution, 0);
  180. softBodyRope0->setTotalMass(0.1f);
  181. softBodyRope0->appendAnchor(0, body1);
  182. softBodyRope0->appendAnchor(softBodyRope0->m_nodes.size() - 1, body2);
  183. softBodyRope0->m_cfg.piterations = 5;
  184. softBodyRope0->m_cfg.kDP = 0.005f;
  185. softBodyRope0->m_cfg.kSHR = 1;
  186. softBodyRope0->m_cfg.kCHR = 1;
  187. softBodyRope0->m_cfg.kKHR = 1;
  188. getSoftDynamicsWorld()->addSoftBody(softBodyRope0);
  189. }
  190. void NewtonsRopeCradleExample::stepSimulation(float deltaTime)
  191. {
  192. applyRForceWithForceScalar(gForceScalar); // apply force defined by apply force slider
  193. if (m_dynamicsWorld)
  194. {
  195. m_dynamicsWorld->stepSimulation(deltaTime);
  196. }
  197. }
  198. void NewtonsRopeCradleExample::createRopePendulum(btSphereShape* colShape,
  199. const btVector3& position, const btQuaternion& pendulumOrientation, btScalar width, btScalar height, btScalar mass)
  200. {
  201. // The pendulum looks like this (names when built):
  202. // O O topSphere1 topSphere2
  203. // \ /
  204. // O bottomSphere
  205. //create a dynamic pendulum
  206. btTransform startTransform;
  207. startTransform.setIdentity();
  208. // calculate sphere positions
  209. btVector3 topSphere1RelPosition(0, 0, width);
  210. btVector3 topSphere2RelPosition(0, 0, -width);
  211. btVector3 bottomSphereRelPosition(0, -height, 0);
  212. // position the top sphere above ground with appropriate orientation
  213. startTransform.setOrigin(btVector3(0, 0, 0)); // no translation intitially
  214. startTransform.setRotation(pendulumOrientation); // pendulum rotation
  215. startTransform.setOrigin(startTransform * topSphere1RelPosition); // rotate this position
  216. startTransform.setOrigin(position + startTransform.getOrigin()); // add non-rotated position to the relative position
  217. btRigidBody* topSphere1 = createRigidBody(0, startTransform, colShape); // make top sphere static
  218. // position the top sphere above ground with appropriate orientation
  219. startTransform.setOrigin(btVector3(0, 0, 0)); // no translation intitially
  220. startTransform.setRotation(pendulumOrientation); // pendulum rotation
  221. startTransform.setOrigin(startTransform * topSphere2RelPosition); // rotate this position
  222. startTransform.setOrigin(position + startTransform.getOrigin()); // add non-rotated position to the relative position
  223. btRigidBody* topSphere2 = createRigidBody(0, startTransform, colShape); // make top sphere static
  224. // position the bottom sphere below the top sphere
  225. startTransform.setOrigin(btVector3(0, 0, 0)); // no translation intitially
  226. startTransform.setRotation(pendulumOrientation); // pendulum rotation
  227. startTransform.setOrigin(startTransform * bottomSphereRelPosition); // rotate this position
  228. startTransform.setOrigin(position + startTransform.getOrigin()); // add non-rotated position to the relative position
  229. btRigidBody* bottomSphere = createRigidBody(mass, startTransform, colShape);
  230. bottomSphere->setFriction(0); // we do not need friction here
  231. pendula.push_back(bottomSphere);
  232. // disable the deactivation when objects do not move anymore
  233. topSphere1->setActivationState(DISABLE_DEACTIVATION);
  234. topSphere2->setActivationState(DISABLE_DEACTIVATION);
  235. bottomSphere->setActivationState(DISABLE_DEACTIVATION);
  236. bottomSphere->setRestitution(gPendulaRestitution); // set pendula restitution
  237. // add ropes between spheres
  238. connectWithRope(topSphere1, bottomSphere);
  239. connectWithRope(topSphere2, bottomSphere);
  240. }
  241. void NewtonsRopeCradleExample::renderScene()
  242. {
  243. CommonRigidBodyBase::renderScene();
  244. btSoftRigidDynamicsWorld* softWorld = getSoftDynamicsWorld();
  245. for (int i = 0; i < softWorld->getSoftBodyArray().size(); i++)
  246. {
  247. btSoftBody* psb = (btSoftBody*)softWorld->getSoftBodyArray()[i];
  248. //if (softWorld->getDebugDrawer() && !(softWorld->getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe)))
  249. {
  250. btSoftBodyHelpers::DrawFrame(psb, softWorld->getDebugDrawer());
  251. btSoftBodyHelpers::Draw(psb, softWorld->getDebugDrawer(), softWorld->getDrawFlags());
  252. }
  253. }
  254. }
  255. void NewtonsRopeCradleExample::changePendulaRestitution(btScalar restitution)
  256. {
  257. for (std::vector<btRigidBody*>::iterator rit = pendula.begin();
  258. rit != pendula.end(); rit++)
  259. {
  260. btAssert((*rit) && "Null constraint");
  261. (*rit)->setRestitution(restitution);
  262. }
  263. }
  264. bool NewtonsRopeCradleExample::keyboardCallback(int key, int state)
  265. {
  266. //b3Printf("Key pressed: %d in state %d \n",key,state);
  267. // key 3
  268. switch (key)
  269. {
  270. case '3' /*ASCII for 3*/:
  271. {
  272. applyPendulumForce(gDisplacementForce);
  273. return true;
  274. }
  275. }
  276. return false;
  277. }
  278. void NewtonsRopeCradleExample::applyPendulumForce(btScalar pendulumForce)
  279. {
  280. if (pendulumForce != 0)
  281. {
  282. b3Printf("Apply %f to pendulum", pendulumForce);
  283. for (int i = 0; i < gDisplacedPendula; i++)
  284. {
  285. if (gDisplacedPendula >= 0 && gDisplacedPendula <= gPendulaQty)
  286. pendula[i]->applyCentralForce(btVector3(pendulumForce, 0, 0));
  287. }
  288. }
  289. }
  290. // GUI parameter modifiers
  291. void onRopePendulaRestitutionChanged(float pendulaRestitution, void*)
  292. {
  293. if (nex)
  294. {
  295. nex->changePendulaRestitution(pendulaRestitution);
  296. }
  297. }
  298. void applyRForceWithForceScalar(float forceScalar)
  299. {
  300. if (nex)
  301. {
  302. btScalar appliedForce = forceScalar * gDisplacementForce;
  303. if (fabs(gForceScalar) < 0.2f)
  304. gForceScalar = 0;
  305. nex->applyPendulumForce(appliedForce);
  306. }
  307. }
  308. CommonExampleInterface* ET_NewtonsRopeCradleCreateFunc(
  309. CommonExampleOptions& options)
  310. {
  311. nex = new NewtonsRopeCradleExample(options.m_guiHelper);
  312. return nex;
  313. }