b2Island.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /*
  2. * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * 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
  9. * freely, subject to the following restrictions:
  10. * 1. The origin of this software must not be misrepresented; you must not
  11. * claim that you wrote the original software. If you use this software
  12. * in a product, an acknowledgment in the product documentation would be
  13. * appreciated but is not required.
  14. * 2. Altered source versions must be plainly marked as such, and must not be
  15. * misrepresented as being the original software.
  16. * 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include <Box2D/Collision/b2Distance.h>
  19. #include <Box2D/Dynamics/b2Island.h>
  20. #include <Box2D/Dynamics/b2Body.h>
  21. #include <Box2D/Dynamics/b2Fixture.h>
  22. #include <Box2D/Dynamics/b2World.h>
  23. #include <Box2D/Dynamics/Contacts/b2Contact.h>
  24. #include <Box2D/Dynamics/Contacts/b2ContactSolver.h>
  25. #include <Box2D/Dynamics/Joints/b2Joint.h>
  26. #include <Box2D/Common/b2StackAllocator.h>
  27. #include <Box2D/Common/b2Timer.h>
  28. /*
  29. Position Correction Notes
  30. =========================
  31. I tried the several algorithms for position correction of the 2D revolute joint.
  32. I looked at these systems:
  33. - simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s.
  34. - suspension bridge with 30 1m long planks of length 1m.
  35. - multi-link chain with 30 1m long links.
  36. Here are the algorithms:
  37. Baumgarte - A fraction of the position error is added to the velocity error. There is no
  38. separate position solver.
  39. Pseudo Velocities - After the velocity solver and position integration,
  40. the position error, Jacobian, and effective mass are recomputed. Then
  41. the velocity constraints are solved with pseudo velocities and a fraction
  42. of the position error is added to the pseudo velocity error. The pseudo
  43. velocities are initialized to zero and there is no warm-starting. After
  44. the position solver, the pseudo velocities are added to the positions.
  45. This is also called the First Order World method or the Position LCP method.
  46. Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the
  47. position error is re-computed for each constraint and the positions are updated
  48. after the constraint is solved. The radius vectors (aka Jacobians) are
  49. re-computed too (otherwise the algorithm has horrible instability). The pseudo
  50. velocity states are not needed because they are effectively zero at the beginning
  51. of each iteration. Since we have the current position error, we allow the
  52. iterations to terminate early if the error becomes smaller than b2_linearSlop.
  53. Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed
  54. each time a constraint is solved.
  55. Here are the results:
  56. Baumgarte - this is the cheapest algorithm but it has some stability problems,
  57. especially with the bridge. The chain links separate easily close to the root
  58. and they jitter as they struggle to pull together. This is one of the most common
  59. methods in the field. The big drawback is that the position correction artificially
  60. affects the momentum, thus leading to instabilities and false bounce. I used a
  61. bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller
  62. factor makes joints and contacts more spongy.
  63. Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is
  64. stable. However, joints still separate with large angular velocities. Drag the
  65. simple pendulum in a circle quickly and the joint will separate. The chain separates
  66. easily and does not recover. I used a bias factor of 0.2. A larger value lead to
  67. the bridge collapsing when a heavy cube drops on it.
  68. Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo
  69. Velocities, but in other ways it is worse. The bridge and chain are much more
  70. stable, but the simple pendulum goes unstable at high angular velocities.
  71. Full NGS - stable in all tests. The joints display good stiffness. The bridge
  72. still sags, but this is better than infinite forces.
  73. Recommendations
  74. Pseudo Velocities are not really worthwhile because the bridge and chain cannot
  75. recover from joint separation. In other cases the benefit over Baumgarte is small.
  76. Modified NGS is not a robust method for the revolute joint due to the violent
  77. instability seen in the simple pendulum. Perhaps it is viable with other constraint
  78. types, especially scalar constraints where the effective mass is a scalar.
  79. This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities
  80. and is very fast. I don't think we can escape Baumgarte, especially in highly
  81. demanding cases where high constraint fidelity is not needed.
  82. Full NGS is robust and easy on the eyes. I recommend this as an option for
  83. higher fidelity simulation and certainly for suspension bridges and long chains.
  84. Full NGS might be a good choice for ragdolls, especially motorized ragdolls where
  85. joint separation can be problematic. The number of NGS iterations can be reduced
  86. for better performance without harming robustness much.
  87. Each joint in a can be handled differently in the position solver. So I recommend
  88. a system where the user can select the algorithm on a per joint basis. I would
  89. probably default to the slower Full NGS and let the user select the faster
  90. Baumgarte method in performance critical scenarios.
  91. */
  92. /*
  93. Cache Performance
  94. The Box2D solvers are dominated by cache misses. Data structures are designed
  95. to increase the number of cache hits. Much of misses are due to random access
  96. to body data. The constraint structures are iterated over linearly, which leads
  97. to few cache misses.
  98. The bodies are not accessed during iteration. Instead read only data, such as
  99. the mass values are stored with the constraints. The mutable data are the constraint
  100. impulses and the bodies velocities/positions. The impulses are held inside the
  101. constraint structures. The body velocities/positions are held in compact, temporary
  102. arrays to increase the number of cache hits. Linear and angular velocity are
  103. stored in a single array since multiple arrays lead to multiple misses.
  104. */
  105. /*
  106. 2D Rotation
  107. R = [cos(theta) -sin(theta)]
  108. [sin(theta) cos(theta) ]
  109. thetaDot = omega
  110. Let q1 = cos(theta), q2 = sin(theta).
  111. R = [q1 -q2]
  112. [q2 q1]
  113. q1Dot = -thetaDot * q2
  114. q2Dot = thetaDot * q1
  115. q1_new = q1_old - dt * w * q2
  116. q2_new = q2_old + dt * w * q1
  117. then normalize.
  118. This might be faster than computing sin+cos.
  119. However, we can compute sin+cos of the same angle fast.
  120. */
  121. b2Island::b2Island(
  122. int32 bodyCapacity,
  123. int32 contactCapacity,
  124. int32 jointCapacity,
  125. b2StackAllocator* allocator,
  126. b2ContactListener* listener)
  127. {
  128. m_bodyCapacity = bodyCapacity;
  129. m_contactCapacity = contactCapacity;
  130. m_jointCapacity = jointCapacity;
  131. m_bodyCount = 0;
  132. m_contactCount = 0;
  133. m_jointCount = 0;
  134. m_allocator = allocator;
  135. m_listener = listener;
  136. m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*));
  137. m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*));
  138. m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*));
  139. m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity));
  140. m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position));
  141. }
  142. b2Island::~b2Island()
  143. {
  144. // Warning: the order should reverse the constructor order.
  145. m_allocator->Free(m_positions);
  146. m_allocator->Free(m_velocities);
  147. m_allocator->Free(m_joints);
  148. m_allocator->Free(m_contacts);
  149. m_allocator->Free(m_bodies);
  150. }
  151. void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep)
  152. {
  153. b2Timer timer;
  154. float32 h = step.dt;
  155. // Integrate velocities and apply damping. Initialize the body state.
  156. for (int32 i = 0; i < m_bodyCount; ++i)
  157. {
  158. b2Body* b = m_bodies[i];
  159. b2Vec2 c = b->m_sweep.c;
  160. float32 a = b->m_sweep.a;
  161. b2Vec2 v = b->m_linearVelocity;
  162. float32 w = b->m_angularVelocity;
  163. // Store positions for continuous collision.
  164. b->m_sweep.c0 = b->m_sweep.c;
  165. b->m_sweep.a0 = b->m_sweep.a;
  166. if (b->m_type == b2_dynamicBody)
  167. {
  168. // Integrate velocities.
  169. v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force);
  170. w += h * b->m_invI * b->m_torque;
  171. // Apply damping.
  172. // ODE: dv/dt + c * v = 0
  173. // Solution: v(t) = v0 * exp(-c * t)
  174. // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
  175. // v2 = exp(-c * dt) * v1
  176. // Pade approximation:
  177. // v2 = v1 * 1 / (1 + c * dt)
  178. v *= 1.0f / (1.0f + h * b->m_linearDamping);
  179. w *= 1.0f / (1.0f + h * b->m_angularDamping);
  180. }
  181. m_positions[i].c = c;
  182. m_positions[i].a = a;
  183. m_velocities[i].v = v;
  184. m_velocities[i].w = w;
  185. }
  186. timer.Reset();
  187. // Solver data
  188. b2SolverData solverData;
  189. solverData.step = step;
  190. solverData.positions = m_positions;
  191. solverData.velocities = m_velocities;
  192. // Initialize velocity constraints.
  193. b2ContactSolverDef contactSolverDef;
  194. contactSolverDef.step = step;
  195. contactSolverDef.contacts = m_contacts;
  196. contactSolverDef.count = m_contactCount;
  197. contactSolverDef.positions = m_positions;
  198. contactSolverDef.velocities = m_velocities;
  199. contactSolverDef.allocator = m_allocator;
  200. b2ContactSolver contactSolver(&contactSolverDef);
  201. contactSolver.InitializeVelocityConstraints();
  202. if (step.warmStarting)
  203. {
  204. contactSolver.WarmStart();
  205. }
  206. for (int32 i = 0; i < m_jointCount; ++i)
  207. {
  208. m_joints[i]->InitVelocityConstraints(solverData);
  209. }
  210. profile->solveInit = timer.GetMilliseconds();
  211. // Solve velocity constraints
  212. timer.Reset();
  213. for (int32 i = 0; i < step.velocityIterations; ++i)
  214. {
  215. for (int32 j = 0; j < m_jointCount; ++j)
  216. {
  217. m_joints[j]->SolveVelocityConstraints(solverData);
  218. }
  219. contactSolver.SolveVelocityConstraints();
  220. }
  221. // Store impulses for warm starting
  222. contactSolver.StoreImpulses();
  223. profile->solveVelocity = timer.GetMilliseconds();
  224. // Integrate positions
  225. for (int32 i = 0; i < m_bodyCount; ++i)
  226. {
  227. b2Vec2 c = m_positions[i].c;
  228. float32 a = m_positions[i].a;
  229. b2Vec2 v = m_velocities[i].v;
  230. float32 w = m_velocities[i].w;
  231. // Check for large velocities
  232. b2Vec2 translation = h * v;
  233. if (b2Dot(translation, translation) > b2_maxTranslationSquared)
  234. {
  235. float32 ratio = b2_maxTranslation / translation.Length();
  236. v *= ratio;
  237. }
  238. float32 rotation = h * w;
  239. if (rotation * rotation > b2_maxRotationSquared)
  240. {
  241. float32 ratio = b2_maxRotation / b2Abs(rotation);
  242. w *= ratio;
  243. }
  244. // Integrate
  245. c += h * v;
  246. a += h * w;
  247. m_positions[i].c = c;
  248. m_positions[i].a = a;
  249. m_velocities[i].v = v;
  250. m_velocities[i].w = w;
  251. }
  252. // Solve position constraints
  253. timer.Reset();
  254. bool positionSolved = false;
  255. for (int32 i = 0; i < step.positionIterations; ++i)
  256. {
  257. bool contactsOkay = contactSolver.SolvePositionConstraints();
  258. bool jointsOkay = true;
  259. for (int32 i = 0; i < m_jointCount; ++i)
  260. {
  261. bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData);
  262. jointsOkay = jointsOkay && jointOkay;
  263. }
  264. if (contactsOkay && jointsOkay)
  265. {
  266. // Exit early if the position errors are small.
  267. positionSolved = true;
  268. break;
  269. }
  270. }
  271. // Copy state buffers back to the bodies
  272. for (int32 i = 0; i < m_bodyCount; ++i)
  273. {
  274. b2Body* body = m_bodies[i];
  275. body->m_sweep.c = m_positions[i].c;
  276. body->m_sweep.a = m_positions[i].a;
  277. body->m_linearVelocity = m_velocities[i].v;
  278. body->m_angularVelocity = m_velocities[i].w;
  279. body->SynchronizeTransform();
  280. }
  281. profile->solvePosition = timer.GetMilliseconds();
  282. Report(contactSolver.m_velocityConstraints);
  283. if (allowSleep)
  284. {
  285. float32 minSleepTime = b2_maxFloat;
  286. const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance;
  287. const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance;
  288. for (int32 i = 0; i < m_bodyCount; ++i)
  289. {
  290. b2Body* b = m_bodies[i];
  291. if (b->GetType() == b2_staticBody)
  292. {
  293. continue;
  294. }
  295. if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 ||
  296. b->m_angularVelocity * b->m_angularVelocity > angTolSqr ||
  297. b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr)
  298. {
  299. b->m_sleepTime = 0.0f;
  300. minSleepTime = 0.0f;
  301. }
  302. else
  303. {
  304. b->m_sleepTime += h;
  305. minSleepTime = b2Min(minSleepTime, b->m_sleepTime);
  306. }
  307. }
  308. if (minSleepTime >= b2_timeToSleep && positionSolved)
  309. {
  310. for (int32 i = 0; i < m_bodyCount; ++i)
  311. {
  312. b2Body* b = m_bodies[i];
  313. b->SetAwake(false);
  314. }
  315. }
  316. }
  317. }
  318. void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB)
  319. {
  320. b2Assert(toiIndexA < m_bodyCount);
  321. b2Assert(toiIndexB < m_bodyCount);
  322. // Initialize the body state.
  323. for (int32 i = 0; i < m_bodyCount; ++i)
  324. {
  325. b2Body* b = m_bodies[i];
  326. m_positions[i].c = b->m_sweep.c;
  327. m_positions[i].a = b->m_sweep.a;
  328. m_velocities[i].v = b->m_linearVelocity;
  329. m_velocities[i].w = b->m_angularVelocity;
  330. }
  331. b2ContactSolverDef contactSolverDef;
  332. contactSolverDef.contacts = m_contacts;
  333. contactSolverDef.count = m_contactCount;
  334. contactSolverDef.allocator = m_allocator;
  335. contactSolverDef.step = subStep;
  336. contactSolverDef.positions = m_positions;
  337. contactSolverDef.velocities = m_velocities;
  338. b2ContactSolver contactSolver(&contactSolverDef);
  339. // Solve position constraints.
  340. for (int32 i = 0; i < subStep.positionIterations; ++i)
  341. {
  342. bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB);
  343. if (contactsOkay)
  344. {
  345. break;
  346. }
  347. }
  348. #if 0
  349. // Is the new position really safe?
  350. for (int32 i = 0; i < m_contactCount; ++i)
  351. {
  352. b2Contact* c = m_contacts[i];
  353. b2Fixture* fA = c->GetFixtureA();
  354. b2Fixture* fB = c->GetFixtureB();
  355. b2Body* bA = fA->GetBody();
  356. b2Body* bB = fB->GetBody();
  357. int32 indexA = c->GetChildIndexA();
  358. int32 indexB = c->GetChildIndexB();
  359. b2DistanceInput input;
  360. input.proxyA.Set(fA->GetShape(), indexA);
  361. input.proxyB.Set(fB->GetShape(), indexB);
  362. input.transformA = bA->GetTransform();
  363. input.transformB = bB->GetTransform();
  364. input.useRadii = false;
  365. b2DistanceOutput output;
  366. b2SimplexCache cache;
  367. cache.count = 0;
  368. b2Distance(&output, &cache, &input);
  369. if (output.distance == 0 || cache.count == 3)
  370. {
  371. cache.count += 0;
  372. }
  373. }
  374. #endif
  375. // Leap of faith to new safe state.
  376. m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c;
  377. m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a;
  378. m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c;
  379. m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a;
  380. // No warm starting is needed for TOI events because warm
  381. // starting impulses were applied in the discrete solver.
  382. contactSolver.InitializeVelocityConstraints();
  383. // Solve velocity constraints.
  384. for (int32 i = 0; i < subStep.velocityIterations; ++i)
  385. {
  386. contactSolver.SolveVelocityConstraints();
  387. }
  388. // Don't store the TOI contact forces for warm starting
  389. // because they can be quite large.
  390. float32 h = subStep.dt;
  391. // Integrate positions
  392. for (int32 i = 0; i < m_bodyCount; ++i)
  393. {
  394. b2Vec2 c = m_positions[i].c;
  395. float32 a = m_positions[i].a;
  396. b2Vec2 v = m_velocities[i].v;
  397. float32 w = m_velocities[i].w;
  398. // Check for large velocities
  399. b2Vec2 translation = h * v;
  400. if (b2Dot(translation, translation) > b2_maxTranslationSquared)
  401. {
  402. float32 ratio = b2_maxTranslation / translation.Length();
  403. v *= ratio;
  404. }
  405. float32 rotation = h * w;
  406. if (rotation * rotation > b2_maxRotationSquared)
  407. {
  408. float32 ratio = b2_maxRotation / b2Abs(rotation);
  409. w *= ratio;
  410. }
  411. // Integrate
  412. c += h * v;
  413. a += h * w;
  414. m_positions[i].c = c;
  415. m_positions[i].a = a;
  416. m_velocities[i].v = v;
  417. m_velocities[i].w = w;
  418. // Sync bodies
  419. b2Body* body = m_bodies[i];
  420. body->m_sweep.c = c;
  421. body->m_sweep.a = a;
  422. body->m_linearVelocity = v;
  423. body->m_angularVelocity = w;
  424. body->SynchronizeTransform();
  425. }
  426. Report(contactSolver.m_velocityConstraints);
  427. }
  428. void b2Island::Report(const b2ContactVelocityConstraint* constraints)
  429. {
  430. if (m_listener == NULL)
  431. {
  432. return;
  433. }
  434. for (int32 i = 0; i < m_contactCount; ++i)
  435. {
  436. b2Contact* c = m_contacts[i];
  437. const b2ContactVelocityConstraint* vc = constraints + i;
  438. b2ContactImpulse impulse;
  439. impulse.count = vc->pointCount;
  440. for (int32 j = 0; j < vc->pointCount; ++j)
  441. {
  442. impulse.normalImpulses[j] = vc->points[j].normalImpulse;
  443. impulse.tangentImpulses[j] = vc->points[j].tangentImpulse;
  444. }
  445. m_listener->PostSolve(c, &impulse);
  446. }
  447. }