b2Island.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*
  2. * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
  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 "b2Island.h"
  19. #include "b2Body.h"
  20. #include "b2World.h"
  21. #include "Contacts/b2Contact.h"
  22. #include "Contacts/b2ContactSolver.h"
  23. #include "Joints/b2Joint.h"
  24. #include "../Common/b2StackAllocator.h"
  25. /*
  26. Position Correction Notes
  27. =========================
  28. I tried the several algorithms for position correction of the 2D revolute joint.
  29. I looked at these systems:
  30. - simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s.
  31. - suspension bridge with 30 1m long planks of length 1m.
  32. - multi-link chain with 30 1m long links.
  33. Here are the algorithms:
  34. Baumgarte - A fraction of the position error is added to the velocity error. There is no
  35. separate position solver.
  36. Pseudo Velocities - After the velocity solver and position integration,
  37. the position error, Jacobian, and effective mass are recomputed. Then
  38. the velocity constraints are solved with pseudo velocities and a fraction
  39. of the position error is added to the pseudo velocity error. The pseudo
  40. velocities are initialized to zero and there is no warm-starting. After
  41. the position solver, the pseudo velocities are added to the positions.
  42. This is also called the First Order World method or the Position LCP method.
  43. Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the
  44. position error is re-computed for each constraint and the positions are updated
  45. after the constraint is solved. The radius vectors (aka Jacobians) are
  46. re-computed too (otherwise the algorithm has horrible instability). The pseudo
  47. velocity states are not needed because they are effectively zero at the beginning
  48. of each iteration. Since we have the current position error, we allow the
  49. iterations to terminate early if the error becomes smaller than b2_linearSlop.
  50. Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed
  51. each time a constraint is solved.
  52. Here are the results:
  53. Baumgarte - this is the cheapest algorithm but it has some stability problems,
  54. especially with the bridge. The chain links separate easily close to the root
  55. and they jitter as they struggle to pull together. This is one of the most common
  56. methods in the field. The big drawback is that the position correction artificially
  57. affects the momentum, thus leading to instabilities and false bounce. I used a
  58. bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller
  59. factor makes joints and contacts more spongy.
  60. Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is
  61. stable. However, joints still separate with large angular velocities. Drag the
  62. simple pendulum in a circle quickly and the joint will separate. The chain separates
  63. easily and does not recover. I used a bias factor of 0.2. A larger value lead to
  64. the bridge collapsing when a heavy cube drops on it.
  65. Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo
  66. Velocities, but in other ways it is worse. The bridge and chain are much more
  67. stable, but the simple pendulum goes unstable at high angular velocities.
  68. Full NGS - stable in all tests. The joints display good stiffness. The bridge
  69. still sags, but this is better than infinite forces.
  70. Recommendations
  71. Pseudo Velocities are not really worthwhile because the bridge and chain cannot
  72. recover from joint separation. In other cases the benefit over Baumgarte is small.
  73. Modified NGS is not a robust method for the revolute joint due to the violent
  74. instability seen in the simple pendulum. Perhaps it is viable with other constraint
  75. types, especially scalar constraints where the effective mass is a scalar.
  76. This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities
  77. and is very fast. I don't think we can escape Baumgarte, especially in highly
  78. demanding cases where high constraint fidelity is not needed.
  79. Full NGS is robust and easy on the eyes. I recommend this as an option for
  80. higher fidelity simulation and certainly for suspension bridges and long chains.
  81. Full NGS might be a good choice for ragdolls, especially motorized ragdolls where
  82. joint separation can be problematic. The number of NGS iterations can be reduced
  83. for better performance without harming robustness much.
  84. Each joint in a can be handled differently in the position solver. So I recommend
  85. a system where the user can select the algorithm on a per joint basis. I would
  86. probably default to the slower Full NGS and let the user select the faster
  87. Baumgarte method in performance critical scenarios.
  88. */
  89. /*
  90. Cache Performance
  91. The Box2D solvers are dominated by cache misses. Data structures are designed
  92. to increase the number of cache hits. Much of misses are due to random access
  93. to body data. The constraint structures are iterated over linearly, which leads
  94. to few cache misses.
  95. The bodies are not accessed during iteration. Instead read only data, such as
  96. the mass values are stored with the constraints. The mutable data are the constraint
  97. impulses and the bodies velocities/positions. The impulses are held inside the
  98. constraint structures. The body velocities/positions are held in compact, temporary
  99. arrays to increase the number of cache hits. Linear and angular velocity are
  100. stored in a single array since multiple arrays lead to multiple misses.
  101. */
  102. /*
  103. 2D Rotation
  104. R = [cos(theta) -sin(theta)]
  105. [sin(theta) cos(theta) ]
  106. thetaDot = omega
  107. Let q1 = cos(theta), q2 = sin(theta).
  108. R = [q1 -q2]
  109. [q2 q1]
  110. q1Dot = -thetaDot * q2
  111. q2Dot = thetaDot * q1
  112. q1_new = q1_old - dt * w * q2
  113. q2_new = q2_old + dt * w * q1
  114. then normalize.
  115. This might be faster than computing sin+cos.
  116. However, we can compute sin+cos of the same angle fast.
  117. */
  118. b2Island::b2Island(
  119. int32 bodyCapacity,
  120. int32 contactCapacity,
  121. int32 jointCapacity,
  122. b2StackAllocator* allocator,
  123. b2ContactListener* listener)
  124. {
  125. m_bodyCapacity = bodyCapacity;
  126. m_contactCapacity = contactCapacity;
  127. m_jointCapacity = jointCapacity;
  128. m_bodyCount = 0;
  129. m_contactCount = 0;
  130. m_jointCount = 0;
  131. m_allocator = allocator;
  132. m_listener = listener;
  133. m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*));
  134. m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*));
  135. m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*));
  136. m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity));
  137. m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position));
  138. }
  139. b2Island::~b2Island()
  140. {
  141. // Warning: the order should reverse the constructor order.
  142. m_allocator->Free(m_positions);
  143. m_allocator->Free(m_velocities);
  144. m_allocator->Free(m_joints);
  145. m_allocator->Free(m_contacts);
  146. m_allocator->Free(m_bodies);
  147. }
  148. void b2Island::Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep)
  149. {
  150. // Integrate velocities and apply damping.
  151. for (int32 i = 0; i < m_bodyCount; ++i)
  152. {
  153. b2Body* b = m_bodies[i];
  154. if (b->IsStatic())
  155. continue;
  156. // Integrate velocities.
  157. b->m_linearVelocity += step.dt * (gravity + b->m_invMass * b->m_force);
  158. b->m_angularVelocity += step.dt * b->m_invI * b->m_torque;
  159. // Reset forces.
  160. b->m_force.Set(0.0f, 0.0f);
  161. b->m_torque = 0.0f;
  162. // Apply damping.
  163. // ODE: dv/dt + c * v = 0
  164. // Solution: v(t) = v0 * exp(-c * t)
  165. // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
  166. // v2 = exp(-c * dt) * v1
  167. // Taylor expansion:
  168. // v2 = (1.0f - c * dt) * v1
  169. b->m_linearVelocity *= b2Clamp(1.0f - step.dt * b->m_linearDamping, 0.0f, 1.0f);
  170. b->m_angularVelocity *= b2Clamp(1.0f - step.dt * b->m_angularDamping, 0.0f, 1.0f);
  171. // Check for large velocities.
  172. #ifdef TARGET_FLOAT32_IS_FIXED
  173. // Fixed point code written this way to prevent
  174. // overflows, float code is optimized for speed
  175. float32 vMagnitude = b->m_linearVelocity.Length();
  176. if(vMagnitude > b2_maxLinearVelocity) {
  177. b->m_linearVelocity *= b2_maxLinearVelocity/vMagnitude;
  178. }
  179. b->m_angularVelocity = b2Clamp(b->m_angularVelocity,
  180. -b2_maxAngularVelocity, b2_maxAngularVelocity);
  181. #else
  182. if (b2Dot(b->m_linearVelocity, b->m_linearVelocity) > b2_maxLinearVelocitySquared)
  183. {
  184. b->m_linearVelocity.Normalize();
  185. b->m_linearVelocity *= b2_maxLinearVelocity;
  186. }
  187. if (b->m_angularVelocity * b->m_angularVelocity > b2_maxAngularVelocitySquared)
  188. {
  189. if (b->m_angularVelocity < 0.0f)
  190. {
  191. b->m_angularVelocity = -b2_maxAngularVelocity;
  192. }
  193. else
  194. {
  195. b->m_angularVelocity = b2_maxAngularVelocity;
  196. }
  197. }
  198. #endif
  199. }
  200. b2ContactSolver contactSolver(step, m_contacts, m_contactCount, m_allocator);
  201. // Initialize velocity constraints.
  202. contactSolver.InitVelocityConstraints(step);
  203. for (int32 i = 0; i < m_jointCount; ++i)
  204. {
  205. m_joints[i]->InitVelocityConstraints(step);
  206. }
  207. // Solve velocity constraints.
  208. for (int32 i = 0; i < step.velocityIterations; ++i)
  209. {
  210. for (int32 j = 0; j < m_jointCount; ++j)
  211. {
  212. m_joints[j]->SolveVelocityConstraints(step);
  213. }
  214. contactSolver.SolveVelocityConstraints();
  215. }
  216. // Post-solve (store impulses for warm starting).
  217. contactSolver.FinalizeVelocityConstraints();
  218. // Integrate positions.
  219. for (int32 i = 0; i < m_bodyCount; ++i)
  220. {
  221. b2Body* b = m_bodies[i];
  222. if (b->IsStatic())
  223. continue;
  224. // Store positions for continuous collision.
  225. b->m_sweep.c0 = b->m_sweep.c;
  226. b->m_sweep.a0 = b->m_sweep.a;
  227. // Integrate
  228. b->m_sweep.c += step.dt * b->m_linearVelocity;
  229. b->m_sweep.a += step.dt * b->m_angularVelocity;
  230. // Compute new transform
  231. b->SynchronizeTransform();
  232. // Note: shapes are synchronized later.
  233. }
  234. // Iterate over constraints.
  235. for (int32 i = 0; i < step.positionIterations; ++i)
  236. {
  237. bool contactsOkay = contactSolver.SolvePositionConstraints(b2_contactBaumgarte);
  238. bool jointsOkay = true;
  239. for (int32 i = 0; i < m_jointCount; ++i)
  240. {
  241. bool jointOkay = m_joints[i]->SolvePositionConstraints(b2_contactBaumgarte);
  242. jointsOkay = jointsOkay && jointOkay;
  243. }
  244. if (contactsOkay && jointsOkay)
  245. {
  246. // Exit early if the position errors are small.
  247. break;
  248. }
  249. }
  250. Report(contactSolver.m_constraints);
  251. if (allowSleep)
  252. {
  253. float32 minSleepTime = B2_FLT_MAX;
  254. #ifndef TARGET_FLOAT32_IS_FIXED
  255. const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance;
  256. const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance;
  257. #endif
  258. for (int32 i = 0; i < m_bodyCount; ++i)
  259. {
  260. b2Body* b = m_bodies[i];
  261. if (b->m_invMass == 0.0f)
  262. {
  263. continue;
  264. }
  265. if ((b->m_flags & b2Body::e_allowSleepFlag) == 0)
  266. {
  267. b->m_sleepTime = 0.0f;
  268. minSleepTime = 0.0f;
  269. }
  270. if ((b->m_flags & b2Body::e_allowSleepFlag) == 0 ||
  271. #ifdef TARGET_FLOAT32_IS_FIXED
  272. b2Abs(b->m_angularVelocity) > b2_angularSleepTolerance ||
  273. b2Abs(b->m_linearVelocity.x) > b2_linearSleepTolerance ||
  274. b2Abs(b->m_linearVelocity.y) > b2_linearSleepTolerance)
  275. #else
  276. b->m_angularVelocity * b->m_angularVelocity > angTolSqr ||
  277. b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr)
  278. #endif
  279. {
  280. b->m_sleepTime = 0.0f;
  281. minSleepTime = 0.0f;
  282. }
  283. else
  284. {
  285. b->m_sleepTime += step.dt;
  286. minSleepTime = b2Min(minSleepTime, b->m_sleepTime);
  287. }
  288. }
  289. if (minSleepTime >= b2_timeToSleep)
  290. {
  291. for (int32 i = 0; i < m_bodyCount; ++i)
  292. {
  293. b2Body* b = m_bodies[i];
  294. b->m_flags |= b2Body::e_sleepFlag;
  295. b->m_linearVelocity = b2Vec2_zero;
  296. b->m_angularVelocity = 0.0f;
  297. }
  298. }
  299. }
  300. }
  301. void b2Island::SolveTOI(b2TimeStep& subStep)
  302. {
  303. b2ContactSolver contactSolver(subStep, m_contacts, m_contactCount, m_allocator);
  304. // No warm starting needed for TOI contact events.
  305. // Warm starting for joints is off for now, but we need to
  306. // call this function to compute Jacobians.
  307. for (int32 i = 0; i < m_jointCount; ++i)
  308. {
  309. m_joints[i]->InitVelocityConstraints(subStep);
  310. }
  311. // Solve velocity constraints.
  312. for (int32 i = 0; i < subStep.velocityIterations; ++i)
  313. {
  314. contactSolver.SolveVelocityConstraints();
  315. for (int32 j = 0; j < m_jointCount; ++j)
  316. {
  317. m_joints[j]->SolveVelocityConstraints(subStep);
  318. }
  319. }
  320. // Don't store the TOI contact forces for warm starting
  321. // because they can be quite large.
  322. // Integrate positions.
  323. for (int32 i = 0; i < m_bodyCount; ++i)
  324. {
  325. b2Body* b = m_bodies[i];
  326. if (b->IsStatic())
  327. continue;
  328. // Store positions for continuous collision.
  329. b->m_sweep.c0 = b->m_sweep.c;
  330. b->m_sweep.a0 = b->m_sweep.a;
  331. // Integrate
  332. b->m_sweep.c += subStep.dt * b->m_linearVelocity;
  333. b->m_sweep.a += subStep.dt * b->m_angularVelocity;
  334. // Compute new transform
  335. b->SynchronizeTransform();
  336. // Note: shapes are synchronized later.
  337. }
  338. // Solve position constraints.
  339. const float32 k_toiBaumgarte = 0.75f;
  340. for (int32 i = 0; i < subStep.positionIterations; ++i)
  341. {
  342. bool contactsOkay = contactSolver.SolvePositionConstraints(k_toiBaumgarte);
  343. bool jointsOkay = true;
  344. for (int32 j = 0; j < m_jointCount; ++j)
  345. {
  346. bool jointOkay = m_joints[j]->SolvePositionConstraints(k_toiBaumgarte);
  347. jointsOkay = jointsOkay && jointOkay;
  348. }
  349. if (contactsOkay && jointsOkay)
  350. {
  351. break;
  352. }
  353. }
  354. Report(contactSolver.m_constraints);
  355. }
  356. void b2Island::Report(b2ContactConstraint* constraints)
  357. {
  358. if (m_listener == NULL)
  359. {
  360. return;
  361. }
  362. for (int32 i = 0; i < m_contactCount; ++i)
  363. {
  364. b2Contact* c = m_contacts[i];
  365. b2ContactConstraint* cc = constraints + i;
  366. b2ContactResult cr;
  367. cr.shape1 = c->GetShape1();
  368. cr.shape2 = c->GetShape2();
  369. b2Body* b1 = cr.shape1->GetBody();
  370. int32 manifoldCount = c->GetManifoldCount();
  371. b2Manifold* manifolds = c->GetManifolds();
  372. for (int32 j = 0; j < manifoldCount; ++j)
  373. {
  374. b2Manifold* manifold = manifolds + j;
  375. cr.normal = manifold->normal;
  376. for (int32 k = 0; k < manifold->pointCount; ++k)
  377. {
  378. b2ManifoldPoint* point = manifold->points + k;
  379. b2ContactConstraintPoint* ccp = cc->points + k;
  380. cr.position = b1->GetWorldPoint(point->localPoint1);
  381. // TOI constraint results are not stored, so get
  382. // the result from the constraint.
  383. cr.normalImpulse = ccp->normalImpulse;
  384. cr.tangentImpulse = ccp->tangentImpulse;
  385. cr.id = point->id;
  386. m_listener->Result(&cr);
  387. }
  388. }
  389. }
  390. }