InverseDynamicsExample.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 "InverseDynamicsExample.h"
  14. #include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
  15. #include "Bullet3Common/b3FileUtils.h"
  16. #include "BulletDynamics/Featherstone/btMultiBodyJointMotor.h"
  17. #include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
  18. #include "../CommonInterfaces/CommonParameterInterface.h"
  19. #include "../Utils/b3ResourcePath.h"
  20. #include "../Importers/ImportURDFDemo/BulletUrdfImporter.h"
  21. #include "../Importers/ImportURDFDemo/URDF2Bullet.h"
  22. #include "../Importers/ImportURDFDemo/MyMultiBodyCreator.h"
  23. #include "../CommonInterfaces/CommonMultiBodyBase.h"
  24. #include "btBulletDynamicsCommon.h"
  25. #include "LinearMath/btVector3.h"
  26. #include "LinearMath/btAlignedObjectArray.h"
  27. #include "../CommonInterfaces/CommonRigidBodyBase.h"
  28. #include "BulletInverseDynamics/IDConfig.hpp"
  29. #include "../Extras/InverseDynamics/btMultiBodyTreeCreator.hpp"
  30. #include "../RenderingExamples/TimeSeriesCanvas.h"
  31. #include <vector>
  32. // the UI interface makes it easier to use static variables & free functions
  33. // as parameters and callbacks
  34. static btScalar kp = 10 * 10;
  35. static btScalar kd = 2 * 10;
  36. static bool useInverseModel = true;
  37. static std::vector<btScalar> qd;
  38. static std::vector<std::string> qd_name;
  39. static std::vector<std::string> q_name;
  40. static btVector4 sJointCurveColors[8] =
  41. {
  42. btVector4(1, 0.3, 0.3, 1),
  43. btVector4(0.3, 1, 0.3, 1),
  44. btVector4(0.3, 0.3, 1, 1),
  45. btVector4(0.3, 1, 1, 1),
  46. btVector4(1, 0.3, 1, 1),
  47. btVector4(1, 1, 0.3, 1),
  48. btVector4(1, 0.7, 0.7, 1),
  49. btVector4(0.7, 1, 1, 1),
  50. };
  51. void toggleUseInverseModel(int buttonId, bool buttonState, void* userPointer)
  52. {
  53. useInverseModel = !useInverseModel;
  54. // todo(thomas) is there a way to get a toggle button with changing text?
  55. b3Printf("switched inverse model %s", useInverseModel ? "on" : "off");
  56. }
  57. class InverseDynamicsExample : public CommonMultiBodyBase
  58. {
  59. btInverseDynamicsExampleOptions m_option;
  60. btMultiBody* m_multiBody;
  61. btInverseDynamics::MultiBodyTree* m_inverseModel;
  62. TimeSeriesCanvas* m_timeSeriesCanvas;
  63. public:
  64. InverseDynamicsExample(struct GUIHelperInterface* helper, btInverseDynamicsExampleOptions option);
  65. virtual ~InverseDynamicsExample();
  66. virtual void initPhysics();
  67. virtual void stepSimulation(float deltaTime);
  68. void setFileName(const char* urdfFileName);
  69. virtual void resetCamera()
  70. {
  71. float dist = 1.5;
  72. float pitch = -10;
  73. float yaw = -80;
  74. float targetPos[3] = {0, 0, 0};
  75. m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]);
  76. }
  77. };
  78. InverseDynamicsExample::InverseDynamicsExample(struct GUIHelperInterface* helper, btInverseDynamicsExampleOptions option)
  79. : CommonMultiBodyBase(helper),
  80. m_option(option),
  81. m_multiBody(0),
  82. m_inverseModel(0),
  83. m_timeSeriesCanvas(0)
  84. {
  85. }
  86. InverseDynamicsExample::~InverseDynamicsExample()
  87. {
  88. delete m_inverseModel;
  89. delete m_timeSeriesCanvas;
  90. }
  91. //todo(erwincoumans) Quick hack, reference to InvertedPendulumPDControl implementation. Will create a separate header/source file for this.
  92. btMultiBody* createInvertedPendulumMultiBody(btMultiBodyDynamicsWorld* world, GUIHelperInterface* guiHelper, const btTransform& baseWorldTrans, bool fixedBase);
  93. void InverseDynamicsExample::initPhysics()
  94. {
  95. //roboticists like Z up
  96. int upAxis = 2;
  97. m_guiHelper->setUpAxis(upAxis);
  98. createEmptyDynamicsWorld();
  99. btVector3 gravity(0, 0, 0);
  100. // gravity[upAxis]=-9.8;
  101. m_dynamicsWorld->setGravity(gravity);
  102. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  103. {
  104. SliderParams slider("Kp", &kp);
  105. slider.m_minVal = 0;
  106. slider.m_maxVal = 2000;
  107. if (m_guiHelper->getParameterInterface())
  108. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
  109. }
  110. {
  111. SliderParams slider("Kd", &kd);
  112. slider.m_minVal = 0;
  113. slider.m_maxVal = 50;
  114. if (m_guiHelper->getParameterInterface())
  115. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
  116. }
  117. if (m_option == BT_ID_PROGRAMMATICALLY)
  118. {
  119. ButtonParams button("toggle inverse model", 0, true);
  120. button.m_callback = toggleUseInverseModel;
  121. m_guiHelper->getParameterInterface()->registerButtonParameter(button);
  122. }
  123. switch (m_option)
  124. {
  125. case BT_ID_LOAD_URDF:
  126. {
  127. BulletURDFImporter u2b(m_guiHelper, 0, 0, 1, 0);
  128. bool loadOk = u2b.loadURDF("kuka_iiwa/model.urdf"); // lwr / kuka.urdf");
  129. if (loadOk)
  130. {
  131. int rootLinkIndex = u2b.getRootLinkIndex();
  132. b3Printf("urdf root link index = %d\n", rootLinkIndex);
  133. MyMultiBodyCreator creation(m_guiHelper);
  134. btTransform identityTrans;
  135. identityTrans.setIdentity();
  136. ConvertURDF2Bullet(u2b, creation, identityTrans, m_dynamicsWorld, true, u2b.getPathPrefix());
  137. for (int i = 0; i < u2b.getNumAllocatedCollisionShapes(); i++)
  138. {
  139. m_collisionShapes.push_back(u2b.getAllocatedCollisionShape(i));
  140. }
  141. m_multiBody = creation.getBulletMultiBody();
  142. if (m_multiBody)
  143. {
  144. //kuka without joint control/constraints will gain energy explode soon due to timestep/integrator
  145. //temporarily set some extreme damping factors until we have some joint control or constraints
  146. m_multiBody->setAngularDamping(0 * 0.99);
  147. m_multiBody->setLinearDamping(0 * 0.99);
  148. b3Printf("Root link name = %s", u2b.getLinkName(u2b.getRootLinkIndex()).c_str());
  149. }
  150. }
  151. break;
  152. }
  153. case BT_ID_PROGRAMMATICALLY:
  154. {
  155. btTransform baseWorldTrans;
  156. baseWorldTrans.setIdentity();
  157. m_multiBody = createInvertedPendulumMultiBody(m_dynamicsWorld, m_guiHelper, baseWorldTrans, false);
  158. break;
  159. }
  160. default:
  161. {
  162. b3Error("Unknown option in InverseDynamicsExample::initPhysics");
  163. b3Assert(0);
  164. }
  165. };
  166. if (m_multiBody)
  167. {
  168. {
  169. if (m_guiHelper->getAppInterface() && m_guiHelper->getParameterInterface())
  170. {
  171. m_timeSeriesCanvas = new TimeSeriesCanvas(m_guiHelper->getAppInterface()->m_2dCanvasInterface, 512, 230, "Joint Space Trajectory");
  172. m_timeSeriesCanvas->setupTimeSeries(3, 100, 0);
  173. }
  174. }
  175. // construct inverse model
  176. btInverseDynamics::btMultiBodyTreeCreator id_creator;
  177. if (-1 == id_creator.createFromBtMultiBody(m_multiBody, false))
  178. {
  179. b3Error("error creating tree\n");
  180. }
  181. else
  182. {
  183. m_inverseModel = btInverseDynamics::CreateMultiBodyTree(id_creator);
  184. }
  185. // add joint target controls
  186. qd.resize(m_multiBody->getNumDofs());
  187. qd_name.resize(m_multiBody->getNumDofs());
  188. q_name.resize(m_multiBody->getNumDofs());
  189. if (m_timeSeriesCanvas && m_guiHelper->getParameterInterface())
  190. {
  191. for (std::size_t dof = 0; dof < qd.size(); dof++)
  192. {
  193. qd[dof] = 0;
  194. char tmp[25];
  195. sprintf(tmp, "q_desired[%lu]", dof);
  196. qd_name[dof] = tmp;
  197. SliderParams slider(qd_name[dof].c_str(), &qd[dof]);
  198. slider.m_minVal = -3.14;
  199. slider.m_maxVal = 3.14;
  200. sprintf(tmp, "q[%lu]", dof);
  201. q_name[dof] = tmp;
  202. m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
  203. btVector4 color = sJointCurveColors[dof & 7];
  204. m_timeSeriesCanvas->addDataSource(q_name[dof].c_str(), color[0] * 255, color[1] * 255, color[2] * 255);
  205. }
  206. }
  207. }
  208. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  209. }
  210. void InverseDynamicsExample::stepSimulation(float deltaTime)
  211. {
  212. if (m_multiBody)
  213. {
  214. const int num_dofs = m_multiBody->getNumDofs();
  215. btInverseDynamics::vecx nu(num_dofs), qdot(num_dofs), q(num_dofs), joint_force(num_dofs);
  216. btInverseDynamics::vecx pd_control(num_dofs);
  217. // compute joint forces from one of two control laws:
  218. // 1) "computed torque" control, which gives perfect, decoupled,
  219. // linear second order error dynamics per dof in case of a
  220. // perfect model and (and negligible time discretization effects)
  221. // 2) decoupled PD control per joint, without a model
  222. for (int dof = 0; dof < num_dofs; dof++)
  223. {
  224. q(dof) = m_multiBody->getJointPos(dof);
  225. qdot(dof) = m_multiBody->getJointVel(dof);
  226. const btScalar qd_dot = 0;
  227. const btScalar qd_ddot = 0;
  228. if (m_timeSeriesCanvas)
  229. m_timeSeriesCanvas->insertDataAtCurrentTime(q[dof], dof, true);
  230. // pd_control is either desired joint torque for pd control,
  231. // or the feedback contribution to nu
  232. pd_control(dof) = kd * (qd_dot - qdot(dof)) + kp * (qd[dof] - q(dof));
  233. // nu is the desired joint acceleration for computed torque control
  234. nu(dof) = qd_ddot + pd_control(dof);
  235. }
  236. if (useInverseModel)
  237. {
  238. // calculate joint forces corresponding to desired accelerations nu
  239. if (m_multiBody->hasFixedBase())
  240. {
  241. if (-1 != m_inverseModel->calculateInverseDynamics(q, qdot, nu, &joint_force))
  242. {
  243. //joint_force(dof) += damping*dot_q(dof);
  244. // use inverse model: apply joint force corresponding to
  245. // desired acceleration nu
  246. for (int dof = 0; dof < num_dofs; dof++)
  247. {
  248. m_multiBody->addJointTorque(dof, joint_force(dof));
  249. }
  250. }
  251. }
  252. else
  253. {
  254. //the inverse dynamics model represents the 6 DOFs of the base, unlike btMultiBody.
  255. //append some dummy values to represent the 6 DOFs of the base
  256. btInverseDynamics::vecx nu6(num_dofs + 6), qdot6(num_dofs + 6), q6(num_dofs + 6), joint_force6(num_dofs + 6);
  257. for (int i = 0; i < num_dofs; i++)
  258. {
  259. nu6[6 + i] = nu[i];
  260. qdot6[6 + i] = qdot[i];
  261. q6[6 + i] = q[i];
  262. joint_force6[6 + i] = joint_force[i];
  263. }
  264. if (-1 != m_inverseModel->calculateInverseDynamics(q6, qdot6, nu6, &joint_force6))
  265. {
  266. //joint_force(dof) += damping*dot_q(dof);
  267. // use inverse model: apply joint force corresponding to
  268. // desired acceleration nu
  269. for (int dof = 0; dof < num_dofs; dof++)
  270. {
  271. m_multiBody->addJointTorque(dof, joint_force6(dof + 6));
  272. }
  273. }
  274. }
  275. }
  276. else
  277. {
  278. for (int dof = 0; dof < num_dofs; dof++)
  279. {
  280. // no model: just apply PD control law
  281. m_multiBody->addJointTorque(dof, pd_control(dof));
  282. }
  283. }
  284. }
  285. if (m_timeSeriesCanvas)
  286. m_timeSeriesCanvas->nextTick();
  287. //todo: joint damping for btMultiBody, tune parameters
  288. // step the simulation
  289. if (m_dynamicsWorld)
  290. {
  291. // todo(thomas) check that this is correct:
  292. // want to advance by 10ms, with 1ms timesteps
  293. m_dynamicsWorld->stepSimulation(1e-3, 0); //,1e-3);
  294. btAlignedObjectArray<btQuaternion> scratch_q;
  295. btAlignedObjectArray<btVector3> scratch_m;
  296. m_multiBody->forwardKinematics(scratch_q, scratch_m);
  297. #if 0
  298. for (int i = 0; i < m_multiBody->getNumLinks(); i++)
  299. {
  300. //btVector3 pos = m_multiBody->getLink(i).m_cachedWorldTransform.getOrigin();
  301. btTransform tr = m_multiBody->getLink(i).m_cachedWorldTransform;
  302. btVector3 pos = tr.getOrigin() - quatRotate(tr.getRotation(), m_multiBody->getLink(i).m_dVector);
  303. btVector3 localAxis = m_multiBody->getLink(i).m_axes[0].m_topVec;
  304. //printf("link %d: %f,%f,%f, local axis:%f,%f,%f\n", i, pos.x(), pos.y(), pos.z(), localAxis.x(), localAxis.y(), localAxis.z());
  305. }
  306. #endif
  307. }
  308. }
  309. CommonExampleInterface* InverseDynamicsExampleCreateFunc(CommonExampleOptions& options)
  310. {
  311. return new InverseDynamicsExample(options.m_guiHelper, btInverseDynamicsExampleOptions(options.m_option));
  312. }
  313. B3_STANDALONE_EXAMPLE(InverseDynamicsExampleCreateFunc)