btDeformableBodySolver.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. /*
  2. Written by Xuchen Han <xuchenhan2015@u.northwestern.edu>
  3. Bullet Continuous Collision Detection and Physics Library
  4. Copyright (c) 2019 Google Inc. http://bulletphysics.org
  5. This software is provided 'as-is', without any express or implied warranty.
  6. In no event will the authors be held liable for any damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it freely,
  9. subject to the following restrictions:
  10. 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.
  11. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  12. 3. This notice may not be removed or altered from any source distribution.
  13. */
  14. #include <stdio.h>
  15. #include <limits>
  16. #include "btDeformableBodySolver.h"
  17. #include "btSoftBodyInternals.h"
  18. #include "LinearMath/btQuickprof.h"
  19. static const int kMaxConjugateGradientIterations = 300;
  20. btDeformableBodySolver::btDeformableBodySolver()
  21. : m_numNodes(0), m_cg(kMaxConjugateGradientIterations), m_cr(kMaxConjugateGradientIterations), m_maxNewtonIterations(1), m_newtonTolerance(1e-4), m_lineSearch(false), m_useProjection(false)
  22. {
  23. m_objective = new btDeformableBackwardEulerObjective(m_softBodies, m_backupVelocity);
  24. m_reducedSolver = false;
  25. }
  26. btDeformableBodySolver::~btDeformableBodySolver()
  27. {
  28. delete m_objective;
  29. }
  30. void btDeformableBodySolver::solveDeformableConstraints(btScalar solverdt)
  31. {
  32. BT_PROFILE("solveDeformableConstraints");
  33. if (!m_implicit)
  34. {
  35. m_objective->computeResidual(solverdt, m_residual);
  36. m_objective->applyDynamicFriction(m_residual);
  37. if (m_useProjection)
  38. {
  39. computeStep(m_dv, m_residual);
  40. }
  41. else
  42. {
  43. TVStack rhs, x;
  44. m_objective->addLagrangeMultiplierRHS(m_residual, m_dv, rhs);
  45. m_objective->addLagrangeMultiplier(m_dv, x);
  46. m_objective->m_preconditioner->reinitialize(true);
  47. computeStep(x, rhs);
  48. for (int i = 0; i < m_dv.size(); ++i)
  49. {
  50. m_dv[i] = x[i];
  51. }
  52. }
  53. updateVelocity();
  54. }
  55. else
  56. {
  57. for (int i = 0; i < m_maxNewtonIterations; ++i)
  58. {
  59. updateState();
  60. // add the inertia term in the residual
  61. int counter = 0;
  62. for (int k = 0; k < m_softBodies.size(); ++k)
  63. {
  64. btSoftBody* psb = m_softBodies[k];
  65. for (int j = 0; j < psb->m_nodes.size(); ++j)
  66. {
  67. if (psb->m_nodes[j].m_im > 0)
  68. {
  69. m_residual[counter] = (-1. / psb->m_nodes[j].m_im) * m_dv[counter];
  70. }
  71. ++counter;
  72. }
  73. }
  74. m_objective->computeResidual(solverdt, m_residual);
  75. if (m_objective->computeNorm(m_residual) < m_newtonTolerance && i > 0)
  76. {
  77. break;
  78. }
  79. // todo xuchenhan@: this really only needs to be calculated once
  80. m_objective->applyDynamicFriction(m_residual);
  81. if (m_lineSearch)
  82. {
  83. btScalar inner_product = computeDescentStep(m_ddv, m_residual);
  84. btScalar alpha = 0.01, beta = 0.5; // Boyd & Vandenberghe suggested alpha between 0.01 and 0.3, beta between 0.1 to 0.8
  85. btScalar scale = 2;
  86. btScalar f0 = m_objective->totalEnergy(solverdt) + kineticEnergy(), f1, f2;
  87. backupDv();
  88. do
  89. {
  90. scale *= beta;
  91. if (scale < 1e-8)
  92. {
  93. return;
  94. }
  95. updateEnergy(scale);
  96. f1 = m_objective->totalEnergy(solverdt) + kineticEnergy();
  97. f2 = f0 - alpha * scale * inner_product;
  98. } while (!(f1 < f2 + SIMD_EPSILON)); // if anything here is nan then the search continues
  99. revertDv();
  100. updateDv(scale);
  101. }
  102. else
  103. {
  104. computeStep(m_ddv, m_residual);
  105. updateDv();
  106. }
  107. for (int j = 0; j < m_numNodes; ++j)
  108. {
  109. m_ddv[j].setZero();
  110. m_residual[j].setZero();
  111. }
  112. }
  113. updateVelocity();
  114. }
  115. }
  116. btScalar btDeformableBodySolver::kineticEnergy()
  117. {
  118. btScalar ke = 0;
  119. for (int i = 0; i < m_softBodies.size(); ++i)
  120. {
  121. btSoftBody* psb = m_softBodies[i];
  122. for (int j = 0; j < psb->m_nodes.size(); ++j)
  123. {
  124. btSoftBody::Node& node = psb->m_nodes[j];
  125. if (node.m_im > 0)
  126. {
  127. ke += m_dv[node.index].length2() * 0.5 / node.m_im;
  128. }
  129. }
  130. }
  131. return ke;
  132. }
  133. void btDeformableBodySolver::backupDv()
  134. {
  135. m_backup_dv.resize(m_dv.size());
  136. for (int i = 0; i < m_backup_dv.size(); ++i)
  137. {
  138. m_backup_dv[i] = m_dv[i];
  139. }
  140. }
  141. void btDeformableBodySolver::revertDv()
  142. {
  143. for (int i = 0; i < m_backup_dv.size(); ++i)
  144. {
  145. m_dv[i] = m_backup_dv[i];
  146. }
  147. }
  148. void btDeformableBodySolver::updateEnergy(btScalar scale)
  149. {
  150. for (int i = 0; i < m_dv.size(); ++i)
  151. {
  152. m_dv[i] = m_backup_dv[i] + scale * m_ddv[i];
  153. }
  154. updateState();
  155. }
  156. btScalar btDeformableBodySolver::computeDescentStep(TVStack& ddv, const TVStack& residual, bool verbose)
  157. {
  158. m_cg.solve(*m_objective, ddv, residual, false);
  159. btScalar inner_product = m_cg.dot(residual, m_ddv);
  160. btScalar res_norm = m_objective->computeNorm(residual);
  161. btScalar tol = 1e-5 * res_norm * m_objective->computeNorm(m_ddv);
  162. if (inner_product < -tol)
  163. {
  164. if (verbose)
  165. {
  166. std::cout << "Looking backwards!" << std::endl;
  167. }
  168. for (int i = 0; i < m_ddv.size(); ++i)
  169. {
  170. m_ddv[i] = -m_ddv[i];
  171. }
  172. inner_product = -inner_product;
  173. }
  174. else if (std::abs(inner_product) < tol)
  175. {
  176. if (verbose)
  177. {
  178. std::cout << "Gradient Descent!" << std::endl;
  179. }
  180. btScalar scale = m_objective->computeNorm(m_ddv) / res_norm;
  181. for (int i = 0; i < m_ddv.size(); ++i)
  182. {
  183. m_ddv[i] = scale * residual[i];
  184. }
  185. inner_product = scale * res_norm * res_norm;
  186. }
  187. return inner_product;
  188. }
  189. void btDeformableBodySolver::updateState()
  190. {
  191. updateVelocity();
  192. updateTempPosition();
  193. }
  194. void btDeformableBodySolver::updateDv(btScalar scale)
  195. {
  196. for (int i = 0; i < m_numNodes; ++i)
  197. {
  198. m_dv[i] += scale * m_ddv[i];
  199. }
  200. }
  201. void btDeformableBodySolver::computeStep(TVStack& ddv, const TVStack& residual)
  202. {
  203. if (m_useProjection)
  204. m_cg.solve(*m_objective, ddv, residual, false);
  205. else
  206. m_cr.solve(*m_objective, ddv, residual, false);
  207. }
  208. void btDeformableBodySolver::reinitialize(const btAlignedObjectArray<btSoftBody*>& softBodies, btScalar dt)
  209. {
  210. m_softBodies.copyFromArray(softBodies);
  211. bool nodeUpdated = updateNodes();
  212. if (nodeUpdated)
  213. {
  214. m_dv.resize(m_numNodes, btVector3(0, 0, 0));
  215. m_ddv.resize(m_numNodes, btVector3(0, 0, 0));
  216. m_residual.resize(m_numNodes, btVector3(0, 0, 0));
  217. m_backupVelocity.resize(m_numNodes, btVector3(0, 0, 0));
  218. }
  219. // need to setZero here as resize only set value for newly allocated items
  220. for (int i = 0; i < m_numNodes; ++i)
  221. {
  222. m_dv[i].setZero();
  223. m_ddv[i].setZero();
  224. m_residual[i].setZero();
  225. }
  226. if (dt > 0)
  227. {
  228. m_dt = dt;
  229. }
  230. m_objective->reinitialize(nodeUpdated, dt);
  231. updateSoftBodies();
  232. }
  233. void btDeformableBodySolver::setConstraints(const btContactSolverInfo& infoGlobal)
  234. {
  235. BT_PROFILE("setConstraint");
  236. m_objective->setConstraints(infoGlobal);
  237. }
  238. btScalar btDeformableBodySolver::solveContactConstraints(btCollisionObject** deformableBodies, int numDeformableBodies, const btContactSolverInfo& infoGlobal)
  239. {
  240. BT_PROFILE("solveContactConstraints");
  241. btScalar maxSquaredResidual = m_objective->m_projection.update(deformableBodies, numDeformableBodies, infoGlobal);
  242. return maxSquaredResidual;
  243. }
  244. void btDeformableBodySolver::updateVelocity()
  245. {
  246. int counter = 0;
  247. for (int i = 0; i < m_softBodies.size(); ++i)
  248. {
  249. btSoftBody* psb = m_softBodies[i];
  250. psb->m_maxSpeedSquared = 0;
  251. if (!psb->isActive())
  252. {
  253. counter += psb->m_nodes.size();
  254. continue;
  255. }
  256. for (int j = 0; j < psb->m_nodes.size(); ++j)
  257. {
  258. // set NaN to zero;
  259. if (m_dv[counter] != m_dv[counter])
  260. {
  261. m_dv[counter].setZero();
  262. }
  263. if (m_implicit)
  264. {
  265. psb->m_nodes[j].m_v = m_backupVelocity[counter] + m_dv[counter];
  266. }
  267. else
  268. {
  269. psb->m_nodes[j].m_v = m_backupVelocity[counter] + m_dv[counter] - psb->m_nodes[j].m_splitv;
  270. }
  271. psb->m_maxSpeedSquared = btMax(psb->m_maxSpeedSquared, psb->m_nodes[j].m_v.length2());
  272. ++counter;
  273. }
  274. }
  275. }
  276. void btDeformableBodySolver::updateTempPosition()
  277. {
  278. int counter = 0;
  279. for (int i = 0; i < m_softBodies.size(); ++i)
  280. {
  281. btSoftBody* psb = m_softBodies[i];
  282. if (!psb->isActive())
  283. {
  284. counter += psb->m_nodes.size();
  285. continue;
  286. }
  287. for (int j = 0; j < psb->m_nodes.size(); ++j)
  288. {
  289. psb->m_nodes[j].m_q = psb->m_nodes[j].m_x + m_dt * (psb->m_nodes[j].m_v + psb->m_nodes[j].m_splitv);
  290. ++counter;
  291. }
  292. psb->updateDeformation();
  293. }
  294. }
  295. void btDeformableBodySolver::backupVelocity()
  296. {
  297. int counter = 0;
  298. for (int i = 0; i < m_softBodies.size(); ++i)
  299. {
  300. btSoftBody* psb = m_softBodies[i];
  301. for (int j = 0; j < psb->m_nodes.size(); ++j)
  302. {
  303. m_backupVelocity[counter++] = psb->m_nodes[j].m_v;
  304. }
  305. }
  306. }
  307. void btDeformableBodySolver::setupDeformableSolve(bool implicit)
  308. {
  309. int counter = 0;
  310. for (int i = 0; i < m_softBodies.size(); ++i)
  311. {
  312. btSoftBody* psb = m_softBodies[i];
  313. if (!psb->isActive())
  314. {
  315. counter += psb->m_nodes.size();
  316. continue;
  317. }
  318. for (int j = 0; j < psb->m_nodes.size(); ++j)
  319. {
  320. if (implicit)
  321. {
  322. // setting the initial guess for newton, need m_dv = v_{n+1} - v_n for dofs that are in constraint.
  323. if (psb->m_nodes[j].m_v == m_backupVelocity[counter])
  324. m_dv[counter].setZero();
  325. else
  326. m_dv[counter] = psb->m_nodes[j].m_v - psb->m_nodes[j].m_vn;
  327. m_backupVelocity[counter] = psb->m_nodes[j].m_vn;
  328. }
  329. else
  330. {
  331. m_dv[counter] = psb->m_nodes[j].m_v + psb->m_nodes[j].m_splitv - m_backupVelocity[counter];
  332. }
  333. psb->m_nodes[j].m_v = m_backupVelocity[counter];
  334. ++counter;
  335. }
  336. }
  337. }
  338. void btDeformableBodySolver::revertVelocity()
  339. {
  340. int counter = 0;
  341. for (int i = 0; i < m_softBodies.size(); ++i)
  342. {
  343. btSoftBody* psb = m_softBodies[i];
  344. for (int j = 0; j < psb->m_nodes.size(); ++j)
  345. {
  346. psb->m_nodes[j].m_v = m_backupVelocity[counter++];
  347. }
  348. }
  349. }
  350. bool btDeformableBodySolver::updateNodes()
  351. {
  352. int numNodes = 0;
  353. for (int i = 0; i < m_softBodies.size(); ++i)
  354. numNodes += m_softBodies[i]->m_nodes.size();
  355. if (numNodes != m_numNodes)
  356. {
  357. m_numNodes = numNodes;
  358. return true;
  359. }
  360. return false;
  361. }
  362. void btDeformableBodySolver::predictMotion(btScalar solverdt)
  363. {
  364. // apply explicit forces to velocity
  365. if (m_implicit)
  366. {
  367. for (int i = 0; i < m_softBodies.size(); ++i)
  368. {
  369. btSoftBody* psb = m_softBodies[i];
  370. if (psb->isActive())
  371. {
  372. for (int j = 0; j < psb->m_nodes.size(); ++j)
  373. {
  374. psb->m_nodes[j].m_q = psb->m_nodes[j].m_x + psb->m_nodes[j].m_v * solverdt;
  375. }
  376. }
  377. }
  378. }
  379. applyExplicitForce();
  380. for (int i = 0; i < m_softBodies.size(); ++i)
  381. {
  382. btSoftBody* psb = m_softBodies[i];
  383. if (psb->isActive())
  384. {
  385. /* Clear contacts when softbody is active*/
  386. psb->m_nodeRigidContacts.resize(0);
  387. psb->m_faceRigidContacts.resize(0);
  388. psb->m_faceNodeContacts.resize(0);
  389. psb->m_faceNodeContactsCCD.resize(0);
  390. // predict motion for collision detection
  391. predictDeformableMotion(psb, solverdt);
  392. }
  393. }
  394. }
  395. void btDeformableBodySolver::predictDeformableMotion(btSoftBody* psb, btScalar dt)
  396. {
  397. BT_PROFILE("btDeformableBodySolver::predictDeformableMotion");
  398. int i, ni;
  399. /* Update */
  400. if (psb->m_bUpdateRtCst)
  401. {
  402. psb->m_bUpdateRtCst = false;
  403. psb->updateConstants();
  404. psb->m_fdbvt.clear();
  405. if (psb->m_cfg.collisions & btSoftBody::fCollision::SDF_RD)
  406. {
  407. psb->initializeFaceTree();
  408. }
  409. }
  410. /* Prepare */
  411. psb->m_sst.sdt = dt * psb->m_cfg.timescale;
  412. psb->m_sst.isdt = 1 / psb->m_sst.sdt;
  413. psb->m_sst.velmrg = psb->m_sst.sdt * 3;
  414. psb->m_sst.radmrg = psb->getCollisionShape()->getMargin();
  415. psb->m_sst.updmrg = psb->m_sst.radmrg * (btScalar)0.25;
  416. /* Bounds */
  417. psb->updateBounds();
  418. /* Integrate */
  419. // do not allow particles to move more than the bounding box size
  420. btScalar max_v = (psb->m_bounds[1] - psb->m_bounds[0]).norm() / dt;
  421. for (i = 0, ni = psb->m_nodes.size(); i < ni; ++i)
  422. {
  423. btSoftBody::Node& n = psb->m_nodes[i];
  424. // apply drag
  425. n.m_v *= (1 - psb->m_cfg.drag);
  426. // scale velocity back
  427. if (m_implicit)
  428. {
  429. n.m_q = n.m_x;
  430. }
  431. else
  432. {
  433. if (n.m_v.norm() > max_v)
  434. {
  435. n.m_v.safeNormalize();
  436. n.m_v *= max_v;
  437. }
  438. n.m_q = n.m_x + n.m_v * dt;
  439. }
  440. n.m_splitv.setZero();
  441. n.m_constrained = false;
  442. }
  443. /* Nodes */
  444. psb->updateNodeTree(true, true);
  445. if (!psb->m_fdbvt.empty())
  446. {
  447. psb->updateFaceTree(true, true);
  448. }
  449. /* Optimize dbvt's */
  450. // psb->m_ndbvt.optimizeIncremental(1);
  451. // psb->m_fdbvt.optimizeIncremental(1);
  452. }
  453. void btDeformableBodySolver::updateSoftBodies()
  454. {
  455. BT_PROFILE("updateSoftBodies");
  456. for (int i = 0; i < m_softBodies.size(); i++)
  457. {
  458. btSoftBody* psb = (btSoftBody*)m_softBodies[i];
  459. if (psb->isActive())
  460. {
  461. psb->updateNormals();
  462. }
  463. }
  464. }
  465. void btDeformableBodySolver::setImplicit(bool implicit)
  466. {
  467. m_implicit = implicit;
  468. m_objective->setImplicit(implicit);
  469. }
  470. void btDeformableBodySolver::setLineSearch(bool lineSearch)
  471. {
  472. m_lineSearch = lineSearch;
  473. }
  474. void btDeformableBodySolver::applyExplicitForce()
  475. {
  476. m_objective->applyExplicitForce(m_residual);
  477. }
  478. void btDeformableBodySolver::applyTransforms(btScalar timeStep)
  479. {
  480. for (int i = 0; i < m_softBodies.size(); ++i)
  481. {
  482. btSoftBody* psb = m_softBodies[i];
  483. for (int j = 0; j < psb->m_nodes.size(); ++j)
  484. {
  485. btSoftBody::Node& node = psb->m_nodes[j];
  486. btScalar maxDisplacement = psb->getWorldInfo()->m_maxDisplacement;
  487. btScalar clampDeltaV = maxDisplacement / timeStep;
  488. for (int c = 0; c < 3; c++)
  489. {
  490. if (node.m_v[c] > clampDeltaV)
  491. {
  492. node.m_v[c] = clampDeltaV;
  493. }
  494. if (node.m_v[c] < -clampDeltaV)
  495. {
  496. node.m_v[c] = -clampDeltaV;
  497. }
  498. }
  499. node.m_x = node.m_x + timeStep * (node.m_v + node.m_splitv);
  500. node.m_q = node.m_x;
  501. node.m_vn = node.m_v;
  502. }
  503. // enforce anchor constraints
  504. for (int j = 0; j < psb->m_deformableAnchors.size(); ++j)
  505. {
  506. btSoftBody::DeformableNodeRigidAnchor& a = psb->m_deformableAnchors[j];
  507. btSoftBody::Node* n = a.m_node;
  508. n->m_x = a.m_cti.m_colObj->getWorldTransform() * a.m_local;
  509. // update multibody anchor info
  510. if (a.m_cti.m_colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK)
  511. {
  512. btMultiBodyLinkCollider* multibodyLinkCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(a.m_cti.m_colObj);
  513. if (multibodyLinkCol)
  514. {
  515. btVector3 nrm;
  516. const btCollisionShape* shp = multibodyLinkCol->getCollisionShape();
  517. const btTransform& wtr = multibodyLinkCol->getWorldTransform();
  518. psb->m_worldInfo->m_sparsesdf.Evaluate(
  519. wtr.invXform(n->m_x),
  520. shp,
  521. nrm,
  522. 0);
  523. a.m_cti.m_normal = wtr.getBasis() * nrm;
  524. btVector3 normal = a.m_cti.m_normal;
  525. btVector3 t1 = generateUnitOrthogonalVector(normal);
  526. btVector3 t2 = btCross(normal, t1);
  527. btMultiBodyJacobianData jacobianData_normal, jacobianData_t1, jacobianData_t2;
  528. findJacobian(multibodyLinkCol, jacobianData_normal, a.m_node->m_x, normal);
  529. findJacobian(multibodyLinkCol, jacobianData_t1, a.m_node->m_x, t1);
  530. findJacobian(multibodyLinkCol, jacobianData_t2, a.m_node->m_x, t2);
  531. btScalar* J_n = &jacobianData_normal.m_jacobians[0];
  532. btScalar* J_t1 = &jacobianData_t1.m_jacobians[0];
  533. btScalar* J_t2 = &jacobianData_t2.m_jacobians[0];
  534. btScalar* u_n = &jacobianData_normal.m_deltaVelocitiesUnitImpulse[0];
  535. btScalar* u_t1 = &jacobianData_t1.m_deltaVelocitiesUnitImpulse[0];
  536. btScalar* u_t2 = &jacobianData_t2.m_deltaVelocitiesUnitImpulse[0];
  537. btMatrix3x3 rot(normal.getX(), normal.getY(), normal.getZ(),
  538. t1.getX(), t1.getY(), t1.getZ(),
  539. t2.getX(), t2.getY(), t2.getZ()); // world frame to local frame
  540. const int ndof = multibodyLinkCol->m_multiBody->getNumDofs() + 6;
  541. btMatrix3x3 local_impulse_matrix = (Diagonal(n->m_im) + OuterProduct(J_n, J_t1, J_t2, u_n, u_t1, u_t2, ndof)).inverse();
  542. a.m_c0 = rot.transpose() * local_impulse_matrix * rot;
  543. a.jacobianData_normal = jacobianData_normal;
  544. a.jacobianData_t1 = jacobianData_t1;
  545. a.jacobianData_t2 = jacobianData_t2;
  546. a.t1 = t1;
  547. a.t2 = t2;
  548. }
  549. }
  550. }
  551. psb->interpolateRenderMesh();
  552. }
  553. }