InvertedPendulumPDControl.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #include "InvertedPendulumPDControl.h"
  2. #include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
  3. #include "BulletDynamics/Featherstone/btMultiBodyJointFeedback.h"
  4. #include "../CommonInterfaces/CommonMultiBodyBase.h"
  5. #include "../Utils/b3ResourcePath.h"
  6. #include "../CommonInterfaces/CommonParameterInterface.h"
  7. static btScalar radius(0.2);
  8. static btScalar kp = 100;
  9. static btScalar kd = 20;
  10. static btScalar maxForce = 100;
  11. struct InvertedPendulumPDControl : public CommonMultiBodyBase
  12. {
  13. btMultiBody* m_multiBody;
  14. btAlignedObjectArray<btMultiBodyJointFeedback*> m_jointFeedbacks;
  15. bool m_once;
  16. int m_frameCount;
  17. public:
  18. InvertedPendulumPDControl(struct GUIHelperInterface* helper);
  19. virtual ~InvertedPendulumPDControl();
  20. virtual void initPhysics();
  21. virtual void stepSimulation(float deltaTime);
  22. virtual void resetCamera()
  23. {
  24. float dist = 5;
  25. float pitch = 270;
  26. float yaw = 21;
  27. float targetPos[3]={-1.34,1.4,3.44};
  28. m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]);
  29. }
  30. };
  31. InvertedPendulumPDControl::InvertedPendulumPDControl(struct GUIHelperInterface* helper)
  32. :CommonMultiBodyBase(helper),
  33. m_once(true),
  34. m_frameCount(0)
  35. {
  36. }
  37. InvertedPendulumPDControl::~InvertedPendulumPDControl()
  38. {
  39. }
  40. ///this is a temporary global, until we determine if we need the option or not
  41. extern bool gJointFeedbackInWorldSpace;
  42. extern bool gJointFeedbackInJointFrame;
  43. btMultiBody* createInvertedPendulumMultiBody(btMultiBodyDynamicsWorld* world, GUIHelperInterface* guiHelper, const btTransform& baseWorldTrans, bool fixedBase)
  44. {
  45. btVector4 colors[4] =
  46. {
  47. btVector4(1,0,0,1),
  48. btVector4(0,1,0,1),
  49. btVector4(0,1,1,1),
  50. btVector4(1,1,0,1),
  51. };
  52. int curColor = 0;
  53. bool damping = false;
  54. bool gyro = false;
  55. int numLinks = 2;
  56. bool spherical = false; //set it ot false -to use 1DoF hinges instead of 3DoF sphericals
  57. bool canSleep = false;
  58. bool selfCollide = false;
  59. btVector3 linkHalfExtents(0.05, 0.37, 0.1);
  60. btVector3 baseHalfExtents(0.04, 0.35, 0.08);
  61. //mbC->forceMultiDof(); //if !spherical, you can comment this line to check the 1DoF algorithm
  62. //init the base
  63. btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
  64. float baseMass = fixedBase ? 0.f : 10.f;
  65. if(baseMass)
  66. {
  67. //btCollisionShape *shape = new btSphereShape(baseHalfExtents[0]);// btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
  68. btCollisionShape *shape = new btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
  69. shape->calculateLocalInertia(baseMass, baseInertiaDiag);
  70. delete shape;
  71. }
  72. btMultiBody *pMultiBody = new btMultiBody(numLinks, 0, baseInertiaDiag, fixedBase, canSleep);
  73. pMultiBody->setBaseWorldTransform(baseWorldTrans);
  74. btVector3 vel(0, 0, 0);
  75. // pMultiBody->setBaseVel(vel);
  76. //init the links
  77. btVector3 hingeJointAxis(1, 0, 0);
  78. //y-axis assumed up
  79. btVector3 parentComToCurrentCom(0, -linkHalfExtents[1] * 2.f, 0); //par body's COM to cur body's COM offset
  80. btVector3 currentPivotToCurrentCom(0, -linkHalfExtents[1], 0); //cur body's COM to cur body's PIV offset
  81. btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset
  82. //////
  83. btScalar q0 = 1.f * SIMD_PI/ 180.f;
  84. btQuaternion quat0(btVector3(1, 0, 0).normalized(), q0);
  85. quat0.normalize();
  86. /////
  87. for(int i = 0; i < numLinks; ++i)
  88. {
  89. float linkMass = 1.f;
  90. //if (i==3 || i==2)
  91. // linkMass= 1000;
  92. btVector3 linkInertiaDiag(0.f, 0.f, 0.f);
  93. btCollisionShape* shape = 0;
  94. if (i==0)
  95. {
  96. shape = new btBoxShape(btVector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2]));//
  97. } else
  98. {
  99. shape = new btSphereShape(radius);
  100. }
  101. shape->calculateLocalInertia(linkMass, linkInertiaDiag);
  102. delete shape;
  103. if(!spherical)
  104. {
  105. //pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
  106. if (i==0)
  107. {
  108. pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1,
  109. btQuaternion(0.f, 0.f, 0.f, 1.f),
  110. hingeJointAxis,
  111. parentComToCurrentPivot,
  112. currentPivotToCurrentCom, false);
  113. } else
  114. {
  115. btVector3 parentComToCurrentCom(0, -radius * 2.f, 0); //par body's COM to cur body's COM offset
  116. btVector3 currentPivotToCurrentCom(0, -radius, 0); //cur body's COM to cur body's PIV offset
  117. btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset
  118. pMultiBody->setupFixed(i, linkMass, linkInertiaDiag, i - 1,
  119. btQuaternion(0.f, 0.f, 0.f, 1.f),
  120. parentComToCurrentPivot,
  121. currentPivotToCurrentCom);
  122. }
  123. //pMultiBody->setupFixed(i,linkMass,linkInertiaDiag,i-1,btQuaternion(0,0,0,1),parentComToCurrentPivot,currentPivotToCurrentCom,false);
  124. }
  125. else
  126. {
  127. //pMultiBody->setupPlanar(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f)/*quat0*/, btVector3(1, 0, 0), parentComToCurrentPivot*2, false);
  128. pMultiBody->setupSpherical(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), parentComToCurrentPivot, currentPivotToCurrentCom, false);
  129. }
  130. }
  131. pMultiBody->finalizeMultiDof();
  132. ///
  133. world->addMultiBody(pMultiBody);
  134. btMultiBody* mbC = pMultiBody;
  135. mbC->setCanSleep(canSleep);
  136. mbC->setHasSelfCollision(selfCollide);
  137. mbC->setUseGyroTerm(gyro);
  138. //
  139. if(!damping)
  140. {
  141. mbC->setLinearDamping(0.f);
  142. mbC->setAngularDamping(0.f);
  143. }else
  144. { mbC->setLinearDamping(0.1f);
  145. mbC->setAngularDamping(0.9f);
  146. }
  147. //
  148. //////////////////////////////////////////////
  149. if(numLinks > 0)
  150. {
  151. btScalar q0 = 180.f * SIMD_PI/ 180.f;
  152. if(!spherical)
  153. {
  154. mbC->setJointPosMultiDof(0, &q0);
  155. }
  156. else
  157. {
  158. btQuaternion quat0(btVector3(1, 1, 0).normalized(), q0);
  159. quat0.normalize();
  160. mbC->setJointPosMultiDof(0, quat0);
  161. }
  162. }
  163. ///
  164. btAlignedObjectArray<btQuaternion> world_to_local;
  165. world_to_local.resize(pMultiBody->getNumLinks() + 1);
  166. btAlignedObjectArray<btVector3> local_origin;
  167. local_origin.resize(pMultiBody->getNumLinks() + 1);
  168. world_to_local[0] = pMultiBody->getWorldToBaseRot();
  169. local_origin[0] = pMultiBody->getBasePos();
  170. double friction = 1;
  171. {
  172. // float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
  173. float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
  174. if (1)
  175. {
  176. btCollisionShape* shape = new btBoxShape(btVector3(baseHalfExtents[0],baseHalfExtents[1],baseHalfExtents[2]));//new btSphereShape(baseHalfExtents[0]);
  177. guiHelper->createCollisionShapeGraphicsObject(shape);
  178. btMultiBodyLinkCollider* col= new btMultiBodyLinkCollider(pMultiBody, -1);
  179. col->setCollisionShape(shape);
  180. btTransform tr;
  181. tr.setIdentity();
  182. //if we don't set the initial pose of the btCollisionObject, the simulator will do this
  183. //when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider
  184. tr.setOrigin(local_origin[0]);
  185. btQuaternion orn(btVector3(0,0,1),0.25*3.1415926538);
  186. tr.setRotation(orn);
  187. col->setWorldTransform(tr);
  188. bool isDynamic = (baseMass > 0 && !fixedBase);
  189. short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
  190. short collisionFilterMask = isDynamic? short(btBroadphaseProxy::AllFilter) : short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
  191. world->addCollisionObject(col,collisionFilterGroup,collisionFilterMask);//, 2,1+2);
  192. btVector3 color(0.0,0.0,0.5);
  193. guiHelper->createCollisionObjectGraphicsObject(col,color);
  194. // col->setFriction(friction);
  195. pMultiBody->setBaseCollider(col);
  196. }
  197. }
  198. for (int i=0; i < pMultiBody->getNumLinks(); ++i)
  199. {
  200. const int parent = pMultiBody->getParent(i);
  201. world_to_local[i+1] = pMultiBody->getParentToLocalRot(i) * world_to_local[parent+1];
  202. local_origin[i+1] = local_origin[parent+1] + (quatRotate(world_to_local[i+1].inverse() , pMultiBody->getRVector(i)));
  203. }
  204. for (int i=0; i < pMultiBody->getNumLinks(); ++i)
  205. {
  206. btVector3 posr = local_origin[i+1];
  207. // float pos[4]={posr.x(),posr.y(),posr.z(),1};
  208. float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};
  209. btCollisionShape* shape =0;
  210. if (i==0)
  211. {
  212. shape = new btBoxShape(btVector3(linkHalfExtents[0],linkHalfExtents[1],linkHalfExtents[2]));//btSphereShape(linkHalfExtents[0]);
  213. } else
  214. {
  215. shape = new btSphereShape(radius);
  216. }
  217. guiHelper->createCollisionShapeGraphicsObject(shape);
  218. btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, i);
  219. col->setCollisionShape(shape);
  220. btTransform tr;
  221. tr.setIdentity();
  222. tr.setOrigin(posr);
  223. tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
  224. col->setWorldTransform(tr);
  225. // col->setFriction(friction);
  226. bool isDynamic = 1;//(linkMass > 0);
  227. short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
  228. short collisionFilterMask = isDynamic? short(btBroadphaseProxy::AllFilter) : short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
  229. //if (i==0||i>numLinks-2)
  230. {
  231. world->addCollisionObject(col,collisionFilterGroup,collisionFilterMask);//,2,1+2);
  232. btVector4 color = colors[curColor];
  233. curColor++;
  234. curColor&=3;
  235. guiHelper->createCollisionObjectGraphicsObject(col,color);
  236. pMultiBody->getLink(i).m_collider=col;
  237. }
  238. }
  239. return pMultiBody;
  240. }
  241. void InvertedPendulumPDControl::initPhysics()
  242. {
  243. {
  244. SliderParams slider("Kp",&kp);
  245. slider.m_minVal=-200;
  246. slider.m_maxVal=200;
  247. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
  248. }
  249. {
  250. SliderParams slider("Kd",&kd);
  251. slider.m_minVal=-50;
  252. slider.m_maxVal=50;
  253. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
  254. }
  255. {
  256. SliderParams slider("max force",&maxForce);
  257. slider.m_minVal=0;
  258. slider.m_maxVal=100;
  259. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
  260. }
  261. int upAxis = 1;
  262. gJointFeedbackInWorldSpace = true;
  263. gJointFeedbackInJointFrame = true;
  264. m_guiHelper->setUpAxis(upAxis);
  265. this->createEmptyDynamicsWorld();
  266. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  267. m_dynamicsWorld->getDebugDrawer()->setDebugMode(
  268. //btIDebugDraw::DBG_DrawConstraints
  269. +btIDebugDraw::DBG_DrawWireframe
  270. +btIDebugDraw::DBG_DrawContactPoints
  271. +btIDebugDraw::DBG_DrawAabb
  272. );//+btIDebugDraw::DBG_DrawConstraintLimits);
  273. m_dynamicsWorld->setGravity(btVector3(0,-10,0));
  274. btTransform baseWorldTrans;
  275. baseWorldTrans.setIdentity();
  276. baseWorldTrans.setOrigin(btVector3(1,2,3));
  277. m_multiBody = createInvertedPendulumMultiBody(m_dynamicsWorld, m_guiHelper, baseWorldTrans, true);
  278. //for (int i=pMultiBody->getNumLinks()-1;i>=0;i--)//
  279. for (int i=0;i<m_multiBody->getNumLinks();i++)
  280. {
  281. btMultiBodyJointFeedback* fb = new btMultiBodyJointFeedback();
  282. m_multiBody->getLink(i).m_jointFeedback = fb;
  283. m_jointFeedbacks.push_back(fb);
  284. //break;
  285. }
  286. }
  287. char fileName[1024];
  288. static btAlignedObjectArray<btScalar> qDesiredArray;
  289. void InvertedPendulumPDControl::stepSimulation(float deltaTime)
  290. {
  291. static btScalar offset = -0.1*SIMD_PI;
  292. m_frameCount++;
  293. if ((m_frameCount&0xff)==0 )
  294. {
  295. offset = -offset;
  296. }
  297. btScalar target= SIMD_PI+offset;
  298. qDesiredArray.resize(0);
  299. qDesiredArray.resize(m_multiBody->getNumLinks(),target);
  300. for (int joint = 0; joint<m_multiBody->getNumLinks();joint++)
  301. {
  302. int dof1 = 0;
  303. btScalar qActual = m_multiBody->getJointPosMultiDof(joint)[dof1];
  304. btScalar qdActual = m_multiBody->getJointVelMultiDof(joint)[dof1];
  305. btScalar positionError = (qDesiredArray[joint]-qActual);
  306. double desiredVelocity = 0;
  307. btScalar velocityError = (desiredVelocity-qdActual);
  308. btScalar force = kp * positionError + kd*velocityError;
  309. btClamp(force,-maxForce,maxForce);
  310. m_multiBody->addJointTorque(joint, force);
  311. }
  312. if (m_frameCount==100)
  313. {
  314. const char* gPngFileName = "pendulum";
  315. if (gPngFileName)
  316. {
  317. //printf("gPngFileName=%s\n",gPngFileName);
  318. sprintf(fileName,"%s%d.png",gPngFileName,m_frameCount);
  319. b3Printf("Made screenshot %s",fileName);
  320. this->m_guiHelper->getAppInterface()->dumpNextFrameToPng(fileName);
  321. }
  322. }
  323. m_dynamicsWorld->stepSimulation(1./60.,0);//240,0);
  324. static int count = 0;
  325. if ((count& 0x0f)==0)
  326. {
  327. #if 0
  328. for (int i=0;i<m_jointFeedbacks.size();i++)
  329. {
  330. b3Printf("F_reaction[%i] linear:%f,%f,%f, angular:%f,%f,%f",
  331. i,
  332. m_jointFeedbacks[i]->m_reactionForces.m_topVec[0],
  333. m_jointFeedbacks[i]->m_reactionForces.m_topVec[1],
  334. m_jointFeedbacks[i]->m_reactionForces.m_topVec[2],
  335. m_jointFeedbacks[i]->m_reactionForces.m_bottomVec[0],
  336. m_jointFeedbacks[i]->m_reactionForces.m_bottomVec[1],
  337. m_jointFeedbacks[i]->m_reactionForces.m_bottomVec[2]
  338. );
  339. }
  340. #endif
  341. }
  342. count++;
  343. /*
  344. b3Printf("base angvel = %f,%f,%f",m_multiBody->getBaseOmega()[0],
  345. m_multiBody->getBaseOmega()[1],
  346. m_multiBody->getBaseOmega()[2]
  347. );
  348. */
  349. btScalar jointVel =m_multiBody->getJointVel(0);
  350. // b3Printf("child angvel = %f",jointVel);
  351. }
  352. class CommonExampleInterface* InvertedPendulumPDControlCreateFunc(struct CommonExampleOptions& options)
  353. {
  354. return new InvertedPendulumPDControl(options.m_guiHelper);
  355. }