NewtonsRopeCradle.cpp 14 KB

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