Advertisement
Tarferi

Box2D Amalgamate

Sep 30th, 2023 (edited)
957
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 602.66 KB | Source Code | 0 0
  1. // Box2D Amalgamate
  2. // Usage: Include this header file for definition, define "BOX2D_IMPL" for implementation.
  3.  
  4.  
  5. // MIT License
  6.  
  7. // Copyright (c) 2019 Erin Catto
  8.  
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15.  
  16. // The above copyright notice and this permission notice shall be included in all
  17. // copies or substantial portions of the Software.
  18.  
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. // SOFTWARE.
  26.  
  27. #ifndef B2_API_H
  28. #define B2_API_H
  29.  
  30. #ifdef B2_SHARED
  31. #if defined _WIN32 || defined __CYGWIN__
  32. #ifdef box2d_EXPORTS
  33. #ifdef __GNUC__
  34. #define B2_API __attribute__ ((dllexport))
  35. #else
  36. #define B2_API __declspec(dllexport)
  37. #endif
  38. #else
  39. #ifdef __GNUC__
  40. #define B2_API __attribute__ ((dllimport))
  41. #else
  42. #define B2_API __declspec(dllimport)
  43. #endif
  44. #endif
  45. #else
  46. #if __GNUC__ >= 4
  47. #define B2_API __attribute__ ((visibility ("default")))
  48. #else
  49. #define B2_API
  50. #endif
  51. #endif
  52. #else
  53. #define B2_API
  54. #endif
  55.  
  56. #endif
  57. // MIT License
  58.  
  59. // Copyright (c) 2020 Erin Catto
  60.  
  61. // Permission is hereby granted, free of charge, to any person obtaining a copy
  62. // of this software and associated documentation files (the "Software"), to deal
  63. // in the Software without restriction, including without limitation the rights
  64. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  65. // copies of the Software, and to permit persons to whom the Software is
  66. // furnished to do so, subject to the following conditions:
  67.  
  68. // The above copyright notice and this permission notice shall be included in all
  69. // copies or substantial portions of the Software.
  70.  
  71. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  72. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  73. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  74. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  75. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  76. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  77. // SOFTWARE.
  78.  
  79. #ifndef B2_TYPES_H
  80. #define B2_TYPES_H
  81.  
  82. typedef signed char int8;
  83. typedef signed short int16;
  84. typedef signed int int32;
  85. typedef unsigned char uint8;
  86. typedef unsigned short uint16;
  87. typedef unsigned int uint32;
  88.  
  89. #endif
  90. // MIT License
  91.  
  92. // Copyright (c) 2019 Erin Catto
  93.  
  94. // Permission is hereby granted, free of charge, to any person obtaining a copy
  95. // of this software and associated documentation files (the "Software"), to deal
  96. // in the Software without restriction, including without limitation the rights
  97. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  98. // copies of the Software, and to permit persons to whom the Software is
  99. // furnished to do so, subject to the following conditions:
  100.  
  101. // The above copyright notice and this permission notice shall be included in all
  102. // copies or substantial portions of the Software.
  103.  
  104. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  105. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  106. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  107. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  108. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  109. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  110. // SOFTWARE.
  111.  
  112. #ifndef B2_SETTINGS_H
  113. #define B2_SETTINGS_H
  114.  
  115. //#include "b2_types.h"
  116. //#include "b2_api.h"
  117.  
  118. /// @file
  119. /// Settings that can be overriden for your application
  120. ///
  121.  
  122. /// Define this macro in your build if you want to override settings
  123. #ifdef B2_USER_SETTINGS
  124.  
  125. /// This is a user file that includes custom definitions of the macros, structs, and functions
  126. /// defined below.
  127. //#include "b2_user_settings.h"
  128.  
  129. #else
  130.  
  131. #include <stdarg.h>
  132. #include <stdint.h>
  133.  
  134. // Tunable Constants
  135.  
  136. /// You can use this to change the length scale used by your game.
  137. /// For example for inches you could use 39.4.
  138. #define b2_lengthUnitsPerMeter 1.0f
  139.  
  140. /// The maximum number of vertices on a convex polygon. You cannot increase
  141. /// this too much because b2BlockAllocator has a maximum object size.
  142. #define b2_maxPolygonVertices   8
  143.  
  144. // User data
  145.  
  146. /// You can define this to inject whatever data you want in b2Body
  147. struct B2_API b2BodyUserData {
  148.     b2BodyUserData() {
  149.         pointer = 0;
  150.     }
  151.  
  152.     /// For legacy compatibility
  153.     uintptr_t pointer;
  154. };
  155.  
  156. /// You can define this to inject whatever data you want in b2Fixture
  157. struct B2_API b2FixtureUserData {
  158.     b2FixtureUserData() {
  159.         pointer = 0;
  160.     }
  161.  
  162.     /// For legacy compatibility
  163.     uintptr_t pointer;
  164. };
  165.  
  166. /// You can define this to inject whatever data you want in b2Joint
  167. struct B2_API b2JointUserData {
  168.     b2JointUserData() {
  169.         pointer = 0;
  170.     }
  171.  
  172.     /// For legacy compatibility
  173.     uintptr_t pointer;
  174. };
  175.  
  176. // Memory Allocation
  177.  
  178. /// Default allocation functions
  179. B2_API void* b2Alloc_Default(int32 size);
  180. B2_API void b2Free_Default(void* mem);
  181.  
  182. /// Implement this function to use your own memory allocator.
  183. inline void* b2Alloc(int32 size) {
  184.     return b2Alloc_Default(size);
  185. }
  186.  
  187. /// If you implement b2Alloc, you should also implement this function.
  188. inline void b2Free(void* mem) {
  189.     b2Free_Default(mem);
  190. }
  191.  
  192. /// Default logging function
  193. B2_API void b2Log_Default(const char* string, va_list args);
  194.  
  195. /// Implement this to use your own logging.
  196. inline void b2Log(const char* string, ...) {
  197.     va_list args;
  198.     va_start(args, string);
  199.     b2Log_Default(string, args);
  200.     va_end(args);
  201. }
  202.  
  203.  
  204. /// The radius of the polygon/edge shape skin. This should not be modified. Making
  205. /// this smaller means polygons will have an insufficient buffer for continuous collision.
  206. /// Making it larger may create artifacts for vertex collision.
  207. #define b2_polygonRadius        (2.0f * b2_linearSlop)
  208.  
  209.  
  210. #endif // B2_USER_SETTINGS
  211.  
  212. //#include "b2_common.h"
  213.  
  214. #endif
  215. // MIT License
  216.  
  217. // Copyright (c) 2019 Erin Catto
  218.  
  219. // Permission is hereby granted, free of charge, to any person obtaining a copy
  220. // of this software and associated documentation files (the "Software"), to deal
  221. // in the Software without restriction, including without limitation the rights
  222. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  223. // copies of the Software, and to permit persons to whom the Software is
  224. // furnished to do so, subject to the following conditions:
  225.  
  226. // The above copyright notice and this permission notice shall be included in all
  227. // copies or substantial portions of the Software.
  228.  
  229. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  230. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  231. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  232. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  233. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  234. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  235. // SOFTWARE.
  236.  
  237. #ifndef B2_STACK_ALLOCATOR_H
  238. #define B2_STACK_ALLOCATOR_H
  239.  
  240. //#include "b2_api.h"
  241. //#include "b2_settings.h"
  242.  
  243. const int32 b2_stackSize = 100 * 1024;  // 100k
  244. const int32 b2_maxStackEntries = 32;
  245.  
  246. struct B2_API b2StackEntry {
  247.     char* data;
  248.     int32 size;
  249.     bool usedMalloc;
  250. };
  251.  
  252. // This is a stack allocator used for fast per step allocations.
  253. // You must nest allocate/free pairs. The code will assert
  254. // if you try to interleave multiple allocate/free pairs.
  255. class B2_API b2StackAllocator {
  256. public:
  257.     b2StackAllocator();
  258.     ~b2StackAllocator();
  259.  
  260.     void* Allocate(int32 size);
  261.     void Free(void* p);
  262.  
  263.     int32 GetMaxAllocation() const;
  264.  
  265. private:
  266.  
  267.     char m_data[b2_stackSize];
  268.     int32 m_index;
  269.  
  270.     int32 m_allocation;
  271.     int32 m_maxAllocation;
  272.  
  273.     b2StackEntry m_entries[b2_maxStackEntries];
  274.     int32 m_entryCount;
  275. };
  276.  
  277. #endif
  278. // MIT License
  279.  
  280. // Copyright (c) 2019 Erin Catto
  281.  
  282. // Permission is hereby granted, free of charge, to any person obtaining a copy
  283. // of this software and associated documentation files (the "Software"), to deal
  284. // in the Software without restriction, including without limitation the rights
  285. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  286. // copies of the Software, and to permit persons to whom the Software is
  287. // furnished to do so, subject to the following conditions:
  288.  
  289. // The above copyright notice and this permission notice shall be included in all
  290. // copies or substantial portions of the Software.
  291.  
  292. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  293. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  294. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  295. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  296. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  297. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  298. // SOFTWARE.
  299.  
  300. #ifndef B2_BLOCK_ALLOCATOR_H
  301. #define B2_BLOCK_ALLOCATOR_H
  302.  
  303. //#include "b2_api.h"
  304. //#include "b2_settings.h"
  305.  
  306. const int32 b2_blockSizeCount = 14;
  307.  
  308. struct b2Block;
  309. struct b2Chunk;
  310.  
  311. /// This is a small object allocator used for allocating small
  312. /// objects that persist for more than one time step.
  313. /// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp
  314. class B2_API b2BlockAllocator {
  315. public:
  316.     b2BlockAllocator();
  317.     ~b2BlockAllocator();
  318.  
  319.     /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize.
  320.     void* Allocate(int32 size);
  321.  
  322.     /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize.
  323.     void Free(void* p, int32 size);
  324.  
  325.     void Clear();
  326.  
  327. private:
  328.  
  329.     b2Chunk* m_chunks;
  330.     int32 m_chunkCount;
  331.     int32 m_chunkSpace;
  332.  
  333.     b2Block* m_freeLists[b2_blockSizeCount];
  334. };
  335.  
  336. #endif
  337. // MIT License
  338.  
  339. // Copyright (c) 2019 Erin Catto
  340.  
  341. // Permission is hereby granted, free of charge, to any person obtaining a copy
  342. // of this software and associated documentation files (the "Software"), to deal
  343. // in the Software without restriction, including without limitation the rights
  344. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  345. // copies of the Software, and to permit persons to whom the Software is
  346. // furnished to do so, subject to the following conditions:
  347.  
  348. // The above copyright notice and this permission notice shall be included in all
  349. // copies or substantial portions of the Software.
  350.  
  351. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  352. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  353. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  354. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  355. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  356. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  357. // SOFTWARE.
  358.  
  359. #ifndef B2_MATH_H
  360. #define B2_MATH_H
  361.  
  362. #include <math.h>
  363. #include <stddef.h>
  364. #include <assert.h>
  365. #include <float.h>
  366.  
  367. #if !defined(NDEBUG)
  368. #define b2DEBUG
  369. #endif
  370.  
  371. #define B2_NOT_USED(x) ((void)(x))
  372. #define b2Assert(A) assert(A)
  373.  
  374. #define b2_maxFloat     FLT_MAX
  375. #define b2_epsilon      FLT_EPSILON
  376. #define b2_pi           3.14159265359f
  377.  
  378.  
  379.  
  380. /// This is used to fatten AABBs in the dynamic tree. This allows proxies
  381. /// to move by a small amount without triggering a tree adjustment.
  382. /// This is in meters.
  383. #define b2_aabbExtension        (0.1f * b2_lengthUnitsPerMeter)
  384.  
  385. /// This is used to fatten AABBs in the dynamic tree. This is used to predict
  386. /// the future position based on the current displacement.
  387. /// This is a dimensionless multiplier.
  388. #define b2_aabbMultiplier       4.0f
  389.  
  390. /// A small length used as a collision and constraint tolerance. Usually it is
  391. /// chosen to be numerically significant, but visually insignificant. In meters.
  392. #define b2_linearSlop           (0.005f * b2_lengthUnitsPerMeter)
  393.  
  394. /// A small angle used as a collision and constraint tolerance. Usually it is
  395. /// chosen to be numerically significant, but visually insignificant.
  396. #define b2_angularSlop          (2.0f / 180.0f * b2_pi)
  397.  
  398. /// Maximum number of sub-steps per contact in continuous physics simulation.
  399. #define b2_maxSubSteps          8
  400.  
  401.  
  402. /// The maximum number of contact points between two convex shapes. Do
  403. /// not change this value.
  404. #define b2_maxManifoldPoints    2
  405.  
  406. //#include "b2_api.h"
  407. //#include "b2_settings.h"
  408.  
  409. /// This function is used to ensure that a floating point number is not a NaN or infinity.
  410. inline bool b2IsValid(float x) {
  411.     return isfinite(x);
  412. }
  413.  
  414. #define b2Sqrt(x)   sqrtf(x)
  415. #define b2Atan2(y, x)   atan2f(y, x)
  416.  
  417. /// A 2D column vector.
  418. struct B2_API b2Vec2 {
  419.     /// Default constructor does nothing (for performance).
  420.     b2Vec2() {}
  421.  
  422.     /// Construct using coordinates.
  423.     b2Vec2(float xIn, float yIn) : x(xIn), y(yIn) {}
  424.  
  425.     /// Set this vector to all zeros.
  426.     void SetZero() { x = 0.0f; y = 0.0f; }
  427.  
  428.     /// Set this vector to some specified coordinates.
  429.     void Set(float x_, float y_) { x = x_; y = y_; }
  430.  
  431.     /// Negate this vector.
  432.     b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; }
  433.  
  434.     /// Read from and indexed element.
  435.     float operator () (int32 i) const {
  436.         return (&x)[i];
  437.     }
  438.  
  439.     /// Write to an indexed element.
  440.     float& operator () (int32 i) {
  441.         return (&x)[i];
  442.     }
  443.  
  444.     /// Add a vector to this vector.
  445.     void operator += (const b2Vec2& v) {
  446.         x += v.x; y += v.y;
  447.     }
  448.  
  449.     /// Subtract a vector from this vector.
  450.     void operator -= (const b2Vec2& v) {
  451.         x -= v.x; y -= v.y;
  452.     }
  453.  
  454.     /// Multiply this vector by a scalar.
  455.     void operator *= (float a) {
  456.         x *= a; y *= a;
  457.     }
  458.  
  459.     /// Get the length of this vector (the norm).
  460.     float Length() const {
  461.         return b2Sqrt(x * x + y * y);
  462.     }
  463.  
  464.     /// Get the length squared. For performance, use this instead of
  465.     /// b2Vec2::Length (if possible).
  466.     float LengthSquared() const {
  467.         return x * x + y * y;
  468.     }
  469.  
  470.     /// Convert this vector into a unit vector. Returns the length.
  471.     float Normalize() {
  472.         float length = Length();
  473.         if (length < b2_epsilon) {
  474.             return 0.0f;
  475.         }
  476.         float invLength = 1.0f / length;
  477.         x *= invLength;
  478.         y *= invLength;
  479.  
  480.         return length;
  481.     }
  482.  
  483.     /// Does this vector contain finite coordinates?
  484.     bool IsValid() const {
  485.         return b2IsValid(x) && b2IsValid(y);
  486.     }
  487.  
  488.     /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other)
  489.     b2Vec2 Skew() const {
  490.         return b2Vec2(-y, x);
  491.     }
  492.  
  493.     float x, y;
  494. };
  495.  
  496. /// A 2D column vector with 3 elements.
  497. struct B2_API b2Vec3 {
  498.     /// Default constructor does nothing (for performance).
  499.     b2Vec3() {}
  500.  
  501.     /// Construct using coordinates.
  502.     b2Vec3(float xIn, float yIn, float zIn) : x(xIn), y(yIn), z(zIn) {}
  503.  
  504.     /// Set this vector to all zeros.
  505.     void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; }
  506.  
  507.     /// Set this vector to some specified coordinates.
  508.     void Set(float x_, float y_, float z_) { x = x_; y = y_; z = z_; }
  509.  
  510.     /// Negate this vector.
  511.     b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; }
  512.  
  513.     /// Add a vector to this vector.
  514.     void operator += (const b2Vec3& v) {
  515.         x += v.x; y += v.y; z += v.z;
  516.     }
  517.  
  518.     /// Subtract a vector from this vector.
  519.     void operator -= (const b2Vec3& v) {
  520.         x -= v.x; y -= v.y; z -= v.z;
  521.     }
  522.  
  523.     /// Multiply this vector by a scalar.
  524.     void operator *= (float s) {
  525.         x *= s; y *= s; z *= s;
  526.     }
  527.  
  528.     float x, y, z;
  529. };
  530.  
  531. /// A 2-by-2 matrix. Stored in column-major order.
  532. struct B2_API b2Mat22 {
  533.     /// The default constructor does nothing (for performance).
  534.     b2Mat22() {}
  535.  
  536.     /// Construct this matrix using columns.
  537.     b2Mat22(const b2Vec2& c1, const b2Vec2& c2) {
  538.         ex = c1;
  539.         ey = c2;
  540.     }
  541.  
  542.     /// Construct this matrix using scalars.
  543.     b2Mat22(float a11, float a12, float a21, float a22) {
  544.         ex.x = a11; ex.y = a21;
  545.         ey.x = a12; ey.y = a22;
  546.     }
  547.  
  548.     /// Initialize this matrix using columns.
  549.     void Set(const b2Vec2& c1, const b2Vec2& c2) {
  550.         ex = c1;
  551.         ey = c2;
  552.     }
  553.  
  554.     /// Set this to the identity matrix.
  555.     void SetIdentity() {
  556.         ex.x = 1.0f; ey.x = 0.0f;
  557.         ex.y = 0.0f; ey.y = 1.0f;
  558.     }
  559.  
  560.     /// Set this matrix to all zeros.
  561.     void SetZero() {
  562.         ex.x = 0.0f; ey.x = 0.0f;
  563.         ex.y = 0.0f; ey.y = 0.0f;
  564.     }
  565.  
  566.     b2Mat22 GetInverse() const {
  567.         float a = ex.x, b = ey.x, c = ex.y, d = ey.y;
  568.         b2Mat22 B;
  569.         float det = a * d - b * c;
  570.         if (det != 0.0f) {
  571.             det = 1.0f / det;
  572.         }
  573.         B.ex.x = det * d;   B.ey.x = -det * b;
  574.         B.ex.y = -det * c;  B.ey.y = det * a;
  575.         return B;
  576.     }
  577.  
  578.     /// Solve A * x = b, where b is a column vector. This is more efficient
  579.     /// than computing the inverse in one-shot cases.
  580.     b2Vec2 Solve(const b2Vec2& b) const {
  581.         float a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y;
  582.         float det = a11 * a22 - a12 * a21;
  583.         if (det != 0.0f) {
  584.             det = 1.0f / det;
  585.         }
  586.         b2Vec2 x;
  587.         x.x = det * (a22 * b.x - a12 * b.y);
  588.         x.y = det * (a11 * b.y - a21 * b.x);
  589.         return x;
  590.     }
  591.  
  592.     b2Vec2 ex, ey;
  593. };
  594.  
  595. /// A 3-by-3 matrix. Stored in column-major order.
  596. struct B2_API b2Mat33 {
  597.     /// The default constructor does nothing (for performance).
  598.     b2Mat33() {}
  599.  
  600.     /// Construct this matrix using columns.
  601.     b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) {
  602.         ex = c1;
  603.         ey = c2;
  604.         ez = c3;
  605.     }
  606.  
  607.     /// Set this matrix to all zeros.
  608.     void SetZero() {
  609.         ex.SetZero();
  610.         ey.SetZero();
  611.         ez.SetZero();
  612.     }
  613.  
  614.     /// Solve A * x = b, where b is a column vector. This is more efficient
  615.     /// than computing the inverse in one-shot cases.
  616.     b2Vec3 Solve33(const b2Vec3& b) const;
  617.  
  618.     /// Solve A * x = b, where b is a column vector. This is more efficient
  619.     /// than computing the inverse in one-shot cases. Solve only the upper
  620.     /// 2-by-2 matrix equation.
  621.     b2Vec2 Solve22(const b2Vec2& b) const;
  622.  
  623.     /// Get the inverse of this matrix as a 2-by-2.
  624.     /// Returns the zero matrix if singular.
  625.     void GetInverse22(b2Mat33* M) const;
  626.  
  627.     /// Get the symmetric inverse of this matrix as a 3-by-3.
  628.     /// Returns the zero matrix if singular.
  629.     void GetSymInverse33(b2Mat33* M) const;
  630.  
  631.     b2Vec3 ex, ey, ez;
  632. };
  633.  
  634. /// Rotation
  635. struct B2_API b2Rot {
  636.     b2Rot() {}
  637.  
  638.     /// Initialize from an angle in radians
  639.     explicit b2Rot(float angle) {
  640.         /// TODO_ERIN optimize
  641.         s = sinf(angle);
  642.         c = cosf(angle);
  643.     }
  644.  
  645.     /// Set using an angle in radians.
  646.     void Set(float angle) {
  647.         /// TODO_ERIN optimize
  648.         s = sinf(angle);
  649.         c = cosf(angle);
  650.     }
  651.  
  652.     /// Set to the identity rotation
  653.     void SetIdentity() {
  654.         s = 0.0f;
  655.         c = 1.0f;
  656.     }
  657.  
  658.     /// Get the angle in radians
  659.     float GetAngle() const {
  660.         return b2Atan2(s, c);
  661.     }
  662.  
  663.     /// Get the x-axis
  664.     b2Vec2 GetXAxis() const {
  665.         return b2Vec2(c, s);
  666.     }
  667.  
  668.     /// Get the u-axis
  669.     b2Vec2 GetYAxis() const {
  670.         return b2Vec2(-s, c);
  671.     }
  672.  
  673.     /// Sine and cosine
  674.     float s, c;
  675. };
  676.  
  677. /// A transform contains translation and rotation. It is used to represent
  678. /// the position and orientation of rigid frames.
  679. struct B2_API b2Transform {
  680.     /// The default constructor does nothing.
  681.     b2Transform() {}
  682.  
  683.     /// Initialize using a position vector and a rotation.
  684.     b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {}
  685.  
  686.     /// Set this to the identity transform.
  687.     void SetIdentity() {
  688.         p.SetZero();
  689.         q.SetIdentity();
  690.     }
  691.  
  692.     /// Set this based on the position and angle.
  693.     void Set(const b2Vec2& position, float angle) {
  694.         p = position;
  695.         q.Set(angle);
  696.     }
  697.  
  698.     b2Vec2 p;
  699.     b2Rot q;
  700. };
  701.  
  702. /// This describes the motion of a body/shape for TOI computation.
  703. /// Shapes are defined with respect to the body origin, which may
  704. /// no coincide with the center of mass. However, to support dynamics
  705. /// we must interpolate the center of mass position.
  706. struct B2_API b2Sweep {
  707.     /// Get the interpolated transform at a specific time.
  708.     /// @param transform the output transform
  709.     /// @param beta is a factor in [0,1], where 0 indicates alpha0.
  710.     void GetTransform(b2Transform* transform, float beta) const;
  711.  
  712.     /// Advance the sweep forward, yielding a new initial state.
  713.     /// @param alpha the new initial time.
  714.     void Advance(float alpha);
  715.  
  716.     /// Normalize the angles.
  717.     void Normalize();
  718.  
  719.     b2Vec2 localCenter; ///< local center of mass position
  720.     b2Vec2 c0, c;       ///< center world positions
  721.     float a0, a;        ///< world angles
  722.  
  723.     /// Fraction of the current time step in the range [0,1]
  724.     /// c0 and a0 are the positions at alpha0.
  725.     float alpha0;
  726. };
  727.  
  728. /// Useful constant
  729. extern B2_API const b2Vec2 b2Vec2_zero;
  730.  
  731. /// Perform the dot product on two vectors.
  732. inline float b2Dot(const b2Vec2& a, const b2Vec2& b) {
  733.     return a.x * b.x + a.y * b.y;
  734. }
  735.  
  736. /// Perform the cross product on two vectors. In 2D this produces a scalar.
  737. inline float b2Cross(const b2Vec2& a, const b2Vec2& b) {
  738.     return a.x * b.y - a.y * b.x;
  739. }
  740.  
  741. /// Perform the cross product on a vector and a scalar. In 2D this produces
  742. /// a vector.
  743. inline b2Vec2 b2Cross(const b2Vec2& a, float s) {
  744.     return b2Vec2(s * a.y, -s * a.x);
  745. }
  746.  
  747. /// Perform the cross product on a scalar and a vector. In 2D this produces
  748. /// a vector.
  749. inline b2Vec2 b2Cross(float s, const b2Vec2& a) {
  750.     return b2Vec2(-s * a.y, s * a.x);
  751. }
  752.  
  753. /// Multiply a matrix times a vector. If a rotation matrix is provided,
  754. /// then this transforms the vector from one frame to another.
  755. inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) {
  756.     return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y);
  757. }
  758.  
  759. /// Multiply a matrix transpose times a vector. If a rotation matrix is provided,
  760. /// then this transforms the vector from one frame to another (inverse transform).
  761. inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) {
  762.     return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey));
  763. }
  764.  
  765. /// Add two vectors component-wise.
  766. inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) {
  767.     return b2Vec2(a.x + b.x, a.y + b.y);
  768. }
  769.  
  770. /// Subtract two vectors component-wise.
  771. inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) {
  772.     return b2Vec2(a.x - b.x, a.y - b.y);
  773. }
  774.  
  775. inline b2Vec2 operator * (float s, const b2Vec2& a) {
  776.     return b2Vec2(s * a.x, s * a.y);
  777. }
  778.  
  779. inline bool operator == (const b2Vec2& a, const b2Vec2& b) {
  780.     return a.x == b.x && a.y == b.y;
  781. }
  782.  
  783. inline bool operator != (const b2Vec2& a, const b2Vec2& b) {
  784.     return a.x != b.x || a.y != b.y;
  785. }
  786.  
  787. inline float b2Distance(const b2Vec2& a, const b2Vec2& b) {
  788.     b2Vec2 c = a - b;
  789.     return c.Length();
  790. }
  791.  
  792. inline float b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) {
  793.     b2Vec2 c = a - b;
  794.     return b2Dot(c, c);
  795. }
  796.  
  797. inline b2Vec3 operator * (float s, const b2Vec3& a) {
  798.     return b2Vec3(s * a.x, s * a.y, s * a.z);
  799. }
  800.  
  801. /// Add two vectors component-wise.
  802. inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) {
  803.     return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
  804. }
  805.  
  806. /// Subtract two vectors component-wise.
  807. inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) {
  808.     return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
  809. }
  810.  
  811. /// Perform the dot product on two vectors.
  812. inline float b2Dot(const b2Vec3& a, const b2Vec3& b) {
  813.     return a.x * b.x + a.y * b.y + a.z * b.z;
  814. }
  815.  
  816. /// Perform the cross product on two vectors.
  817. inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) {
  818.     return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
  819. }
  820.  
  821. inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) {
  822.     return b2Mat22(A.ex + B.ex, A.ey + B.ey);
  823. }
  824.  
  825. // A * B
  826. inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) {
  827.     return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey));
  828. }
  829.  
  830. // A^T * B
  831. inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) {
  832.     b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex));
  833.     b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey));
  834.     return b2Mat22(c1, c2);
  835. }
  836.  
  837. /// Multiply a matrix times a vector.
  838. inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) {
  839.     return v.x * A.ex + v.y * A.ey + v.z * A.ez;
  840. }
  841.  
  842. /// Multiply a matrix times a vector.
  843. inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) {
  844.     return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y);
  845. }
  846.  
  847. /// Multiply two rotations: q * r
  848. inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) {
  849.     // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc]
  850.     // [qs  qc]   [rs  rc]   [qs*rc+qc*rs -qs*rs+qc*rc]
  851.     // s = qs * rc + qc * rs
  852.     // c = qc * rc - qs * rs
  853.     b2Rot qr;
  854.     qr.s = q.s * r.c + q.c * r.s;
  855.     qr.c = q.c * r.c - q.s * r.s;
  856.     return qr;
  857. }
  858.  
  859. /// Transpose multiply two rotations: qT * r
  860. inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) {
  861.     // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc]
  862.     // [-qs qc]   [rs  rc]   [-qs*rc+qc*rs qs*rs+qc*rc]
  863.     // s = qc * rs - qs * rc
  864.     // c = qc * rc + qs * rs
  865.     b2Rot qr;
  866.     qr.s = q.c * r.s - q.s * r.c;
  867.     qr.c = q.c * r.c + q.s * r.s;
  868.     return qr;
  869. }
  870.  
  871. /// Rotate a vector
  872. inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) {
  873.     return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y);
  874. }
  875.  
  876. /// Inverse rotate a vector
  877. inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) {
  878.     return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y);
  879. }
  880.  
  881. inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) {
  882.     float x = (T.q.c * v.x - T.q.s * v.y) + T.p.x;
  883.     float y = (T.q.s * v.x + T.q.c * v.y) + T.p.y;
  884.  
  885.     return b2Vec2(x, y);
  886. }
  887.  
  888. inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) {
  889.     float px = v.x - T.p.x;
  890.     float py = v.y - T.p.y;
  891.     float x = (T.q.c * px + T.q.s * py);
  892.     float y = (-T.q.s * px + T.q.c * py);
  893.  
  894.     return b2Vec2(x, y);
  895. }
  896.  
  897. // v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p
  898. //    = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p
  899. inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) {
  900.     b2Transform C;
  901.     C.q = b2Mul(A.q, B.q);
  902.     C.p = b2Mul(A.q, B.p) + A.p;
  903.     return C;
  904. }
  905.  
  906. // v2 = A.q' * (B.q * v1 + B.p - A.p)
  907. //    = A.q' * B.q * v1 + A.q' * (B.p - A.p)
  908. inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) {
  909.     b2Transform C;
  910.     C.q = b2MulT(A.q, B.q);
  911.     C.p = b2MulT(A.q, B.p - A.p);
  912.     return C;
  913. }
  914.  
  915. template <typename T>
  916. inline T b2Abs(T a) {
  917.     return a > T(0) ? a : -a;
  918. }
  919.  
  920. inline b2Vec2 b2Abs(const b2Vec2& a) {
  921.     return b2Vec2(b2Abs(a.x), b2Abs(a.y));
  922. }
  923.  
  924. inline b2Mat22 b2Abs(const b2Mat22& A) {
  925.     return b2Mat22(b2Abs(A.ex), b2Abs(A.ey));
  926. }
  927.  
  928. template <typename T>
  929. inline T b2Min(T a, T b) {
  930.     return a < b ? a : b;
  931. }
  932.  
  933. inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) {
  934.     return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y));
  935. }
  936.  
  937. template <typename T>
  938. inline T b2Max(T a, T b) {
  939.     return a > b ? a : b;
  940. }
  941.  
  942. inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) {
  943.     return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y));
  944. }
  945.  
  946. template <typename T>
  947. inline T b2Clamp(T a, T low, T high) {
  948.     return b2Max(low, b2Min(a, high));
  949. }
  950.  
  951. inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) {
  952.     return b2Max(low, b2Min(a, high));
  953. }
  954.  
  955. template<typename T> inline void b2Swap(T& a, T& b) {
  956.     T tmp = a;
  957.     a = b;
  958.     b = tmp;
  959. }
  960.  
  961. /// "Next Largest Power of 2
  962. /// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm
  963. /// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with
  964. /// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next
  965. /// largest power of 2. For a 32-bit value:"
  966. inline uint32 b2NextPowerOfTwo(uint32 x) {
  967.     x |= (x >> 1);
  968.     x |= (x >> 2);
  969.     x |= (x >> 4);
  970.     x |= (x >> 8);
  971.     x |= (x >> 16);
  972.     return x + 1;
  973. }
  974.  
  975. inline bool b2IsPowerOfTwo(uint32 x) {
  976.     bool result = x > 0 && (x & (x - 1)) == 0;
  977.     return result;
  978. }
  979.  
  980. // https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/
  981. inline void b2Sweep::GetTransform(b2Transform* xf, float beta) const {
  982.     xf->p = (1.0f - beta) * c0 + beta * c;
  983.     float angle = (1.0f - beta) * a0 + beta * a;
  984.     xf->q.Set(angle);
  985.  
  986.     // Shift to origin
  987.     xf->p -= b2Mul(xf->q, localCenter);
  988. }
  989.  
  990. inline void b2Sweep::Advance(float alpha) {
  991.     b2Assert(alpha0 < 1.0f);
  992.     float beta = (alpha - alpha0) / (1.0f - alpha0);
  993.     c0 += beta * (c - c0);
  994.     a0 += beta * (a - a0);
  995.     alpha0 = alpha;
  996. }
  997.  
  998. /// Normalize an angle in radians to be between -pi and pi
  999. inline void b2Sweep::Normalize() {
  1000.     float twoPi = 2.0f * b2_pi;
  1001.     float d = twoPi * floorf(a0 / twoPi);
  1002.     a0 -= d;
  1003.     a -= d;
  1004. }
  1005.  
  1006. #endif
  1007. // MIT License
  1008.  
  1009. // Copyright (c) 2019 Erin Catto
  1010.  
  1011. // Permission is hereby granted, free of charge, to any person obtaining a copy
  1012. // of this software and associated documentation files (the "Software"), to deal
  1013. // in the Software without restriction, including without limitation the rights
  1014. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  1015. // copies of the Software, and to permit persons to whom the Software is
  1016. // furnished to do so, subject to the following conditions:
  1017.  
  1018. // The above copyright notice and this permission notice shall be included in all
  1019. // copies or substantial portions of the Software.
  1020.  
  1021. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1022. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1023. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1024. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1025. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1026. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  1027. // SOFTWARE.
  1028.  
  1029. #ifndef B2_COLLISION_H
  1030. #define B2_COLLISION_H
  1031.  
  1032. #include <limits.h>
  1033.  
  1034. //#include "b2_api.h"
  1035. //#include "b2_math.h"
  1036.  
  1037. /// @file
  1038. /// Structures and functions used for computing contact points, distance
  1039. /// queries, and TOI queries.
  1040.  
  1041. class b2Shape;
  1042. class b2CircleShape;
  1043. class b2EdgeShape;
  1044. class b2PolygonShape;
  1045.  
  1046. const uint8 b2_nullFeature = UCHAR_MAX;
  1047.  
  1048. /// The features that intersect to form the contact point
  1049. /// This must be 4 bytes or less.
  1050. struct B2_API b2ContactFeature {
  1051.     enum Type {
  1052.         e_vertex = 0,
  1053.         e_face = 1
  1054.     };
  1055.  
  1056.     uint8 indexA;       ///< Feature index on shapeA
  1057.     uint8 indexB;       ///< Feature index on shapeB
  1058.     uint8 typeA;        ///< The feature type on shapeA
  1059.     uint8 typeB;        ///< The feature type on shapeB
  1060. };
  1061.  
  1062. /// Contact ids to facilitate warm starting.
  1063. union B2_API b2ContactID {
  1064.     b2ContactFeature cf;
  1065.     uint32 key;                 ///< Used to quickly compare contact ids.
  1066. };
  1067.  
  1068. /// A manifold point is a contact point belonging to a contact
  1069. /// manifold. It holds details related to the geometry and dynamics
  1070. /// of the contact points.
  1071. /// The local point usage depends on the manifold type:
  1072. /// -e_circles: the local center of circleB
  1073. /// -e_faceA: the local center of cirlceB or the clip point of polygonB
  1074. /// -e_faceB: the clip point of polygonA
  1075. /// This structure is stored across time steps, so we keep it small.
  1076. /// Note: the impulses are used for internal caching and may not
  1077. /// provide reliable contact forces, especially for high speed collisions.
  1078. struct B2_API b2ManifoldPoint {
  1079.     b2Vec2 localPoint;      ///< usage depends on manifold type
  1080.     float normalImpulse;    ///< the non-penetration impulse
  1081.     float tangentImpulse;   ///< the friction impulse
  1082.     b2ContactID id;         ///< uniquely identifies a contact point between two shapes
  1083. };
  1084.  
  1085. /// A manifold for two touching convex shapes.
  1086. /// Box2D supports multiple types of contact:
  1087. /// - clip point versus plane with radius
  1088. /// - point versus point with radius (circles)
  1089. /// The local point usage depends on the manifold type:
  1090. /// -e_circles: the local center of circleA
  1091. /// -e_faceA: the center of faceA
  1092. /// -e_faceB: the center of faceB
  1093. /// Similarly the local normal usage:
  1094. /// -e_circles: not used
  1095. /// -e_faceA: the normal on polygonA
  1096. /// -e_faceB: the normal on polygonB
  1097. /// We store contacts in this way so that position correction can
  1098. /// account for movement, which is critical for continuous physics.
  1099. /// All contact scenarios must be expressed in one of these types.
  1100. /// This structure is stored across time steps, so we keep it small.
  1101. struct B2_API b2Manifold {
  1102.     enum Type {
  1103.         e_circles,
  1104.         e_faceA,
  1105.         e_faceB
  1106.     };
  1107.  
  1108.     b2ManifoldPoint points[b2_maxManifoldPoints];   ///< the points of contact
  1109.     b2Vec2 localNormal;                             ///< not use for Type::e_points
  1110.     b2Vec2 localPoint;                              ///< usage depends on manifold type
  1111.     Type type;
  1112.     int32 pointCount;                               ///< the number of manifold points
  1113. };
  1114.  
  1115. /// This is used to compute the current state of a contact manifold.
  1116. struct B2_API b2WorldManifold {
  1117.     /// Evaluate the manifold with supplied transforms. This assumes
  1118.     /// modest motion from the original state. This does not change the
  1119.     /// point count, impulses, etc. The radii must come from the shapes
  1120.     /// that generated the manifold.
  1121.     void Initialize(const b2Manifold* manifold,
  1122.         const b2Transform& xfA, float radiusA,
  1123.         const b2Transform& xfB, float radiusB);
  1124.  
  1125.     b2Vec2 normal;                              ///< world vector pointing from A to B
  1126.     b2Vec2 points[b2_maxManifoldPoints];        ///< world contact point (point of intersection)
  1127.     float separations[b2_maxManifoldPoints];    ///< a negative value indicates overlap, in meters
  1128. };
  1129.  
  1130. /// This is used for determining the state of contact points.
  1131. enum b2PointState {
  1132.     b2_nullState,       ///< point does not exist
  1133.     b2_addState,        ///< point was added in the update
  1134.     b2_persistState,    ///< point persisted across the update
  1135.     b2_removeState      ///< point was removed in the update
  1136. };
  1137.  
  1138. /// Compute the point states given two manifolds. The states pertain to the transition from manifold1
  1139. /// to manifold2. So state1 is either persist or remove while state2 is either add or persist.
  1140. B2_API void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints],
  1141.     const b2Manifold* manifold1, const b2Manifold* manifold2);
  1142.  
  1143. /// Used for computing contact manifolds.
  1144. struct B2_API b2ClipVertex {
  1145.     b2Vec2 v;
  1146.     b2ContactID id;
  1147. };
  1148.  
  1149. /// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
  1150. struct B2_API b2RayCastInput {
  1151.     b2Vec2 p1, p2;
  1152.     float maxFraction;
  1153. };
  1154.  
  1155. /// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2
  1156. /// come from b2RayCastInput.
  1157. struct B2_API b2RayCastOutput {
  1158.     b2Vec2 normal;
  1159.     float fraction;
  1160. };
  1161.  
  1162. /// An axis aligned bounding box.
  1163. struct B2_API b2AABB {
  1164.     /// Verify that the bounds are sorted.
  1165.     bool IsValid() const;
  1166.  
  1167.     /// Get the center of the AABB.
  1168.     b2Vec2 GetCenter() const {
  1169.         return 0.5f * (lowerBound + upperBound);
  1170.     }
  1171.  
  1172.     /// Get the extents of the AABB (half-widths).
  1173.     b2Vec2 GetExtents() const {
  1174.         return 0.5f * (upperBound - lowerBound);
  1175.     }
  1176.  
  1177.     /// Get the perimeter length
  1178.     float GetPerimeter() const {
  1179.         float wx = upperBound.x - lowerBound.x;
  1180.         float wy = upperBound.y - lowerBound.y;
  1181.         return 2.0f * (wx + wy);
  1182.     }
  1183.  
  1184.     /// Combine an AABB into this one.
  1185.     void Combine(const b2AABB& aabb) {
  1186.         lowerBound = b2Min(lowerBound, aabb.lowerBound);
  1187.         upperBound = b2Max(upperBound, aabb.upperBound);
  1188.     }
  1189.  
  1190.     /// Combine two AABBs into this one.
  1191.     void Combine(const b2AABB& aabb1, const b2AABB& aabb2) {
  1192.         lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound);
  1193.         upperBound = b2Max(aabb1.upperBound, aabb2.upperBound);
  1194.     }
  1195.  
  1196.     /// Does this aabb contain the provided AABB.
  1197.     bool Contains(const b2AABB& aabb) const {
  1198.         bool result = true;
  1199.         result = result && lowerBound.x <= aabb.lowerBound.x;
  1200.         result = result && lowerBound.y <= aabb.lowerBound.y;
  1201.         result = result && aabb.upperBound.x <= upperBound.x;
  1202.         result = result && aabb.upperBound.y <= upperBound.y;
  1203.         return result;
  1204.     }
  1205.  
  1206.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const;
  1207.  
  1208.     b2Vec2 lowerBound;  ///< the lower vertex
  1209.     b2Vec2 upperBound;  ///< the upper vertex
  1210. };
  1211.  
  1212. /// Compute the collision manifold between two circles.
  1213. B2_API void b2CollideCircles(b2Manifold* manifold,
  1214.     const b2CircleShape* circleA, const b2Transform& xfA,
  1215.     const b2CircleShape* circleB, const b2Transform& xfB);
  1216.  
  1217. /// Compute the collision manifold between a polygon and a circle.
  1218. B2_API void b2CollidePolygonAndCircle(b2Manifold* manifold,
  1219.     const b2PolygonShape* polygonA, const b2Transform& xfA,
  1220.     const b2CircleShape* circleB, const b2Transform& xfB);
  1221.  
  1222. /// Compute the collision manifold between two polygons.
  1223. B2_API void b2CollidePolygons(b2Manifold* manifold,
  1224.     const b2PolygonShape* polygonA, const b2Transform& xfA,
  1225.     const b2PolygonShape* polygonB, const b2Transform& xfB);
  1226.  
  1227. /// Compute the collision manifold between an edge and a circle.
  1228. B2_API void b2CollideEdgeAndCircle(b2Manifold* manifold,
  1229.     const b2EdgeShape* polygonA, const b2Transform& xfA,
  1230.     const b2CircleShape* circleB, const b2Transform& xfB);
  1231.  
  1232. /// Compute the collision manifold between an edge and a polygon.
  1233. B2_API void b2CollideEdgeAndPolygon(b2Manifold* manifold,
  1234.     const b2EdgeShape* edgeA, const b2Transform& xfA,
  1235.     const b2PolygonShape* circleB, const b2Transform& xfB);
  1236.  
  1237. /// Clipping for contact manifolds.
  1238. B2_API int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2],
  1239.     const b2Vec2& normal, float offset, int32 vertexIndexA);
  1240.  
  1241. /// Determine if two generic shapes overlap.
  1242. B2_API bool b2TestOverlap(const b2Shape* shapeA, int32 indexA,
  1243.     const b2Shape* shapeB, int32 indexB,
  1244.     const b2Transform& xfA, const b2Transform& xfB);
  1245.  
  1246. // ---------------- Inline Functions ------------------------------------------
  1247.  
  1248. inline bool b2AABB::IsValid() const {
  1249.     b2Vec2 d = upperBound - lowerBound;
  1250.     bool valid = d.x >= 0.0f && d.y >= 0.0f;
  1251.     valid = valid && lowerBound.IsValid() && upperBound.IsValid();
  1252.     return valid;
  1253. }
  1254.  
  1255. inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) {
  1256.     b2Vec2 d1, d2;
  1257.     d1 = b.lowerBound - a.upperBound;
  1258.     d2 = a.lowerBound - b.upperBound;
  1259.  
  1260.     if (d1.x > 0.0f || d1.y > 0.0f)
  1261.         return false;
  1262.  
  1263.     if (d2.x > 0.0f || d2.y > 0.0f)
  1264.         return false;
  1265.  
  1266.     return true;
  1267. }
  1268.  
  1269. #endif
  1270. // MIT License
  1271.  
  1272. // Copyright (c) 2019 Erin Catto
  1273.  
  1274. // Permission is hereby granted, free of charge, to any person obtaining a copy
  1275. // of this software and associated documentation files (the "Software"), to deal
  1276. // in the Software without restriction, including without limitation the rights
  1277. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  1278. // copies of the Software, and to permit persons to whom the Software is
  1279. // furnished to do so, subject to the following conditions:
  1280.  
  1281. // The above copyright notice and this permission notice shall be included in all
  1282. // copies or substantial portions of the Software.
  1283.  
  1284. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1285. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1286. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1287. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1288. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1289. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  1290. // SOFTWARE.
  1291.  
  1292. #ifndef B2_SHAPE_H
  1293. #define B2_SHAPE_H
  1294.  
  1295. //#include "b2_api.h"
  1296. //#include "b2_math.h"
  1297. //#include "b2_collision.h"
  1298.  
  1299. class b2BlockAllocator;
  1300.  
  1301. /// This holds the mass data computed for a shape.
  1302. struct B2_API b2MassData {
  1303.     /// The mass of the shape, usually in kilograms.
  1304.     float mass;
  1305.  
  1306.     /// The position of the shape's centroid relative to the shape's origin.
  1307.     b2Vec2 center;
  1308.  
  1309.     /// The rotational inertia of the shape about the local origin.
  1310.     float I;
  1311. };
  1312.  
  1313. /// A shape is used for collision detection. You can create a shape however you like.
  1314. /// Shapes used for simulation in b2World are created automatically when a b2Fixture
  1315. /// is created. Shapes may encapsulate a one or more child shapes.
  1316. class B2_API b2Shape {
  1317. public:
  1318.  
  1319.     enum Type {
  1320.         e_circle = 0,
  1321.         e_edge = 1,
  1322.         e_polygon = 2,
  1323.         e_chain = 3,
  1324.         e_typeCount = 4
  1325.     };
  1326.  
  1327.     virtual ~b2Shape() {}
  1328.  
  1329.     /// Clone the concrete shape using the provided allocator.
  1330.     virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0;
  1331.  
  1332.     /// Get the type of this shape. You can use this to down cast to the concrete shape.
  1333.     /// @return the shape type.
  1334.     Type GetType() const;
  1335.  
  1336.     /// Get the number of child primitives.
  1337.     virtual int32 GetChildCount() const = 0;
  1338.  
  1339.     /// Test a point for containment in this shape. This only works for convex shapes.
  1340.     /// @param xf the shape world transform.
  1341.     /// @param p a point in world coordinates.
  1342.     virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0;
  1343.  
  1344.     /// Cast a ray against a child shape.
  1345.     /// @param output the ray-cast results.
  1346.     /// @param input the ray-cast input parameters.
  1347.     /// @param transform the transform to be applied to the shape.
  1348.     /// @param childIndex the child shape index
  1349.     virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  1350.         const b2Transform& transform, int32 childIndex) const = 0;
  1351.  
  1352.     /// Given a transform, compute the associated axis aligned bounding box for a child shape.
  1353.     /// @param aabb returns the axis aligned box.
  1354.     /// @param xf the world transform of the shape.
  1355.     /// @param childIndex the child shape
  1356.     virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0;
  1357.  
  1358.     /// Compute the mass properties of this shape using its dimensions and density.
  1359.     /// The inertia tensor is computed about the local origin.
  1360.     /// @param massData returns the mass data for this shape.
  1361.     /// @param density the density in kilograms per meter squared.
  1362.     virtual void ComputeMass(b2MassData* massData, float density) const = 0;
  1363.  
  1364.     Type m_type;
  1365.  
  1366.     /// Radius of a shape. For polygonal shapes this must be b2_polygonRadius. There is no support for
  1367.     /// making rounded polygons.
  1368.     float m_radius;
  1369. };
  1370.  
  1371. inline b2Shape::Type b2Shape::GetType() const {
  1372.     return m_type;
  1373. }
  1374.  
  1375. #endif
  1376. // MIT License
  1377.  
  1378. // Copyright (c) 2019 Erin Catto
  1379.  
  1380. // Permission is hereby granted, free of charge, to any person obtaining a copy
  1381. // of this software and associated documentation files (the "Software"), to deal
  1382. // in the Software without restriction, including without limitation the rights
  1383. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  1384. // copies of the Software, and to permit persons to whom the Software is
  1385. // furnished to do so, subject to the following conditions:
  1386.  
  1387. // The above copyright notice and this permission notice shall be included in all
  1388. // copies or substantial portions of the Software.
  1389.  
  1390. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1391. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1392. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1393. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1394. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1395. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  1396. // SOFTWARE.
  1397.  
  1398. #ifndef B2_BODY_H
  1399. #define B2_BODY_H
  1400.  
  1401. //#include "b2_api.h"
  1402. //#include "b2_math.h"
  1403. //#include "b2_shape.h"
  1404.  
  1405. class b2Fixture;
  1406. class b2Joint;
  1407. class b2Contact;
  1408. class b2Controller;
  1409. class b2World;
  1410. struct b2FixtureDef;
  1411. struct b2JointEdge;
  1412. struct b2ContactEdge;
  1413.  
  1414. /// The body type.
  1415. /// static: zero mass, zero velocity, may be manually moved
  1416. /// kinematic: zero mass, non-zero velocity set by user, moved by solver
  1417. /// dynamic: positive mass, non-zero velocity determined by forces, moved by solver
  1418. enum b2BodyType {
  1419.     b2_staticBody = 0,
  1420.     b2_kinematicBody,
  1421.     b2_dynamicBody
  1422. };
  1423.  
  1424. /// A body definition holds all the data needed to construct a rigid body.
  1425. /// You can safely re-use body definitions. Shapes are added to a body after construction.
  1426. struct B2_API b2BodyDef {
  1427.     /// This constructor sets the body definition default values.
  1428.     b2BodyDef() {
  1429.         position.Set(0.0f, 0.0f);
  1430.         angle = 0.0f;
  1431.         linearVelocity.Set(0.0f, 0.0f);
  1432.         angularVelocity = 0.0f;
  1433.         linearDamping = 0.0f;
  1434.         angularDamping = 0.0f;
  1435.         allowSleep = true;
  1436.         awake = true;
  1437.         fixedRotation = false;
  1438.         bullet = false;
  1439.         type = b2_staticBody;
  1440.         enabled = true;
  1441.         gravityScale = 1.0f;
  1442.     }
  1443.  
  1444.     /// The body type: static, kinematic, or dynamic.
  1445.     /// Note: if a dynamic body would have zero mass, the mass is set to one.
  1446.     b2BodyType type;
  1447.  
  1448.     /// The world position of the body. Avoid creating bodies at the origin
  1449.     /// since this can lead to many overlapping shapes.
  1450.     b2Vec2 position;
  1451.  
  1452.     /// The world angle of the body in radians.
  1453.     float angle;
  1454.  
  1455.     /// The linear velocity of the body's origin in world co-ordinates.
  1456.     b2Vec2 linearVelocity;
  1457.  
  1458.     /// The angular velocity of the body.
  1459.     float angularVelocity;
  1460.  
  1461.     /// Linear damping is use to reduce the linear velocity. The damping parameter
  1462.     /// can be larger than 1.0f but the damping effect becomes sensitive to the
  1463.     /// time step when the damping parameter is large.
  1464.     /// Units are 1/time
  1465.     float linearDamping;
  1466.  
  1467.     /// Angular damping is use to reduce the angular velocity. The damping parameter
  1468.     /// can be larger than 1.0f but the damping effect becomes sensitive to the
  1469.     /// time step when the damping parameter is large.
  1470.     /// Units are 1/time
  1471.     float angularDamping;
  1472.  
  1473.     /// Set this flag to false if this body should never fall asleep. Note that
  1474.     /// this increases CPU usage.
  1475.     bool allowSleep;
  1476.  
  1477.     /// Is this body initially awake or sleeping?
  1478.     bool awake;
  1479.  
  1480.     /// Should this body be prevented from rotating? Useful for characters.
  1481.     bool fixedRotation;
  1482.  
  1483.     /// Is this a fast moving body that should be prevented from tunneling through
  1484.     /// other moving bodies? Note that all bodies are prevented from tunneling through
  1485.     /// kinematic and static bodies. This setting is only considered on dynamic bodies.
  1486.     /// @warning You should use this flag sparingly since it increases processing time.
  1487.     bool bullet;
  1488.  
  1489.     /// Does this body start out enabled?
  1490.     bool enabled;
  1491.  
  1492.     /// Use this to store application specific body data.
  1493.     b2BodyUserData userData;
  1494.  
  1495.     /// Scale the gravity applied to this body.
  1496.     float gravityScale;
  1497. };
  1498.  
  1499. /// A rigid body. These are created via b2World::CreateBody.
  1500. class B2_API b2Body {
  1501. public:
  1502.     /// Creates a fixture and attach it to this body. Use this function if you need
  1503.     /// to set some fixture parameters, like friction. Otherwise you can create the
  1504.     /// fixture directly from a shape.
  1505.     /// If the density is non-zero, this function automatically updates the mass of the body.
  1506.     /// Contacts are not created until the next time step.
  1507.     /// @param def the fixture definition.
  1508.     /// @warning This function is locked during callbacks.
  1509.     b2Fixture* CreateFixture(const b2FixtureDef* def);
  1510.  
  1511.     /// Creates a fixture from a shape and attach it to this body.
  1512.     /// This is a convenience function. Use b2FixtureDef if you need to set parameters
  1513.     /// like friction, restitution, user data, or filtering.
  1514.     /// If the density is non-zero, this function automatically updates the mass of the body.
  1515.     /// @param shape the shape to be cloned.
  1516.     /// @param density the shape density (set to zero for static bodies).
  1517.     /// @warning This function is locked during callbacks.
  1518.     b2Fixture* CreateFixture(const b2Shape* shape, float density);
  1519.  
  1520.     /// Destroy a fixture. This removes the fixture from the broad-phase and
  1521.     /// destroys all contacts associated with this fixture. This will
  1522.     /// automatically adjust the mass of the body if the body is dynamic and the
  1523.     /// fixture has positive density.
  1524.     /// All fixtures attached to a body are implicitly destroyed when the body is destroyed.
  1525.     /// @param fixture the fixture to be removed.
  1526.     /// @warning This function is locked during callbacks.
  1527.     void DestroyFixture(b2Fixture* fixture);
  1528.  
  1529.     /// Set the position of the body's origin and rotation.
  1530.     /// Manipulating a body's transform may cause non-physical behavior.
  1531.     /// Note: contacts are updated on the next call to b2World::Step.
  1532.     /// @param position the world position of the body's local origin.
  1533.     /// @param angle the world rotation in radians.
  1534.     void SetTransform(const b2Vec2& position, float angle);
  1535.  
  1536.     /// Get the body transform for the body's origin.
  1537.     /// @return the world transform of the body's origin.
  1538.     const b2Transform& GetTransform() const;
  1539.  
  1540.     /// Get the world body origin position.
  1541.     /// @return the world position of the body's origin.
  1542.     const b2Vec2& GetPosition() const;
  1543.  
  1544.     /// Get the angle in radians.
  1545.     /// @return the current world rotation angle in radians.
  1546.     float GetAngle() const;
  1547.  
  1548.     /// Get the world position of the center of mass.
  1549.     const b2Vec2& GetWorldCenter() const;
  1550.  
  1551.     /// Get the local position of the center of mass.
  1552.     const b2Vec2& GetLocalCenter() const;
  1553.  
  1554.     /// Set the linear velocity of the center of mass.
  1555.     /// @param v the new linear velocity of the center of mass.
  1556.     void SetLinearVelocity(const b2Vec2& v);
  1557.  
  1558.     /// Get the linear velocity of the center of mass.
  1559.     /// @return the linear velocity of the center of mass.
  1560.     const b2Vec2& GetLinearVelocity() const;
  1561.  
  1562.     /// Set the angular velocity.
  1563.     /// @param omega the new angular velocity in radians/second.
  1564.     void SetAngularVelocity(float omega);
  1565.  
  1566.     /// Get the angular velocity.
  1567.     /// @return the angular velocity in radians/second.
  1568.     float GetAngularVelocity() const;
  1569.  
  1570.     /// Apply a force at a world point. If the force is not
  1571.     /// applied at the center of mass, it will generate a torque and
  1572.     /// affect the angular velocity. This wakes up the body.
  1573.     /// @param force the world force vector, usually in Newtons (N).
  1574.     /// @param point the world position of the point of application.
  1575.     /// @param wake also wake up the body
  1576.     void ApplyForce(const b2Vec2& force, const b2Vec2& point, bool wake);
  1577.  
  1578.     /// Apply a force to the center of mass. This wakes up the body.
  1579.     /// @param force the world force vector, usually in Newtons (N).
  1580.     /// @param wake also wake up the body
  1581.     void ApplyForceToCenter(const b2Vec2& force, bool wake);
  1582.  
  1583.     /// Apply a torque. This affects the angular velocity
  1584.     /// without affecting the linear velocity of the center of mass.
  1585.     /// @param torque about the z-axis (out of the screen), usually in N-m.
  1586.     /// @param wake also wake up the body
  1587.     void ApplyTorque(float torque, bool wake);
  1588.  
  1589.     /// Apply an impulse at a point. This immediately modifies the velocity.
  1590.     /// It also modifies the angular velocity if the point of application
  1591.     /// is not at the center of mass. This wakes up the body.
  1592.     /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
  1593.     /// @param point the world position of the point of application.
  1594.     /// @param wake also wake up the body
  1595.     void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point, bool wake);
  1596.  
  1597.     /// Apply an impulse to the center of mass. This immediately modifies the velocity.
  1598.     /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
  1599.     /// @param wake also wake up the body
  1600.     void ApplyLinearImpulseToCenter(const b2Vec2& impulse, bool wake);
  1601.  
  1602.     /// Apply an angular impulse.
  1603.     /// @param impulse the angular impulse in units of kg*m*m/s
  1604.     /// @param wake also wake up the body
  1605.     void ApplyAngularImpulse(float impulse, bool wake);
  1606.  
  1607.     /// Get the total mass of the body.
  1608.     /// @return the mass, usually in kilograms (kg).
  1609.     float GetMass() const;
  1610.  
  1611.     /// Get the rotational inertia of the body about the local origin.
  1612.     /// @return the rotational inertia, usually in kg-m^2.
  1613.     float GetInertia() const;
  1614.  
  1615.     /// Get the mass data of the body.
  1616.     /// @return a struct containing the mass, inertia and center of the body.
  1617.     void GetMassData(b2MassData* data) const;
  1618.  
  1619.     /// Set the mass properties to override the mass properties of the fixtures.
  1620.     /// Note that this changes the center of mass position.
  1621.     /// Note that creating or destroying fixtures can also alter the mass.
  1622.     /// This function has no effect if the body isn't dynamic.
  1623.     /// @param data the mass properties.
  1624.     void SetMassData(const b2MassData* data);
  1625.  
  1626.     /// This resets the mass properties to the sum of the mass properties of the fixtures.
  1627.     /// This normally does not need to be called unless you called SetMassData to override
  1628.     /// the mass and you later want to reset the mass.
  1629.     void ResetMassData();
  1630.  
  1631.     /// Get the world coordinates of a point given the local coordinates.
  1632.     /// @param localPoint a point on the body measured relative the the body's origin.
  1633.     /// @return the same point expressed in world coordinates.
  1634.     b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const;
  1635.  
  1636.     /// Get the world coordinates of a vector given the local coordinates.
  1637.     /// @param localVector a vector fixed in the body.
  1638.     /// @return the same vector expressed in world coordinates.
  1639.     b2Vec2 GetWorldVector(const b2Vec2& localVector) const;
  1640.  
  1641.     /// Gets a local point relative to the body's origin given a world point.
  1642.     /// @param worldPoint a point in world coordinates.
  1643.     /// @return the corresponding local point relative to the body's origin.
  1644.     b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const;
  1645.  
  1646.     /// Gets a local vector given a world vector.
  1647.     /// @param worldVector a vector in world coordinates.
  1648.     /// @return the corresponding local vector.
  1649.     b2Vec2 GetLocalVector(const b2Vec2& worldVector) const;
  1650.  
  1651.     /// Get the world linear velocity of a world point attached to this body.
  1652.     /// @param worldPoint a point in world coordinates.
  1653.     /// @return the world velocity of a point.
  1654.     b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const;
  1655.  
  1656.     /// Get the world velocity of a local point.
  1657.     /// @param localPoint a point in local coordinates.
  1658.     /// @return the world velocity of a point.
  1659.     b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const;
  1660.  
  1661.     /// Get the linear damping of the body.
  1662.     float GetLinearDamping() const;
  1663.  
  1664.     /// Set the linear damping of the body.
  1665.     void SetLinearDamping(float linearDamping);
  1666.  
  1667.     /// Get the angular damping of the body.
  1668.     float GetAngularDamping() const;
  1669.  
  1670.     /// Set the angular damping of the body.
  1671.     void SetAngularDamping(float angularDamping);
  1672.  
  1673.     /// Get the gravity scale of the body.
  1674.     float GetGravityScale() const;
  1675.  
  1676.     /// Set the gravity scale of the body.
  1677.     void SetGravityScale(float scale);
  1678.  
  1679.     /// Set the type of this body. This may alter the mass and velocity.
  1680.     void SetType(b2BodyType type);
  1681.  
  1682.     /// Get the type of this body.
  1683.     b2BodyType GetType() const;
  1684.  
  1685.     /// Should this body be treated like a bullet for continuous collision detection?
  1686.     void SetBullet(bool flag);
  1687.  
  1688.     /// Is this body treated like a bullet for continuous collision detection?
  1689.     bool IsBullet() const;
  1690.  
  1691.     /// You can disable sleeping on this body. If you disable sleeping, the
  1692.     /// body will be woken.
  1693.     void SetSleepingAllowed(bool flag);
  1694.  
  1695.     /// Is this body allowed to sleep
  1696.     bool IsSleepingAllowed() const;
  1697.  
  1698.     /// Set the sleep state of the body. A sleeping body has very
  1699.     /// low CPU cost.
  1700.     /// @param flag set to true to wake the body, false to put it to sleep.
  1701.     void SetAwake(bool flag);
  1702.  
  1703.     /// Get the sleeping state of this body.
  1704.     /// @return true if the body is awake.
  1705.     bool IsAwake() const;
  1706.  
  1707.     /// Allow a body to be disabled. A disabled body is not simulated and cannot
  1708.     /// be collided with or woken up.
  1709.     /// If you pass a flag of true, all fixtures will be added to the broad-phase.
  1710.     /// If you pass a flag of false, all fixtures will be removed from the
  1711.     /// broad-phase and all contacts will be destroyed.
  1712.     /// Fixtures and joints are otherwise unaffected. You may continue
  1713.     /// to create/destroy fixtures and joints on disabled bodies.
  1714.     /// Fixtures on a disabled body are implicitly disabled and will
  1715.     /// not participate in collisions, ray-casts, or queries.
  1716.     /// Joints connected to a disabled body are implicitly disabled.
  1717.     /// An diabled body is still owned by a b2World object and remains
  1718.     /// in the body list.
  1719.     void SetEnabled(bool flag);
  1720.  
  1721.     /// Get the active state of the body.
  1722.     bool IsEnabled() const;
  1723.  
  1724.     /// Set this body to have fixed rotation. This causes the mass
  1725.     /// to be reset.
  1726.     void SetFixedRotation(bool flag);
  1727.  
  1728.     /// Does this body have fixed rotation?
  1729.     bool IsFixedRotation() const;
  1730.  
  1731.     /// Get the list of all fixtures attached to this body.
  1732.     b2Fixture* GetFixtureList();
  1733.     const b2Fixture* GetFixtureList() const;
  1734.  
  1735.     /// Get the list of all joints attached to this body.
  1736.     b2JointEdge* GetJointList();
  1737.     const b2JointEdge* GetJointList() const;
  1738.  
  1739.     /// Get the list of all contacts attached to this body.
  1740.     /// @warning this list changes during the time step and you may
  1741.     /// miss some collisions if you don't use b2ContactListener.
  1742.     b2ContactEdge* GetContactList();
  1743.     const b2ContactEdge* GetContactList() const;
  1744.  
  1745.     /// Get the next body in the world's body list.
  1746.     b2Body* GetNext();
  1747.     const b2Body* GetNext() const;
  1748.  
  1749.     /// Get the user data pointer that was provided in the body definition.
  1750.     b2BodyUserData& GetUserData();
  1751.  
  1752.     /// Set the user data. Use this to store your application specific data.
  1753.     void SetUserData(void* data);
  1754.  
  1755.     /// Get the parent world of this body.
  1756.     b2World* GetWorld();
  1757.     const b2World* GetWorld() const;
  1758.  
  1759.     /// Dump this body to a file
  1760.     void Dump();
  1761.  
  1762. private:
  1763.  
  1764.     friend class b2World;
  1765.     friend class b2Island;
  1766.     friend class b2ContactManager;
  1767.     friend class b2ContactSolver;
  1768.     friend class b2Contact;
  1769.  
  1770.     friend class b2DistanceJoint;
  1771.     friend class b2FrictionJoint;
  1772.     friend class b2GearJoint;
  1773.     friend class b2MotorJoint;
  1774.     friend class b2MouseJoint;
  1775.     friend class b2PrismaticJoint;
  1776.     friend class b2PulleyJoint;
  1777.     friend class b2RevoluteJoint;
  1778.     friend class b2RopeJoint;
  1779.     friend class b2WeldJoint;
  1780.     friend class b2WheelJoint;
  1781.  
  1782.     // m_flags
  1783.     enum {
  1784.         e_islandFlag = 0x0001,
  1785.         e_awakeFlag = 0x0002,
  1786.         e_autoSleepFlag = 0x0004,
  1787.         e_bulletFlag = 0x0008,
  1788.         e_fixedRotationFlag = 0x0010,
  1789.         e_enabledFlag = 0x0020,
  1790.         e_toiFlag = 0x0040
  1791.     };
  1792.  
  1793.     b2Body(const b2BodyDef* bd, b2World* world);
  1794.     ~b2Body();
  1795.  
  1796.     void SynchronizeFixtures();
  1797.     void SynchronizeTransform();
  1798.  
  1799.     // This is used to prevent connected bodies from colliding.
  1800.     // It may lie, depending on the collideConnected flag.
  1801.     bool ShouldCollide(const b2Body* other) const;
  1802.  
  1803.     void Advance(float t);
  1804.  
  1805.     b2BodyType m_type;
  1806.  
  1807.     uint16 m_flags;
  1808.  
  1809.     int32 m_islandIndex;
  1810.  
  1811.     b2Transform m_xf;       // the body origin transform
  1812.     b2Sweep m_sweep;        // the swept motion for CCD
  1813.  
  1814.     b2Vec2 m_linearVelocity;
  1815.     float m_angularVelocity;
  1816.  
  1817.     b2Vec2 m_force;
  1818.     float m_torque;
  1819.  
  1820.     b2World* m_world;
  1821.     b2Body* m_prev;
  1822.     b2Body* m_next;
  1823.  
  1824.     b2Fixture* m_fixtureList;
  1825.     int32 m_fixtureCount;
  1826.  
  1827.     b2JointEdge* m_jointList;
  1828.     b2ContactEdge* m_contactList;
  1829.  
  1830.     float m_mass, m_invMass;
  1831.  
  1832.     // Rotational inertia about the center of mass.
  1833.     float m_I, m_invI;
  1834.  
  1835.     float m_linearDamping;
  1836.     float m_angularDamping;
  1837.     float m_gravityScale;
  1838.  
  1839.     float m_sleepTime;
  1840.  
  1841.     b2BodyUserData m_userData;
  1842. };
  1843.  
  1844. inline b2BodyType b2Body::GetType() const {
  1845.     return m_type;
  1846. }
  1847.  
  1848. inline const b2Transform& b2Body::GetTransform() const {
  1849.     return m_xf;
  1850. }
  1851.  
  1852. inline const b2Vec2& b2Body::GetPosition() const {
  1853.     return m_xf.p;
  1854. }
  1855.  
  1856. inline float b2Body::GetAngle() const {
  1857.     return m_sweep.a;
  1858. }
  1859.  
  1860. inline const b2Vec2& b2Body::GetWorldCenter() const {
  1861.     return m_sweep.c;
  1862. }
  1863.  
  1864. inline const b2Vec2& b2Body::GetLocalCenter() const {
  1865.     return m_sweep.localCenter;
  1866. }
  1867.  
  1868. inline void b2Body::SetLinearVelocity(const b2Vec2& v) {
  1869.     if (m_type == b2_staticBody) {
  1870.         return;
  1871.     }
  1872.  
  1873.     if (b2Dot(v, v) > 0.0f) {
  1874.         SetAwake(true);
  1875.     }
  1876.  
  1877.     m_linearVelocity = v;
  1878. }
  1879.  
  1880. inline const b2Vec2& b2Body::GetLinearVelocity() const {
  1881.     return m_linearVelocity;
  1882. }
  1883.  
  1884. inline void b2Body::SetAngularVelocity(float w) {
  1885.     if (m_type == b2_staticBody) {
  1886.         return;
  1887.     }
  1888.  
  1889.     if (w * w > 0.0f) {
  1890.         SetAwake(true);
  1891.     }
  1892.  
  1893.     m_angularVelocity = w;
  1894. }
  1895.  
  1896. inline float b2Body::GetAngularVelocity() const {
  1897.     return m_angularVelocity;
  1898. }
  1899.  
  1900. inline float b2Body::GetMass() const {
  1901.     return m_mass;
  1902. }
  1903.  
  1904. inline float b2Body::GetInertia() const {
  1905.     return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
  1906. }
  1907.  
  1908. inline void b2Body::GetMassData(b2MassData* data) const {
  1909.     data->mass = m_mass;
  1910.     data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
  1911.     data->center = m_sweep.localCenter;
  1912. }
  1913.  
  1914. inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const {
  1915.     return b2Mul(m_xf, localPoint);
  1916. }
  1917.  
  1918. inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const {
  1919.     return b2Mul(m_xf.q, localVector);
  1920. }
  1921.  
  1922. inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const {
  1923.     return b2MulT(m_xf, worldPoint);
  1924. }
  1925.  
  1926. inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const {
  1927.     return b2MulT(m_xf.q, worldVector);
  1928. }
  1929.  
  1930. inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const {
  1931.     return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c);
  1932. }
  1933.  
  1934. inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const {
  1935.     return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint));
  1936. }
  1937.  
  1938. inline float b2Body::GetLinearDamping() const {
  1939.     return m_linearDamping;
  1940. }
  1941.  
  1942. inline void b2Body::SetLinearDamping(float linearDamping) {
  1943.     m_linearDamping = linearDamping;
  1944. }
  1945.  
  1946. inline float b2Body::GetAngularDamping() const {
  1947.     return m_angularDamping;
  1948. }
  1949.  
  1950. inline void b2Body::SetAngularDamping(float angularDamping) {
  1951.     m_angularDamping = angularDamping;
  1952. }
  1953.  
  1954. inline float b2Body::GetGravityScale() const {
  1955.     return m_gravityScale;
  1956. }
  1957.  
  1958. inline void b2Body::SetGravityScale(float scale) {
  1959.     m_gravityScale = scale;
  1960. }
  1961.  
  1962. inline void b2Body::SetBullet(bool flag) {
  1963.     if (flag) {
  1964.         m_flags |= e_bulletFlag;
  1965.     } else {
  1966.         m_flags &= ~e_bulletFlag;
  1967.     }
  1968. }
  1969.  
  1970. inline bool b2Body::IsBullet() const {
  1971.     return (m_flags & e_bulletFlag) == e_bulletFlag;
  1972. }
  1973.  
  1974. inline void b2Body::SetAwake(bool flag) {
  1975.     if (m_type == b2_staticBody) {
  1976.         return;
  1977.     }
  1978.  
  1979.     if (flag) {
  1980.         m_flags |= e_awakeFlag;
  1981.         m_sleepTime = 0.0f;
  1982.     } else {
  1983.         m_flags &= ~e_awakeFlag;
  1984.         m_sleepTime = 0.0f;
  1985.         m_linearVelocity.SetZero();
  1986.         m_angularVelocity = 0.0f;
  1987.         m_force.SetZero();
  1988.         m_torque = 0.0f;
  1989.     }
  1990. }
  1991.  
  1992. inline bool b2Body::IsAwake() const {
  1993.     return (m_flags & e_awakeFlag) == e_awakeFlag;
  1994. }
  1995.  
  1996. inline bool b2Body::IsEnabled() const {
  1997.     return (m_flags & e_enabledFlag) == e_enabledFlag;
  1998. }
  1999.  
  2000. inline bool b2Body::IsFixedRotation() const {
  2001.     return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
  2002. }
  2003.  
  2004. inline void b2Body::SetSleepingAllowed(bool flag) {
  2005.     if (flag) {
  2006.         m_flags |= e_autoSleepFlag;
  2007.     } else {
  2008.         m_flags &= ~e_autoSleepFlag;
  2009.         SetAwake(true);
  2010.     }
  2011. }
  2012.  
  2013. inline bool b2Body::IsSleepingAllowed() const {
  2014.     return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
  2015. }
  2016.  
  2017. inline b2Fixture* b2Body::GetFixtureList() {
  2018.     return m_fixtureList;
  2019. }
  2020.  
  2021. inline const b2Fixture* b2Body::GetFixtureList() const {
  2022.     return m_fixtureList;
  2023. }
  2024.  
  2025. inline b2JointEdge* b2Body::GetJointList() {
  2026.     return m_jointList;
  2027. }
  2028.  
  2029. inline const b2JointEdge* b2Body::GetJointList() const {
  2030.     return m_jointList;
  2031. }
  2032.  
  2033. inline b2ContactEdge* b2Body::GetContactList() {
  2034.     return m_contactList;
  2035. }
  2036.  
  2037. inline const b2ContactEdge* b2Body::GetContactList() const {
  2038.     return m_contactList;
  2039. }
  2040.  
  2041. inline b2Body* b2Body::GetNext() {
  2042.     return m_next;
  2043. }
  2044.  
  2045. inline const b2Body* b2Body::GetNext() const {
  2046.     return m_next;
  2047. }
  2048.  
  2049. inline b2BodyUserData& b2Body::GetUserData() {
  2050.     return m_userData;
  2051. }
  2052.  
  2053. inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point, bool wake) {
  2054.     if (m_type != b2_dynamicBody) {
  2055.         return;
  2056.     }
  2057.  
  2058.     if (wake && (m_flags & e_awakeFlag) == 0) {
  2059.         SetAwake(true);
  2060.     }
  2061.  
  2062.     // Don't accumulate a force if the body is sleeping.
  2063.     if (m_flags & e_awakeFlag) {
  2064.         m_force += force;
  2065.         m_torque += b2Cross(point - m_sweep.c, force);
  2066.     }
  2067. }
  2068.  
  2069. inline void b2Body::ApplyForceToCenter(const b2Vec2& force, bool wake) {
  2070.     if (m_type != b2_dynamicBody) {
  2071.         return;
  2072.     }
  2073.  
  2074.     if (wake && (m_flags & e_awakeFlag) == 0) {
  2075.         SetAwake(true);
  2076.     }
  2077.  
  2078.     // Don't accumulate a force if the body is sleeping
  2079.     if (m_flags & e_awakeFlag) {
  2080.         m_force += force;
  2081.     }
  2082. }
  2083.  
  2084. inline void b2Body::ApplyTorque(float torque, bool wake) {
  2085.     if (m_type != b2_dynamicBody) {
  2086.         return;
  2087.     }
  2088.  
  2089.     if (wake && (m_flags & e_awakeFlag) == 0) {
  2090.         SetAwake(true);
  2091.     }
  2092.  
  2093.     // Don't accumulate a force if the body is sleeping
  2094.     if (m_flags & e_awakeFlag) {
  2095.         m_torque += torque;
  2096.     }
  2097. }
  2098.  
  2099. inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point, bool wake) {
  2100.     if (m_type != b2_dynamicBody) {
  2101.         return;
  2102.     }
  2103.  
  2104.     if (wake && (m_flags & e_awakeFlag) == 0) {
  2105.         SetAwake(true);
  2106.     }
  2107.  
  2108.     // Don't accumulate velocity if the body is sleeping
  2109.     if (m_flags & e_awakeFlag) {
  2110.         m_linearVelocity += m_invMass * impulse;
  2111.         m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse);
  2112.     }
  2113. }
  2114.  
  2115. inline void b2Body::ApplyLinearImpulseToCenter(const b2Vec2& impulse, bool wake) {
  2116.     if (m_type != b2_dynamicBody) {
  2117.         return;
  2118.     }
  2119.  
  2120.     if (wake && (m_flags & e_awakeFlag) == 0) {
  2121.         SetAwake(true);
  2122.     }
  2123.  
  2124.     // Don't accumulate velocity if the body is sleeping
  2125.     if (m_flags & e_awakeFlag) {
  2126.         m_linearVelocity += m_invMass * impulse;
  2127.     }
  2128. }
  2129.  
  2130. inline void b2Body::ApplyAngularImpulse(float impulse, bool wake) {
  2131.     if (m_type != b2_dynamicBody) {
  2132.         return;
  2133.     }
  2134.  
  2135.     if (wake && (m_flags & e_awakeFlag) == 0) {
  2136.         SetAwake(true);
  2137.     }
  2138.  
  2139.     // Don't accumulate velocity if the body is sleeping
  2140.     if (m_flags & e_awakeFlag) {
  2141.         m_angularVelocity += m_invI * impulse;
  2142.     }
  2143. }
  2144.  
  2145. inline void b2Body::SynchronizeTransform() {
  2146.     m_xf.q.Set(m_sweep.a);
  2147.     m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter);
  2148. }
  2149.  
  2150. inline void b2Body::Advance(float alpha) {
  2151.     // Advance to the new safe time. This doesn't sync the broad-phase.
  2152.     m_sweep.Advance(alpha);
  2153.     m_sweep.c = m_sweep.c0;
  2154.     m_sweep.a = m_sweep.a0;
  2155.     m_xf.q.Set(m_sweep.a);
  2156.     m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter);
  2157. }
  2158.  
  2159. inline b2World* b2Body::GetWorld() {
  2160.     return m_world;
  2161. }
  2162.  
  2163. inline const b2World* b2Body::GetWorld() const {
  2164.     return m_world;
  2165. }
  2166.  
  2167. #endif
  2168. // MIT License
  2169.  
  2170. // Copyright (c) 2019 Erin Catto
  2171.  
  2172. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2173. // of this software and associated documentation files (the "Software"), to deal
  2174. // in the Software without restriction, including without limitation the rights
  2175. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2176. // copies of the Software, and to permit persons to whom the Software is
  2177. // furnished to do so, subject to the following conditions:
  2178.  
  2179. // The above copyright notice and this permission notice shall be included in all
  2180. // copies or substantial portions of the Software.
  2181.  
  2182. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2183. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2184. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2185. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2186. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2187. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  2188. // SOFTWARE.
  2189.  
  2190. #ifndef B2_GROWABLE_STACK_H
  2191. #define B2_GROWABLE_STACK_H
  2192.  
  2193. #include <string.h>
  2194.  
  2195. //#include "b2_settings.h"
  2196.  
  2197. /// This is a growable LIFO stack with an initial capacity of N.
  2198. /// If the stack size exceeds the initial capacity, the heap is used
  2199. /// to increase the size of the stack.
  2200. template <typename T, int32 N>
  2201. class b2GrowableStack {
  2202. public:
  2203.     b2GrowableStack() {
  2204.         m_stack = m_array;
  2205.         m_count = 0;
  2206.         m_capacity = N;
  2207.     }
  2208.  
  2209.     ~b2GrowableStack() {
  2210.         if (m_stack != m_array) {
  2211.             b2Free(m_stack);
  2212.             m_stack = nullptr;
  2213.         }
  2214.     }
  2215.  
  2216.     void Push(const T& element) {
  2217.         if (m_count == m_capacity) {
  2218.             T* old = m_stack;
  2219.             m_capacity *= 2;
  2220.             m_stack = (T*)b2Alloc(m_capacity * sizeof(T));
  2221.             memcpy(m_stack, old, m_count * sizeof(T));
  2222.             if (old != m_array) {
  2223.                 b2Free(old);
  2224.             }
  2225.         }
  2226.  
  2227.         m_stack[m_count] = element;
  2228.         ++m_count;
  2229.     }
  2230.  
  2231.     T Pop() {
  2232.         b2Assert(m_count > 0);
  2233.         --m_count;
  2234.         return m_stack[m_count];
  2235.     }
  2236.  
  2237.     int32 GetCount() {
  2238.         return m_count;
  2239.     }
  2240.  
  2241. private:
  2242.     T* m_stack;
  2243.     T m_array[N];
  2244.     int32 m_count;
  2245.     int32 m_capacity;
  2246. };
  2247.  
  2248.  
  2249. #endif
  2250. // MIT License
  2251.  
  2252. // Copyright (c) 2019 Erin Catto
  2253.  
  2254. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2255. // of this software and associated documentation files (the "Software"), to deal
  2256. // in the Software without restriction, including without limitation the rights
  2257. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2258. // copies of the Software, and to permit persons to whom the Software is
  2259. // furnished to do so, subject to the following conditions:
  2260.  
  2261. // The above copyright notice and this permission notice shall be included in all
  2262. // copies or substantial portions of the Software.
  2263.  
  2264. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2265. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2266. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2267. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2268. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2269. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  2270. // SOFTWARE.
  2271.  
  2272. #ifndef B2_DYNAMIC_TREE_H
  2273. #define B2_DYNAMIC_TREE_H
  2274.  
  2275. //#include "b2_api.h"
  2276. //#include "b2_collision.h"
  2277. //#include "b2_growable_stack.h"
  2278.  
  2279. #define b2_nullNode (-1)
  2280.  
  2281. /// A node in the dynamic tree. The client does not interact with this directly.
  2282. struct B2_API b2TreeNode {
  2283.     bool IsLeaf() const {
  2284.         return child1 == b2_nullNode;
  2285.     }
  2286.  
  2287.     /// Enlarged AABB
  2288.     b2AABB aabb;
  2289.  
  2290.     void* userData;
  2291.  
  2292.     union {
  2293.         int32 parent;
  2294.         int32 next;
  2295.     };
  2296.  
  2297.     int32 child1;
  2298.     int32 child2;
  2299.  
  2300.     // leaf = 0, free node = -1
  2301.     int32 height;
  2302.  
  2303.     bool moved;
  2304. };
  2305.  
  2306. /// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
  2307. /// A dynamic tree arranges data in a binary tree to accelerate
  2308. /// queries such as volume queries and ray casts. Leafs are proxies
  2309. /// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor
  2310. /// so that the proxy AABB is bigger than the client object. This allows the client
  2311. /// object to move by small amounts without triggering a tree update.
  2312. ///
  2313. /// Nodes are pooled and relocatable, so we use node indices rather than pointers.
  2314. class B2_API b2DynamicTree {
  2315. public:
  2316.     /// Constructing the tree initializes the node pool.
  2317.     b2DynamicTree();
  2318.  
  2319.     /// Destroy the tree, freeing the node pool.
  2320.     ~b2DynamicTree();
  2321.  
  2322.     /// Create a proxy. Provide a tight fitting AABB and a userData pointer.
  2323.     int32 CreateProxy(const b2AABB& aabb, void* userData);
  2324.  
  2325.     /// Destroy a proxy. This asserts if the id is invalid.
  2326.     void DestroyProxy(int32 proxyId);
  2327.  
  2328.     /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB,
  2329.     /// then the proxy is removed from the tree and re-inserted. Otherwise
  2330.     /// the function returns immediately.
  2331.     /// @return true if the proxy was re-inserted.
  2332.     bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement);
  2333.  
  2334.     /// Get proxy user data.
  2335.     /// @return the proxy user data or 0 if the id is invalid.
  2336.     void* GetUserData(int32 proxyId) const;
  2337.  
  2338.     bool WasMoved(int32 proxyId) const;
  2339.     void ClearMoved(int32 proxyId);
  2340.  
  2341.     /// Get the fat AABB for a proxy.
  2342.     const b2AABB& GetFatAABB(int32 proxyId) const;
  2343.  
  2344.     /// Query an AABB for overlapping proxies. The callback class
  2345.     /// is called for each proxy that overlaps the supplied AABB.
  2346.     template <typename T>
  2347.     void Query(T* callback, const b2AABB& aabb) const;
  2348.  
  2349.     /// Ray-cast against the proxies in the tree. This relies on the callback
  2350.     /// to perform a exact ray-cast in the case were the proxy contains a shape.
  2351.     /// The callback also performs the any collision filtering. This has performance
  2352.     /// roughly equal to k * log(n), where k is the number of collisions and n is the
  2353.     /// number of proxies in the tree.
  2354.     /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
  2355.     /// @param callback a callback class that is called for each proxy that is hit by the ray.
  2356.     template <typename T>
  2357.     void RayCast(T* callback, const b2RayCastInput& input) const;
  2358.  
  2359.     /// Validate this tree. For testing.
  2360.     void Validate() const;
  2361.  
  2362.     /// Compute the height of the binary tree in O(N) time. Should not be
  2363.     /// called often.
  2364.     int32 GetHeight() const;
  2365.  
  2366.     /// Get the maximum balance of an node in the tree. The balance is the difference
  2367.     /// in height of the two children of a node.
  2368.     int32 GetMaxBalance() const;
  2369.  
  2370.     /// Get the ratio of the sum of the node areas to the root area.
  2371.     float GetAreaRatio() const;
  2372.  
  2373.     /// Build an optimal tree. Very expensive. For testing.
  2374.     void RebuildBottomUp();
  2375.  
  2376.     /// Shift the world origin. Useful for large worlds.
  2377.     /// The shift formula is: position -= newOrigin
  2378.     /// @param newOrigin the new origin with respect to the old origin
  2379.     void ShiftOrigin(const b2Vec2& newOrigin);
  2380.  
  2381. private:
  2382.  
  2383.     int32 AllocateNode();
  2384.     void FreeNode(int32 node);
  2385.  
  2386.     void InsertLeaf(int32 node);
  2387.     void RemoveLeaf(int32 node);
  2388.  
  2389.     int32 Balance(int32 index);
  2390.  
  2391.     int32 ComputeHeight() const;
  2392.     int32 ComputeHeight(int32 nodeId) const;
  2393.  
  2394.     void ValidateStructure(int32 index) const;
  2395.     void ValidateMetrics(int32 index) const;
  2396.  
  2397.     int32 m_root;
  2398.  
  2399.     b2TreeNode* m_nodes;
  2400.     int32 m_nodeCount;
  2401.     int32 m_nodeCapacity;
  2402.  
  2403.     int32 m_freeList;
  2404.  
  2405.     int32 m_insertionCount;
  2406. };
  2407.  
  2408. inline void* b2DynamicTree::GetUserData(int32 proxyId) const {
  2409.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
  2410.     return m_nodes[proxyId].userData;
  2411. }
  2412.  
  2413. inline bool b2DynamicTree::WasMoved(int32 proxyId) const {
  2414.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
  2415.     return m_nodes[proxyId].moved;
  2416. }
  2417.  
  2418. inline void b2DynamicTree::ClearMoved(int32 proxyId) {
  2419.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
  2420.     m_nodes[proxyId].moved = false;
  2421. }
  2422.  
  2423. inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const {
  2424.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
  2425.     return m_nodes[proxyId].aabb;
  2426. }
  2427.  
  2428. template <typename T>
  2429. inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const {
  2430.     b2GrowableStack<int32, 256> stack;
  2431.     stack.Push(m_root);
  2432.  
  2433.     while (stack.GetCount() > 0) {
  2434.         int32 nodeId = stack.Pop();
  2435.         if (nodeId == b2_nullNode) {
  2436.             continue;
  2437.         }
  2438.  
  2439.         const b2TreeNode* node = m_nodes + nodeId;
  2440.  
  2441.         if (b2TestOverlap(node->aabb, aabb)) {
  2442.             if (node->IsLeaf()) {
  2443.                 bool proceed = callback->QueryCallback(nodeId);
  2444.                 if (proceed == false) {
  2445.                     return;
  2446.                 }
  2447.             } else {
  2448.                 stack.Push(node->child1);
  2449.                 stack.Push(node->child2);
  2450.             }
  2451.         }
  2452.     }
  2453. }
  2454.  
  2455. template <typename T>
  2456. inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const {
  2457.     b2Vec2 p1 = input.p1;
  2458.     b2Vec2 p2 = input.p2;
  2459.     b2Vec2 r = p2 - p1;
  2460.     b2Assert(r.LengthSquared() > 0.0f);
  2461.     r.Normalize();
  2462.  
  2463.     // v is perpendicular to the segment.
  2464.     b2Vec2 v = b2Cross(1.0f, r);
  2465.     b2Vec2 abs_v = b2Abs(v);
  2466.  
  2467.     // Separating axis for segment (Gino, p80).
  2468.     // |dot(v, p1 - c)| > dot(|v|, h)
  2469.  
  2470.     float maxFraction = input.maxFraction;
  2471.  
  2472.     // Build a bounding box for the segment.
  2473.     b2AABB segmentAABB;
  2474.     {
  2475.         b2Vec2 t = p1 + maxFraction * (p2 - p1);
  2476.         segmentAABB.lowerBound = b2Min(p1, t);
  2477.         segmentAABB.upperBound = b2Max(p1, t);
  2478.     }
  2479.  
  2480.     b2GrowableStack<int32, 256> stack;
  2481.     stack.Push(m_root);
  2482.  
  2483.     while (stack.GetCount() > 0) {
  2484.         int32 nodeId = stack.Pop();
  2485.         if (nodeId == b2_nullNode) {
  2486.             continue;
  2487.         }
  2488.  
  2489.         const b2TreeNode* node = m_nodes + nodeId;
  2490.  
  2491.         if (b2TestOverlap(node->aabb, segmentAABB) == false) {
  2492.             continue;
  2493.         }
  2494.  
  2495.         // Separating axis for segment (Gino, p80).
  2496.         // |dot(v, p1 - c)| > dot(|v|, h)
  2497.         b2Vec2 c = node->aabb.GetCenter();
  2498.         b2Vec2 h = node->aabb.GetExtents();
  2499.         float separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h);
  2500.         if (separation > 0.0f) {
  2501.             continue;
  2502.         }
  2503.  
  2504.         if (node->IsLeaf()) {
  2505.             b2RayCastInput subInput;
  2506.             subInput.p1 = input.p1;
  2507.             subInput.p2 = input.p2;
  2508.             subInput.maxFraction = maxFraction;
  2509.  
  2510.             float value = callback->RayCastCallback(subInput, nodeId);
  2511.  
  2512.             if (value == 0.0f) {
  2513.                 // The client has terminated the ray cast.
  2514.                 return;
  2515.             }
  2516.  
  2517.             if (value > 0.0f) {
  2518.                 // Update segment bounding box.
  2519.                 maxFraction = value;
  2520.                 b2Vec2 t = p1 + maxFraction * (p2 - p1);
  2521.                 segmentAABB.lowerBound = b2Min(p1, t);
  2522.                 segmentAABB.upperBound = b2Max(p1, t);
  2523.             }
  2524.         } else {
  2525.             stack.Push(node->child1);
  2526.             stack.Push(node->child2);
  2527.         }
  2528.     }
  2529. }
  2530.  
  2531. #endif
  2532. // MIT License
  2533.  
  2534. // Copyright (c) 2019 Erin Catto
  2535.  
  2536. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2537. // of this software and associated documentation files (the "Software"), to deal
  2538. // in the Software without restriction, including without limitation the rights
  2539. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2540. // copies of the Software, and to permit persons to whom the Software is
  2541. // furnished to do so, subject to the following conditions:
  2542.  
  2543. // The above copyright notice and this permission notice shall be included in all
  2544. // copies or substantial portions of the Software.
  2545.  
  2546. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2547. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2548. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2549. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2550. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2551. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  2552. // SOFTWARE.
  2553.  
  2554. #ifndef B2_BROAD_PHASE_H
  2555. #define B2_BROAD_PHASE_H
  2556.  
  2557. //#include "b2_api.h"
  2558. //#include "b2_settings.h"
  2559. //#include "b2_collision.h"
  2560. //#include "b2_dynamic_tree.h"
  2561.  
  2562. struct B2_API b2Pair {
  2563.     int32 proxyIdA;
  2564.     int32 proxyIdB;
  2565. };
  2566.  
  2567. /// The broad-phase is used for computing pairs and performing volume queries and ray casts.
  2568. /// This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
  2569. /// It is up to the client to consume the new pairs and to track subsequent overlap.
  2570. class B2_API b2BroadPhase {
  2571. public:
  2572.  
  2573.     enum {
  2574.         e_nullProxy = -1
  2575.     };
  2576.  
  2577.     b2BroadPhase();
  2578.     ~b2BroadPhase();
  2579.  
  2580.     /// Create a proxy with an initial AABB. Pairs are not reported until
  2581.     /// UpdatePairs is called.
  2582.     int32 CreateProxy(const b2AABB& aabb, void* userData);
  2583.  
  2584.     /// Destroy a proxy. It is up to the client to remove any pairs.
  2585.     void DestroyProxy(int32 proxyId);
  2586.  
  2587.     /// Call MoveProxy as many times as you like, then when you are done
  2588.     /// call UpdatePairs to finalized the proxy pairs (for your time step).
  2589.     void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement);
  2590.  
  2591.     /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs.
  2592.     void TouchProxy(int32 proxyId);
  2593.  
  2594.     /// Get the fat AABB for a proxy.
  2595.     const b2AABB& GetFatAABB(int32 proxyId) const;
  2596.  
  2597.     /// Get user data from a proxy. Returns nullptr if the id is invalid.
  2598.     void* GetUserData(int32 proxyId) const;
  2599.  
  2600.     /// Test overlap of fat AABBs.
  2601.     bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const;
  2602.  
  2603.     /// Get the number of proxies.
  2604.     int32 GetProxyCount() const;
  2605.  
  2606.     /// Update the pairs. This results in pair callbacks. This can only add pairs.
  2607.     template <typename T>
  2608.     void UpdatePairs(T* callback);
  2609.  
  2610.     /// Query an AABB for overlapping proxies. The callback class
  2611.     /// is called for each proxy that overlaps the supplied AABB.
  2612.     template <typename T>
  2613.     void Query(T* callback, const b2AABB& aabb) const;
  2614.  
  2615.     /// Ray-cast against the proxies in the tree. This relies on the callback
  2616.     /// to perform a exact ray-cast in the case were the proxy contains a shape.
  2617.     /// The callback also performs the any collision filtering. This has performance
  2618.     /// roughly equal to k * log(n), where k is the number of collisions and n is the
  2619.     /// number of proxies in the tree.
  2620.     /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
  2621.     /// @param callback a callback class that is called for each proxy that is hit by the ray.
  2622.     template <typename T>
  2623.     void RayCast(T* callback, const b2RayCastInput& input) const;
  2624.  
  2625.     /// Get the height of the embedded tree.
  2626.     int32 GetTreeHeight() const;
  2627.  
  2628.     /// Get the balance of the embedded tree.
  2629.     int32 GetTreeBalance() const;
  2630.  
  2631.     /// Get the quality metric of the embedded tree.
  2632.     float GetTreeQuality() const;
  2633.  
  2634.     /// Shift the world origin. Useful for large worlds.
  2635.     /// The shift formula is: position -= newOrigin
  2636.     /// @param newOrigin the new origin with respect to the old origin
  2637.     void ShiftOrigin(const b2Vec2& newOrigin);
  2638.  
  2639. private:
  2640.  
  2641.     friend class b2DynamicTree;
  2642.  
  2643.     void BufferMove(int32 proxyId);
  2644.     void UnBufferMove(int32 proxyId);
  2645.  
  2646.     bool QueryCallback(int32 proxyId);
  2647.  
  2648.     b2DynamicTree m_tree;
  2649.  
  2650.     int32 m_proxyCount;
  2651.  
  2652.     int32* m_moveBuffer;
  2653.     int32 m_moveCapacity;
  2654.     int32 m_moveCount;
  2655.  
  2656.     b2Pair* m_pairBuffer;
  2657.     int32 m_pairCapacity;
  2658.     int32 m_pairCount;
  2659.  
  2660.     int32 m_queryProxyId;
  2661. };
  2662.  
  2663. inline void* b2BroadPhase::GetUserData(int32 proxyId) const {
  2664.     return m_tree.GetUserData(proxyId);
  2665. }
  2666.  
  2667. inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const {
  2668.     const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA);
  2669.     const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB);
  2670.     return b2TestOverlap(aabbA, aabbB);
  2671. }
  2672.  
  2673. inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const {
  2674.     return m_tree.GetFatAABB(proxyId);
  2675. }
  2676.  
  2677. inline int32 b2BroadPhase::GetProxyCount() const {
  2678.     return m_proxyCount;
  2679. }
  2680.  
  2681. inline int32 b2BroadPhase::GetTreeHeight() const {
  2682.     return m_tree.GetHeight();
  2683. }
  2684.  
  2685. inline int32 b2BroadPhase::GetTreeBalance() const {
  2686.     return m_tree.GetMaxBalance();
  2687. }
  2688.  
  2689. inline float b2BroadPhase::GetTreeQuality() const {
  2690.     return m_tree.GetAreaRatio();
  2691. }
  2692.  
  2693. template <typename T>
  2694. void b2BroadPhase::UpdatePairs(T* callback) {
  2695.     // Reset pair buffer
  2696.     m_pairCount = 0;
  2697.  
  2698.     // Perform tree queries for all moving proxies.
  2699.     for (int32 i = 0; i < m_moveCount; ++i) {
  2700.         m_queryProxyId = m_moveBuffer[i];
  2701.         if (m_queryProxyId == e_nullProxy) {
  2702.             continue;
  2703.         }
  2704.  
  2705.         // We have to query the tree with the fat AABB so that
  2706.         // we don't fail to create a pair that may touch later.
  2707.         const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId);
  2708.  
  2709.         // Query tree, create pairs and add them pair buffer.
  2710.         m_tree.Query(this, fatAABB);
  2711.     }
  2712.  
  2713.     // Send pairs to caller
  2714.     for (int32 i = 0; i < m_pairCount; ++i) {
  2715.         b2Pair* primaryPair = m_pairBuffer + i;
  2716.         void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA);
  2717.         void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB);
  2718.  
  2719.         callback->AddPair(userDataA, userDataB);
  2720.     }
  2721.  
  2722.     // Clear move flags
  2723.     for (int32 i = 0; i < m_moveCount; ++i) {
  2724.         int32 proxyId = m_moveBuffer[i];
  2725.         if (proxyId == e_nullProxy) {
  2726.             continue;
  2727.         }
  2728.  
  2729.         m_tree.ClearMoved(proxyId);
  2730.     }
  2731.  
  2732.     // Reset move buffer
  2733.     m_moveCount = 0;
  2734. }
  2735.  
  2736. template <typename T>
  2737. inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const {
  2738.     m_tree.Query(callback, aabb);
  2739. }
  2740.  
  2741. template <typename T>
  2742. inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const {
  2743.     m_tree.RayCast(callback, input);
  2744. }
  2745.  
  2746. inline void b2BroadPhase::ShiftOrigin(const b2Vec2& newOrigin) {
  2747.     m_tree.ShiftOrigin(newOrigin);
  2748. }
  2749.  
  2750. #endif
  2751. // MIT License
  2752.  
  2753. // Copyright (c) 2019 Erin Catto
  2754.  
  2755. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2756. // of this software and associated documentation files (the "Software"), to deal
  2757. // in the Software without restriction, including without limitation the rights
  2758. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2759. // copies of the Software, and to permit persons to whom the Software is
  2760. // furnished to do so, subject to the following conditions:
  2761.  
  2762. // The above copyright notice and this permission notice shall be included in all
  2763. // copies or substantial portions of the Software.
  2764.  
  2765. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2766. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2767. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2768. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2769. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2770. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  2771. // SOFTWARE.
  2772.  
  2773. #ifndef B2_CHAIN_SHAPE_H
  2774. #define B2_CHAIN_SHAPE_H
  2775.  
  2776. //#include "b2_api.h"
  2777. //#include "b2_shape.h"
  2778.  
  2779. class b2EdgeShape;
  2780.  
  2781. /// A chain shape is a free form sequence of line segments.
  2782. /// The chain has one-sided collision, with the surface normal pointing to the right of the edge.
  2783. /// This provides a counter-clockwise winding like the polygon shape.
  2784. /// Connectivity information is used to create smooth collisions.
  2785. /// @warning the chain will not collide properly if there are self-intersections.
  2786. class B2_API b2ChainShape : public b2Shape {
  2787. public:
  2788.     b2ChainShape();
  2789.  
  2790.     /// The destructor frees the vertices using b2Free.
  2791.     ~b2ChainShape();
  2792.  
  2793.     /// Clear all data.
  2794.     void Clear();
  2795.  
  2796.     /// Create a loop. This automatically adjusts connectivity.
  2797.     /// @param vertices an array of vertices, these are copied
  2798.     /// @param count the vertex count
  2799.     void CreateLoop(const b2Vec2* vertices, int32 count);
  2800.  
  2801.     /// Create a chain with ghost vertices to connect multiple chains together.
  2802.     /// @param vertices an array of vertices, these are copied
  2803.     /// @param count the vertex count
  2804.     /// @param prevVertex previous vertex from chain that connects to the start
  2805.     /// @param nextVertex next vertex from chain that connects to the end
  2806.     void CreateChain(const b2Vec2* vertices, int32 count,
  2807.         const b2Vec2& prevVertex, const b2Vec2& nextVertex);
  2808.  
  2809.     /// Implement b2Shape. Vertices are cloned using b2Alloc.
  2810.     b2Shape* Clone(b2BlockAllocator* allocator) const override;
  2811.  
  2812.     /// @see b2Shape::GetChildCount
  2813.     int32 GetChildCount() const override;
  2814.  
  2815.     /// Get a child edge.
  2816.     void GetChildEdge(b2EdgeShape* edge, int32 index) const;
  2817.  
  2818.     /// This always return false.
  2819.     /// @see b2Shape::TestPoint
  2820.     bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override;
  2821.  
  2822.     /// Implement b2Shape.
  2823.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  2824.         const b2Transform& transform, int32 childIndex) const override;
  2825.  
  2826.     /// @see b2Shape::ComputeAABB
  2827.     void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override;
  2828.  
  2829.     /// Chains have zero mass.
  2830.     /// @see b2Shape::ComputeMass
  2831.     void ComputeMass(b2MassData* massData, float density) const override;
  2832.  
  2833.     /// The vertices. Owned by this class.
  2834.     b2Vec2* m_vertices;
  2835.  
  2836.     /// The vertex count.
  2837.     int32 m_count;
  2838.  
  2839.     b2Vec2 m_prevVertex, m_nextVertex;
  2840. };
  2841.  
  2842. inline b2ChainShape::b2ChainShape() {
  2843.     m_type = e_chain;
  2844.     m_radius = b2_polygonRadius;
  2845.     m_vertices = nullptr;
  2846.     m_count = 0;
  2847. }
  2848.  
  2849. #endif
  2850. // MIT License
  2851.  
  2852. // Copyright (c) 2019 Erin Catto
  2853.  
  2854. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2855. // of this software and associated documentation files (the "Software"), to deal
  2856. // in the Software without restriction, including without limitation the rights
  2857. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2858. // copies of the Software, and to permit persons to whom the Software is
  2859. // furnished to do so, subject to the following conditions:
  2860.  
  2861. // The above copyright notice and this permission notice shall be included in all
  2862. // copies or substantial portions of the Software.
  2863.  
  2864. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2865. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2866. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2867. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2868. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2869. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  2870. // SOFTWARE.
  2871.  
  2872. #ifndef B2_CIRCLE_SHAPE_H
  2873. #define B2_CIRCLE_SHAPE_H
  2874.  
  2875. //#include "b2_api.h"
  2876. //#include "b2_shape.h"
  2877.  
  2878. /// A solid circle shape
  2879. class B2_API b2CircleShape : public b2Shape {
  2880. public:
  2881.     b2CircleShape();
  2882.  
  2883.     /// Implement b2Shape.
  2884.     b2Shape* Clone(b2BlockAllocator* allocator) const override;
  2885.  
  2886.     /// @see b2Shape::GetChildCount
  2887.     int32 GetChildCount() const override;
  2888.  
  2889.     /// Implement b2Shape.
  2890.     bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override;
  2891.  
  2892.     /// Implement b2Shape.
  2893.     /// @note because the circle is solid, rays that start inside do not hit because the normal is
  2894.     /// not defined.
  2895.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  2896.         const b2Transform& transform, int32 childIndex) const override;
  2897.  
  2898.     /// @see b2Shape::ComputeAABB
  2899.     void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override;
  2900.  
  2901.     /// @see b2Shape::ComputeMass
  2902.     void ComputeMass(b2MassData* massData, float density) const override;
  2903.  
  2904.     /// Position
  2905.     b2Vec2 m_p;
  2906. };
  2907.  
  2908. inline b2CircleShape::b2CircleShape() {
  2909.     m_type = e_circle;
  2910.     m_radius = 0.0f;
  2911.     m_p.SetZero();
  2912. }
  2913.  
  2914. #endif
  2915. // MIT License
  2916.  
  2917. // Copyright (c) 2019 Erin Catto
  2918.  
  2919. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2920. // of this software and associated documentation files (the "Software"), to deal
  2921. // in the Software without restriction, including without limitation the rights
  2922. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2923. // copies of the Software, and to permit persons to whom the Software is
  2924. // furnished to do so, subject to the following conditions:
  2925.  
  2926. // The above copyright notice and this permission notice shall be included in all
  2927. // copies or substantial portions of the Software.
  2928.  
  2929. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2930. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2931. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2932. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2933. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2934. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  2935. // SOFTWARE.
  2936.  
  2937. #ifndef B2_COMMON_H
  2938. #define B2_COMMON_H
  2939.  
  2940. //#include "b2_settings.h"
  2941.  
  2942.  
  2943. /// @file
  2944. /// Global tuning constants based on meters-kilograms-seconds (MKS) units.
  2945. ///
  2946.  
  2947. // Collision
  2948.  
  2949.  
  2950. // Dynamics
  2951.  
  2952. /// Maximum number of contacts to be handled to solve a TOI impact.
  2953. #define b2_maxTOIContacts           32
  2954.  
  2955. /// The maximum linear position correction used when solving constraints. This helps to
  2956. /// prevent overshoot. Meters.
  2957. #define b2_maxLinearCorrection      (0.2f * b2_lengthUnitsPerMeter)
  2958.  
  2959. /// The maximum angular position correction used when solving constraints. This helps to
  2960. /// prevent overshoot.
  2961. #define b2_maxAngularCorrection     (8.0f / 180.0f * b2_pi)
  2962.  
  2963. /// The maximum linear translation of a body per step. This limit is very large and is used
  2964. /// to prevent numerical problems. You shouldn't need to adjust this. Meters.
  2965. #define b2_maxTranslation           (2.0f * b2_lengthUnitsPerMeter)
  2966. #define b2_maxTranslationSquared    (b2_maxTranslation * b2_maxTranslation)
  2967.  
  2968. /// The maximum angular velocity of a body. This limit is very large and is used
  2969. /// to prevent numerical problems. You shouldn't need to adjust this.
  2970. #define b2_maxRotation              (0.5f * b2_pi)
  2971. #define b2_maxRotationSquared       (b2_maxRotation * b2_maxRotation)
  2972.  
  2973. /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so
  2974. /// that overlap is removed in one time step. However using values close to 1 often lead
  2975. /// to overshoot.
  2976. #define b2_baumgarte                0.2f
  2977. #define b2_toiBaumgarte             0.75f
  2978.  
  2979.  
  2980. // Sleep
  2981.  
  2982. /// The time that a body must be still before it will go to sleep.
  2983. #define b2_timeToSleep              0.5f
  2984.  
  2985. /// A body cannot sleep if its linear velocity is above this tolerance.
  2986. #define b2_linearSleepTolerance     (0.01f * b2_lengthUnitsPerMeter)
  2987.  
  2988. /// A body cannot sleep if its angular velocity is above this tolerance.
  2989. #define b2_angularSleepTolerance    (2.0f / 180.0f * b2_pi)
  2990.  
  2991. /// Dump to a file. Only one dump file allowed at a time.
  2992. void b2OpenDump(const char* fileName);
  2993. void b2Dump(const char* string, ...);
  2994. void b2CloseDump();
  2995.  
  2996. /// Version numbering scheme.
  2997. /// See http://en.wikipedia.org/wiki/Software_versioning
  2998. struct b2Version {
  2999.     int32 major;        ///< significant changes
  3000.     int32 minor;        ///< incremental changes
  3001.     int32 revision;     ///< bug fixes
  3002. };
  3003.  
  3004. /// Current version.
  3005. extern B2_API b2Version b2_version;
  3006.  
  3007. #endif
  3008. // MIT License
  3009.  
  3010. // Copyright (c) 2019 Erin Catto
  3011.  
  3012. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3013. // of this software and associated documentation files (the "Software"), to deal
  3014. // in the Software without restriction, including without limitation the rights
  3015. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  3016. // copies of the Software, and to permit persons to whom the Software is
  3017. // furnished to do so, subject to the following conditions:
  3018.  
  3019. // The above copyright notice and this permission notice shall be included in all
  3020. // copies or substantial portions of the Software.
  3021.  
  3022. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3023. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3024. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3025. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3026. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3027. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  3028. // SOFTWARE.
  3029.  
  3030. #ifndef B2_FIXTURE_H
  3031. #define B2_FIXTURE_H
  3032.  
  3033. //#include "b2_api.h"
  3034. //#include "b2_body.h"
  3035. //#include "b2_collision.h"
  3036. //#include "b2_shape.h"
  3037.  
  3038. class b2BlockAllocator;
  3039. class b2Body;
  3040. class b2BroadPhase;
  3041. class b2Fixture;
  3042.  
  3043. /// This holds contact filtering data.
  3044. struct B2_API b2Filter {
  3045.     b2Filter() {
  3046.         categoryBits = 0x0001;
  3047.         maskBits = 0xFFFF;
  3048.         groupIndex = 0;
  3049.     }
  3050.  
  3051.     /// The collision category bits. Normally you would just set one bit.
  3052.     uint16 categoryBits;
  3053.  
  3054.     /// The collision mask bits. This states the categories that this
  3055.     /// shape would accept for collision.
  3056.     uint16 maskBits;
  3057.  
  3058.     /// Collision groups allow a certain group of objects to never collide (negative)
  3059.     /// or always collide (positive). Zero means no collision group. Non-zero group
  3060.     /// filtering always wins against the mask bits.
  3061.     int16 groupIndex;
  3062. };
  3063.  
  3064. /// A fixture definition is used to create a fixture. This class defines an
  3065. /// abstract fixture definition. You can reuse fixture definitions safely.
  3066. struct B2_API b2FixtureDef {
  3067.     /// The constructor sets the default fixture definition values.
  3068.     b2FixtureDef() {
  3069.         shape = nullptr;
  3070.         friction = 0.2f;
  3071.         restitution = 0.0f;
  3072.         restitutionThreshold = 1.0f * b2_lengthUnitsPerMeter;
  3073.         density = 0.0f;
  3074.         isSensor = false;
  3075.     }
  3076.  
  3077.     /// The shape, this must be set. The shape will be cloned, so you
  3078.     /// can create the shape on the stack.
  3079.     const b2Shape* shape;
  3080.  
  3081.     /// Use this to store application specific fixture data.
  3082.     b2FixtureUserData userData;
  3083.  
  3084.     /// The friction coefficient, usually in the range [0,1].
  3085.     float friction;
  3086.  
  3087.     /// The restitution (elasticity) usually in the range [0,1].
  3088.     float restitution;
  3089.  
  3090.     /// Restitution velocity threshold, usually in m/s. Collisions above this
  3091.     /// speed have restitution applied (will bounce).
  3092.     float restitutionThreshold;
  3093.  
  3094.     /// The density, usually in kg/m^2.
  3095.     float density;
  3096.  
  3097.     /// A sensor shape collects contact information but never generates a collision
  3098.     /// response.
  3099.     bool isSensor;
  3100.  
  3101.     /// Contact filtering data.
  3102.     b2Filter filter;
  3103. };
  3104.  
  3105. /// This proxy is used internally to connect fixtures to the broad-phase.
  3106. struct B2_API b2FixtureProxy {
  3107.     b2AABB aabb;
  3108.     b2Fixture* fixture;
  3109.     int32 childIndex;
  3110.     int32 proxyId;
  3111. };
  3112.  
  3113. /// A fixture is used to attach a shape to a body for collision detection. A fixture
  3114. /// inherits its transform from its parent. Fixtures hold additional non-geometric data
  3115. /// such as friction, collision filters, etc.
  3116. /// Fixtures are created via b2Body::CreateFixture.
  3117. /// @warning you cannot reuse fixtures.
  3118. class B2_API b2Fixture {
  3119. public:
  3120.     /// Get the type of the child shape. You can use this to down cast to the concrete shape.
  3121.     /// @return the shape type.
  3122.     b2Shape::Type GetType() const;
  3123.  
  3124.     /// Get the child shape. You can modify the child shape, however you should not change the
  3125.     /// number of vertices because this will crash some collision caching mechanisms.
  3126.     /// Manipulating the shape may lead to non-physical behavior.
  3127.     b2Shape* GetShape();
  3128.     const b2Shape* GetShape() const;
  3129.  
  3130.     /// Set if this fixture is a sensor.
  3131.     void SetSensor(bool sensor);
  3132.  
  3133.     /// Is this fixture a sensor (non-solid)?
  3134.     /// @return the true if the shape is a sensor.
  3135.     bool IsSensor() const;
  3136.  
  3137.     /// Set the contact filtering data. This will not update contacts until the next time
  3138.     /// step when either parent body is active and awake.
  3139.     /// This automatically calls Refilter.
  3140.     void SetFilterData(const b2Filter& filter);
  3141.  
  3142.     /// Get the contact filtering data.
  3143.     const b2Filter& GetFilterData() const;
  3144.  
  3145.     /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide.
  3146.     void Refilter();
  3147.  
  3148.     /// Get the parent body of this fixture. This is nullptr if the fixture is not attached.
  3149.     /// @return the parent body.
  3150.     b2Body* GetBody();
  3151.     const b2Body* GetBody() const;
  3152.  
  3153.     /// Get the next fixture in the parent body's fixture list.
  3154.     /// @return the next shape.
  3155.     b2Fixture* GetNext();
  3156.     const b2Fixture* GetNext() const;
  3157.  
  3158.     /// Get the user data that was assigned in the fixture definition. Use this to
  3159.     /// store your application specific data.
  3160.     b2FixtureUserData& GetUserData();
  3161.  
  3162.     /// Test a point for containment in this fixture.
  3163.     /// @param p a point in world coordinates.
  3164.     bool TestPoint(const b2Vec2& p) const;
  3165.  
  3166.     /// Cast a ray against this shape.
  3167.     /// @param output the ray-cast results.
  3168.     /// @param input the ray-cast input parameters.
  3169.     /// @param childIndex the child shape index (e.g. edge index)
  3170.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const;
  3171.  
  3172.     /// Get the mass data for this fixture. The mass data is based on the density and
  3173.     /// the shape. The rotational inertia is about the shape's origin. This operation
  3174.     /// may be expensive.
  3175.     void GetMassData(b2MassData* massData) const;
  3176.  
  3177.     /// Set the density of this fixture. This will _not_ automatically adjust the mass
  3178.     /// of the body. You must call b2Body::ResetMassData to update the body's mass.
  3179.     void SetDensity(float density);
  3180.  
  3181.     /// Get the density of this fixture.
  3182.     float GetDensity() const;
  3183.  
  3184.     /// Get the coefficient of friction.
  3185.     float GetFriction() const;
  3186.  
  3187.     /// Set the coefficient of friction. This will _not_ change the friction of
  3188.     /// existing contacts.
  3189.     void SetFriction(float friction);
  3190.  
  3191.     /// Get the coefficient of restitution.
  3192.     float GetRestitution() const;
  3193.  
  3194.     /// Set the coefficient of restitution. This will _not_ change the restitution of
  3195.     /// existing contacts.
  3196.     void SetRestitution(float restitution);
  3197.  
  3198.     /// Get the restitution velocity threshold.
  3199.     float GetRestitutionThreshold() const;
  3200.  
  3201.     /// Set the restitution threshold. This will _not_ change the restitution threshold of
  3202.     /// existing contacts.
  3203.     void SetRestitutionThreshold(float threshold);
  3204.  
  3205.     /// Get the fixture's AABB. This AABB may be enlarge and/or stale.
  3206.     /// If you need a more accurate AABB, compute it using the shape and
  3207.     /// the body transform.
  3208.     const b2AABB& GetAABB(int32 childIndex) const;
  3209.  
  3210.     /// Dump this fixture to the log file.
  3211.     void Dump(int32 bodyIndex);
  3212.  
  3213. protected:
  3214.  
  3215.     friend class b2Body;
  3216.     friend class b2World;
  3217.     friend class b2Contact;
  3218.     friend class b2ContactManager;
  3219.  
  3220.     b2Fixture();
  3221.  
  3222.     // We need separation create/destroy functions from the constructor/destructor because
  3223.     // the destructor cannot access the allocator (no destructor arguments allowed by C++).
  3224.     void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def);
  3225.     void Destroy(b2BlockAllocator* allocator);
  3226.  
  3227.     // These support body activation/deactivation.
  3228.     void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf);
  3229.     void DestroyProxies(b2BroadPhase* broadPhase);
  3230.  
  3231.     void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2);
  3232.  
  3233.     float m_density;
  3234.  
  3235.     b2Fixture* m_next;
  3236.     b2Body* m_body;
  3237.  
  3238.     b2Shape* m_shape;
  3239.  
  3240.     float m_friction;
  3241.     float m_restitution;
  3242.     float m_restitutionThreshold;
  3243.  
  3244.     b2FixtureProxy* m_proxies;
  3245.     int32 m_proxyCount;
  3246.  
  3247.     b2Filter m_filter;
  3248.  
  3249.     bool m_isSensor;
  3250.  
  3251.     b2FixtureUserData m_userData;
  3252. };
  3253.  
  3254. inline b2Shape::Type b2Fixture::GetType() const {
  3255.     return m_shape->GetType();
  3256. }
  3257.  
  3258. inline b2Shape* b2Fixture::GetShape() {
  3259.     return m_shape;
  3260. }
  3261.  
  3262. inline const b2Shape* b2Fixture::GetShape() const {
  3263.     return m_shape;
  3264. }
  3265.  
  3266. inline bool b2Fixture::IsSensor() const {
  3267.     return m_isSensor;
  3268. }
  3269.  
  3270. inline const b2Filter& b2Fixture::GetFilterData() const {
  3271.     return m_filter;
  3272. }
  3273.  
  3274. inline b2FixtureUserData& b2Fixture::GetUserData() {
  3275.     return m_userData;
  3276. }
  3277.  
  3278. inline b2Body* b2Fixture::GetBody() {
  3279.     return m_body;
  3280. }
  3281.  
  3282. inline const b2Body* b2Fixture::GetBody() const {
  3283.     return m_body;
  3284. }
  3285.  
  3286. inline b2Fixture* b2Fixture::GetNext() {
  3287.     return m_next;
  3288. }
  3289.  
  3290. inline const b2Fixture* b2Fixture::GetNext() const {
  3291.     return m_next;
  3292. }
  3293.  
  3294. inline void b2Fixture::SetDensity(float density) {
  3295.     b2Assert(b2IsValid(density) && density >= 0.0f);
  3296.     m_density = density;
  3297. }
  3298.  
  3299. inline float b2Fixture::GetDensity() const {
  3300.     return m_density;
  3301. }
  3302.  
  3303. inline float b2Fixture::GetFriction() const {
  3304.     return m_friction;
  3305. }
  3306.  
  3307. inline void b2Fixture::SetFriction(float friction) {
  3308.     m_friction = friction;
  3309. }
  3310.  
  3311. inline float b2Fixture::GetRestitution() const {
  3312.     return m_restitution;
  3313. }
  3314.  
  3315. inline void b2Fixture::SetRestitution(float restitution) {
  3316.     m_restitution = restitution;
  3317. }
  3318.  
  3319. inline float b2Fixture::GetRestitutionThreshold() const {
  3320.     return m_restitutionThreshold;
  3321. }
  3322.  
  3323. inline void b2Fixture::SetRestitutionThreshold(float threshold) {
  3324.     m_restitutionThreshold = threshold;
  3325. }
  3326.  
  3327. inline bool b2Fixture::TestPoint(const b2Vec2& p) const {
  3328.     return m_shape->TestPoint(m_body->GetTransform(), p);
  3329. }
  3330.  
  3331. inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const {
  3332.     return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex);
  3333. }
  3334.  
  3335. inline void b2Fixture::GetMassData(b2MassData* massData) const {
  3336.     m_shape->ComputeMass(massData, m_density);
  3337. }
  3338.  
  3339. inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const {
  3340.     b2Assert(0 <= childIndex && childIndex < m_proxyCount);
  3341.     return m_proxies[childIndex].aabb;
  3342. }
  3343.  
  3344. #endif
  3345. // MIT License
  3346.  
  3347. // Copyright (c) 2019 Erin Catto
  3348.  
  3349. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3350. // of this software and associated documentation files (the "Software"), to deal
  3351. // in the Software without restriction, including without limitation the rights
  3352. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  3353. // copies of the Software, and to permit persons to whom the Software is
  3354. // furnished to do so, subject to the following conditions:
  3355.  
  3356. // The above copyright notice and this permission notice shall be included in all
  3357. // copies or substantial portions of the Software.
  3358.  
  3359. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3360. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3361. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3362. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3363. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3364. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  3365. // SOFTWARE.
  3366.  
  3367. #ifndef B2_CONTACT_H
  3368. #define B2_CONTACT_H
  3369.  
  3370. //#include "b2_api.h"
  3371. //#include "b2_collision.h"
  3372. //#include "b2_fixture.h"
  3373. //#include "b2_math.h"
  3374. //#include "b2_shape.h"
  3375.  
  3376. class b2Body;
  3377. class b2Contact;
  3378. class b2Fixture;
  3379. class b2World;
  3380. class b2BlockAllocator;
  3381. class b2StackAllocator;
  3382. class b2ContactListener;
  3383.  
  3384. /// Friction mixing law. The idea is to allow either fixture to drive the friction to zero.
  3385. /// For example, anything slides on ice.
  3386. inline float b2MixFriction(float friction1, float friction2) {
  3387.     return b2Sqrt(friction1 * friction2);
  3388. }
  3389.  
  3390. /// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface.
  3391. /// For example, a superball bounces on anything.
  3392. inline float b2MixRestitution(float restitution1, float restitution2) {
  3393.     return restitution1 > restitution2 ? restitution1 : restitution2;
  3394. }
  3395.  
  3396. /// Restitution mixing law. This picks the lowest value.
  3397. inline float b2MixRestitutionThreshold(float threshold1, float threshold2) {
  3398.     return threshold1 < threshold2 ? threshold1 : threshold2;
  3399. }
  3400.  
  3401. typedef b2Contact* b2ContactCreateFcn(b2Fixture* fixtureA, int32 indexA,
  3402.     b2Fixture* fixtureB, int32 indexB,
  3403.     b2BlockAllocator* allocator);
  3404. typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator);
  3405.  
  3406. struct B2_API b2ContactRegister {
  3407.     b2ContactCreateFcn* createFcn;
  3408.     b2ContactDestroyFcn* destroyFcn;
  3409.     bool primary;
  3410. };
  3411.  
  3412. /// A contact edge is used to connect bodies and contacts together
  3413. /// in a contact graph where each body is a node and each contact
  3414. /// is an edge. A contact edge belongs to a doubly linked list
  3415. /// maintained in each attached body. Each contact has two contact
  3416. /// nodes, one for each attached body.
  3417. struct B2_API b2ContactEdge {
  3418.     b2Body* other;          ///< provides quick access to the other body attached.
  3419.     b2Contact* contact;     ///< the contact
  3420.     b2ContactEdge* prev;    ///< the previous contact edge in the body's contact list
  3421.     b2ContactEdge* next;    ///< the next contact edge in the body's contact list
  3422. };
  3423.  
  3424. /// The class manages contact between two shapes. A contact exists for each overlapping
  3425. /// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
  3426. /// that has no contact points.
  3427. class B2_API b2Contact {
  3428. public:
  3429.  
  3430.     /// Get the contact manifold. Do not modify the manifold unless you understand the
  3431.     /// internals of Box2D.
  3432.     b2Manifold* GetManifold();
  3433.     const b2Manifold* GetManifold() const;
  3434.  
  3435.     /// Get the world manifold.
  3436.     void GetWorldManifold(b2WorldManifold* worldManifold) const;
  3437.  
  3438.     /// Is this contact touching?
  3439.     bool IsTouching() const;
  3440.  
  3441.     /// Enable/disable this contact. This can be used inside the pre-solve
  3442.     /// contact listener. The contact is only disabled for the current
  3443.     /// time step (or sub-step in continuous collisions).
  3444.     void SetEnabled(bool flag);
  3445.  
  3446.     /// Has this contact been disabled?
  3447.     bool IsEnabled() const;
  3448.  
  3449.     /// Get the next contact in the world's contact list.
  3450.     b2Contact* GetNext();
  3451.     const b2Contact* GetNext() const;
  3452.  
  3453.     /// Get fixture A in this contact.
  3454.     b2Fixture* GetFixtureA();
  3455.     const b2Fixture* GetFixtureA() const;
  3456.  
  3457.     /// Get the child primitive index for fixture A.
  3458.     int32 GetChildIndexA() const;
  3459.  
  3460.     /// Get fixture B in this contact.
  3461.     b2Fixture* GetFixtureB();
  3462.     const b2Fixture* GetFixtureB() const;
  3463.  
  3464.     /// Get the child primitive index for fixture B.
  3465.     int32 GetChildIndexB() const;
  3466.  
  3467.     /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
  3468.     /// This value persists until set or reset.
  3469.     void SetFriction(float friction);
  3470.  
  3471.     /// Get the friction.
  3472.     float GetFriction() const;
  3473.  
  3474.     /// Reset the friction mixture to the default value.
  3475.     void ResetFriction();
  3476.  
  3477.     /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
  3478.     /// The value persists until you set or reset.
  3479.     void SetRestitution(float restitution);
  3480.  
  3481.     /// Get the restitution.
  3482.     float GetRestitution() const;
  3483.  
  3484.     /// Reset the restitution to the default value.
  3485.     void ResetRestitution();
  3486.  
  3487.     /// Override the default restitution velocity threshold mixture. You can call this in b2ContactListener::PreSolve.
  3488.     /// The value persists until you set or reset.
  3489.     void SetRestitutionThreshold(float threshold);
  3490.  
  3491.     /// Get the restitution threshold.
  3492.     float GetRestitutionThreshold() const;
  3493.  
  3494.     /// Reset the restitution threshold to the default value.
  3495.     void ResetRestitutionThreshold();
  3496.  
  3497.     /// Set the desired tangent speed for a conveyor belt behavior. In meters per second.
  3498.     void SetTangentSpeed(float speed);
  3499.  
  3500.     /// Get the desired tangent speed. In meters per second.
  3501.     float GetTangentSpeed() const;
  3502.  
  3503.     /// Evaluate this contact with your own manifold and transforms.
  3504.     virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0;
  3505.  
  3506. protected:
  3507.     friend class b2ContactManager;
  3508.     friend class b2World;
  3509.     friend class b2ContactSolver;
  3510.     friend class b2Body;
  3511.     friend class b2Fixture;
  3512.  
  3513.     // Flags stored in m_flags
  3514.     enum {
  3515.         // Used when crawling contact graph when forming islands.
  3516.         e_islandFlag = 0x0001,
  3517.  
  3518.         // Set when the shapes are touching.
  3519.         e_touchingFlag = 0x0002,
  3520.  
  3521.         // This contact can be disabled (by user)
  3522.         e_enabledFlag = 0x0004,
  3523.  
  3524.         // This contact needs filtering because a fixture filter was changed.
  3525.         e_filterFlag = 0x0008,
  3526.  
  3527.         // This bullet contact had a TOI event
  3528.         e_bulletHitFlag = 0x0010,
  3529.  
  3530.         // This contact has a valid TOI in m_toi
  3531.         e_toiFlag = 0x0020
  3532.     };
  3533.  
  3534.     /// Flag this contact for filtering. Filtering will occur the next time step.
  3535.     void FlagForFiltering();
  3536.  
  3537.     static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn,
  3538.         b2Shape::Type typeA, b2Shape::Type typeB);
  3539.     static void InitializeRegisters();
  3540.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  3541.     static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator);
  3542.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  3543.  
  3544.     b2Contact() : m_fixtureA(nullptr), m_fixtureB(nullptr) {}
  3545.     b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB);
  3546.     virtual ~b2Contact() {}
  3547.  
  3548.     void Update(b2ContactListener* listener);
  3549.  
  3550.     static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount];
  3551.     static bool s_initialized;
  3552.  
  3553.     uint32 m_flags;
  3554.  
  3555.     // World pool and list pointers.
  3556.     b2Contact* m_prev;
  3557.     b2Contact* m_next;
  3558.  
  3559.     // Nodes for connecting bodies.
  3560.     b2ContactEdge m_nodeA;
  3561.     b2ContactEdge m_nodeB;
  3562.  
  3563.     b2Fixture* m_fixtureA;
  3564.     b2Fixture* m_fixtureB;
  3565.  
  3566.     int32 m_indexA;
  3567.     int32 m_indexB;
  3568.  
  3569.     b2Manifold m_manifold;
  3570.  
  3571.     int32 m_toiCount;
  3572.     float m_toi;
  3573.  
  3574.     float m_friction;
  3575.     float m_restitution;
  3576.     float m_restitutionThreshold;
  3577.  
  3578.     float m_tangentSpeed;
  3579. };
  3580.  
  3581. inline b2Manifold* b2Contact::GetManifold() {
  3582.     return &m_manifold;
  3583. }
  3584.  
  3585. inline const b2Manifold* b2Contact::GetManifold() const {
  3586.     return &m_manifold;
  3587. }
  3588.  
  3589. inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const {
  3590.     const b2Body* bodyA = m_fixtureA->GetBody();
  3591.     const b2Body* bodyB = m_fixtureB->GetBody();
  3592.     const b2Shape* shapeA = m_fixtureA->GetShape();
  3593.     const b2Shape* shapeB = m_fixtureB->GetShape();
  3594.  
  3595.     worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius);
  3596. }
  3597.  
  3598. inline void b2Contact::SetEnabled(bool flag) {
  3599.     if (flag) {
  3600.         m_flags |= e_enabledFlag;
  3601.     } else {
  3602.         m_flags &= ~e_enabledFlag;
  3603.     }
  3604. }
  3605.  
  3606. inline bool b2Contact::IsEnabled() const {
  3607.     return (m_flags & e_enabledFlag) == e_enabledFlag;
  3608. }
  3609.  
  3610. inline bool b2Contact::IsTouching() const {
  3611.     return (m_flags & e_touchingFlag) == e_touchingFlag;
  3612. }
  3613.  
  3614. inline b2Contact* b2Contact::GetNext() {
  3615.     return m_next;
  3616. }
  3617.  
  3618. inline const b2Contact* b2Contact::GetNext() const {
  3619.     return m_next;
  3620. }
  3621.  
  3622. inline b2Fixture* b2Contact::GetFixtureA() {
  3623.     return m_fixtureA;
  3624. }
  3625.  
  3626. inline const b2Fixture* b2Contact::GetFixtureA() const {
  3627.     return m_fixtureA;
  3628. }
  3629.  
  3630. inline b2Fixture* b2Contact::GetFixtureB() {
  3631.     return m_fixtureB;
  3632. }
  3633.  
  3634. inline int32 b2Contact::GetChildIndexA() const {
  3635.     return m_indexA;
  3636. }
  3637.  
  3638. inline const b2Fixture* b2Contact::GetFixtureB() const {
  3639.     return m_fixtureB;
  3640. }
  3641.  
  3642. inline int32 b2Contact::GetChildIndexB() const {
  3643.     return m_indexB;
  3644. }
  3645.  
  3646. inline void b2Contact::FlagForFiltering() {
  3647.     m_flags |= e_filterFlag;
  3648. }
  3649.  
  3650. inline void b2Contact::SetFriction(float friction) {
  3651.     m_friction = friction;
  3652. }
  3653.  
  3654. inline float b2Contact::GetFriction() const {
  3655.     return m_friction;
  3656. }
  3657.  
  3658. inline void b2Contact::ResetFriction() {
  3659.     m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction);
  3660. }
  3661.  
  3662. inline void b2Contact::SetRestitution(float restitution) {
  3663.     m_restitution = restitution;
  3664. }
  3665.  
  3666. inline float b2Contact::GetRestitution() const {
  3667.     return m_restitution;
  3668. }
  3669.  
  3670. inline void b2Contact::ResetRestitution() {
  3671.     m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution);
  3672. }
  3673.  
  3674. inline void b2Contact::SetRestitutionThreshold(float threshold) {
  3675.     m_restitutionThreshold = threshold;
  3676. }
  3677.  
  3678. inline float b2Contact::GetRestitutionThreshold() const {
  3679.     return m_restitutionThreshold;
  3680. }
  3681.  
  3682. inline void b2Contact::ResetRestitutionThreshold() {
  3683.     m_restitutionThreshold = b2MixRestitutionThreshold(m_fixtureA->m_restitutionThreshold, m_fixtureB->m_restitutionThreshold);
  3684. }
  3685.  
  3686. inline void b2Contact::SetTangentSpeed(float speed) {
  3687.     m_tangentSpeed = speed;
  3688. }
  3689.  
  3690. inline float b2Contact::GetTangentSpeed() const {
  3691.     return m_tangentSpeed;
  3692. }
  3693.  
  3694. #endif
  3695. // MIT License
  3696.  
  3697. // Copyright (c) 2019 Erin Catto
  3698.  
  3699. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3700. // of this software and associated documentation files (the "Software"), to deal
  3701. // in the Software without restriction, including without limitation the rights
  3702. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  3703. // copies of the Software, and to permit persons to whom the Software is
  3704. // furnished to do so, subject to the following conditions:
  3705.  
  3706. // The above copyright notice and this permission notice shall be included in all
  3707. // copies or substantial portions of the Software.
  3708.  
  3709. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3710. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3711. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3712. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3713. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3714. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  3715. // SOFTWARE.
  3716.  
  3717. #ifndef B2_CONTACT_MANAGER_H
  3718. #define B2_CONTACT_MANAGER_H
  3719.  
  3720. //#include "b2_api.h"
  3721. //#include "b2_broad_phase.h"
  3722.  
  3723. class b2Contact;
  3724. class b2ContactFilter;
  3725. class b2ContactListener;
  3726. class b2BlockAllocator;
  3727.  
  3728. // Delegate of b2World.
  3729. class B2_API b2ContactManager {
  3730. public:
  3731.     b2ContactManager();
  3732.  
  3733.     // Broad-phase callback.
  3734.     void AddPair(void* proxyUserDataA, void* proxyUserDataB);
  3735.  
  3736.     void FindNewContacts();
  3737.  
  3738.     void Destroy(b2Contact* c);
  3739.  
  3740.     void Collide();
  3741.  
  3742.     b2BroadPhase m_broadPhase;
  3743.     b2Contact* m_contactList;
  3744.     int32 m_contactCount;
  3745.     b2ContactFilter* m_contactFilter;
  3746.     b2ContactListener* m_contactListener;
  3747.     b2BlockAllocator* m_allocator;
  3748. };
  3749.  
  3750. #endif
  3751. // MIT License
  3752.  
  3753. // Copyright (c) 2019 Erin Catto
  3754.  
  3755. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3756. // of this software and associated documentation files (the "Software"), to deal
  3757. // in the Software without restriction, including without limitation the rights
  3758. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  3759. // copies of the Software, and to permit persons to whom the Software is
  3760. // furnished to do so, subject to the following conditions:
  3761.  
  3762. // The above copyright notice and this permission notice shall be included in all
  3763. // copies or substantial portions of the Software.
  3764.  
  3765. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3766. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3767. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3768. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3769. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3770. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  3771. // SOFTWARE.
  3772.  
  3773. #ifndef B2_DISTANCE_H
  3774. #define B2_DISTANCE_H
  3775.  
  3776. //#include "b2_api.h"
  3777. //#include "b2_math.h"
  3778.  
  3779. class b2Shape;
  3780.  
  3781. /// A distance proxy is used by the GJK algorithm.
  3782. /// It encapsulates any shape.
  3783. struct B2_API b2DistanceProxy {
  3784.     b2DistanceProxy() : m_vertices(nullptr), m_count(0), m_radius(0.0f) {}
  3785.  
  3786.     /// Initialize the proxy using the given shape. The shape
  3787.     /// must remain in scope while the proxy is in use.
  3788.     void Set(const b2Shape* shape, int32 index);
  3789.  
  3790.     /// Initialize the proxy using a vertex cloud and radius. The vertices
  3791.     /// must remain in scope while the proxy is in use.
  3792.     void Set(const b2Vec2* vertices, int32 count, float radius);
  3793.  
  3794.     /// Get the supporting vertex index in the given direction.
  3795.     int32 GetSupport(const b2Vec2& d) const;
  3796.  
  3797.     /// Get the supporting vertex in the given direction.
  3798.     const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
  3799.  
  3800.     /// Get the vertex count.
  3801.     int32 GetVertexCount() const;
  3802.  
  3803.     /// Get a vertex by index. Used by b2Distance.
  3804.     const b2Vec2& GetVertex(int32 index) const;
  3805.  
  3806.     b2Vec2 m_buffer[2];
  3807.     const b2Vec2* m_vertices;
  3808.     int32 m_count;
  3809.     float m_radius;
  3810. };
  3811.  
  3812. /// Used to warm start b2Distance.
  3813. /// Set count to zero on first call.
  3814. struct B2_API b2SimplexCache {
  3815.     float metric;       ///< length or area
  3816.     uint16 count;
  3817.     uint8 indexA[3];    ///< vertices on shape A
  3818.     uint8 indexB[3];    ///< vertices on shape B
  3819. };
  3820.  
  3821. /// Input for b2Distance.
  3822. /// You have to option to use the shape radii
  3823. /// in the computation. Even
  3824. struct B2_API b2DistanceInput {
  3825.     b2DistanceProxy proxyA;
  3826.     b2DistanceProxy proxyB;
  3827.     b2Transform transformA;
  3828.     b2Transform transformB;
  3829.     bool useRadii;
  3830. };
  3831.  
  3832. /// Output for b2Distance.
  3833. struct B2_API b2DistanceOutput {
  3834.     b2Vec2 pointA;      ///< closest point on shapeA
  3835.     b2Vec2 pointB;      ///< closest point on shapeB
  3836.     float distance;
  3837.     int32 iterations;   ///< number of GJK iterations used
  3838. };
  3839.  
  3840. /// Compute the closest points between two shapes. Supports any combination of:
  3841. /// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output.
  3842. /// On the first call set b2SimplexCache.count to zero.
  3843. B2_API void b2Distance(b2DistanceOutput* output,
  3844.     b2SimplexCache* cache,
  3845.     const b2DistanceInput* input);
  3846.  
  3847. /// Input parameters for b2ShapeCast
  3848. struct B2_API b2ShapeCastInput {
  3849.     b2DistanceProxy proxyA;
  3850.     b2DistanceProxy proxyB;
  3851.     b2Transform transformA;
  3852.     b2Transform transformB;
  3853.     b2Vec2 translationB;
  3854. };
  3855.  
  3856. /// Output results for b2ShapeCast
  3857. struct B2_API b2ShapeCastOutput {
  3858.     b2Vec2 point;
  3859.     b2Vec2 normal;
  3860.     float lambda;
  3861.     int32 iterations;
  3862. };
  3863.  
  3864. /// Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction.
  3865. /// @returns true if hit, false if there is no hit or an initial overlap
  3866. B2_API bool b2ShapeCast(b2ShapeCastOutput* output, const b2ShapeCastInput* input);
  3867.  
  3868. //////////////////////////////////////////////////////////////////////////
  3869.  
  3870. inline int32 b2DistanceProxy::GetVertexCount() const {
  3871.     return m_count;
  3872. }
  3873.  
  3874. inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const {
  3875.     b2Assert(0 <= index && index < m_count);
  3876.     return m_vertices[index];
  3877. }
  3878.  
  3879. inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const {
  3880.     int32 bestIndex = 0;
  3881.     float bestValue = b2Dot(m_vertices[0], d);
  3882.     for (int32 i = 1; i < m_count; ++i) {
  3883.         float value = b2Dot(m_vertices[i], d);
  3884.         if (value > bestValue) {
  3885.             bestIndex = i;
  3886.             bestValue = value;
  3887.         }
  3888.     }
  3889.  
  3890.     return bestIndex;
  3891. }
  3892.  
  3893. inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const {
  3894.     int32 bestIndex = 0;
  3895.     float bestValue = b2Dot(m_vertices[0], d);
  3896.     for (int32 i = 1; i < m_count; ++i) {
  3897.         float value = b2Dot(m_vertices[i], d);
  3898.         if (value > bestValue) {
  3899.             bestIndex = i;
  3900.             bestValue = value;
  3901.         }
  3902.     }
  3903.  
  3904.     return m_vertices[bestIndex];
  3905. }
  3906.  
  3907. #endif
  3908. // MIT License
  3909.  
  3910. // Copyright (c) 2019 Erin Catto
  3911.  
  3912. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3913. // of this software and associated documentation files (the "Software"), to deal
  3914. // in the Software without restriction, including without limitation the rights
  3915. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  3916. // copies of the Software, and to permit persons to whom the Software is
  3917. // furnished to do so, subject to the following conditions:
  3918.  
  3919. // The above copyright notice and this permission notice shall be included in all
  3920. // copies or substantial portions of the Software.
  3921.  
  3922. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3923. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3924. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3925. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3926. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3927. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  3928. // SOFTWARE.
  3929.  
  3930. #ifndef B2_JOINT_H
  3931. #define B2_JOINT_H
  3932.  
  3933. //#include "b2_api.h"
  3934. //#include "b2_math.h"
  3935.  
  3936. class b2Body;
  3937. class b2Draw;
  3938. class b2Joint;
  3939. struct b2SolverData;
  3940. class b2BlockAllocator;
  3941.  
  3942. enum b2JointType {
  3943.     e_unknownJoint,
  3944.     e_revoluteJoint,
  3945.     e_prismaticJoint,
  3946.     e_distanceJoint,
  3947.     e_pulleyJoint,
  3948.     e_mouseJoint,
  3949.     e_gearJoint,
  3950.     e_wheelJoint,
  3951.     e_weldJoint,
  3952.     e_frictionJoint,
  3953.     e_ropeJoint,
  3954.     e_motorJoint
  3955. };
  3956.  
  3957. struct B2_API b2Jacobian {
  3958.     b2Vec2 linear;
  3959.     float angularA;
  3960.     float angularB;
  3961. };
  3962.  
  3963. /// A joint edge is used to connect bodies and joints together
  3964. /// in a joint graph where each body is a node and each joint
  3965. /// is an edge. A joint edge belongs to a doubly linked list
  3966. /// maintained in each attached body. Each joint has two joint
  3967. /// nodes, one for each attached body.
  3968. struct B2_API b2JointEdge {
  3969.     b2Body* other;          ///< provides quick access to the other body attached.
  3970.     b2Joint* joint;         ///< the joint
  3971.     b2JointEdge* prev;      ///< the previous joint edge in the body's joint list
  3972.     b2JointEdge* next;      ///< the next joint edge in the body's joint list
  3973. };
  3974.  
  3975. /// Joint definitions are used to construct joints.
  3976. struct B2_API b2JointDef {
  3977.     b2JointDef() {
  3978.         type = e_unknownJoint;
  3979.         bodyA = nullptr;
  3980.         bodyB = nullptr;
  3981.         collideConnected = false;
  3982.     }
  3983.  
  3984.     /// The joint type is set automatically for concrete joint types.
  3985.     b2JointType type;
  3986.  
  3987.     /// Use this to attach application specific data to your joints.
  3988.     b2JointUserData userData;
  3989.  
  3990.     /// The first attached body.
  3991.     b2Body* bodyA;
  3992.  
  3993.     /// The second attached body.
  3994.     b2Body* bodyB;
  3995.  
  3996.     /// Set this flag to true if the attached bodies should collide.
  3997.     bool collideConnected;
  3998. };
  3999.  
  4000. /// Utility to compute linear stiffness values from frequency and damping ratio
  4001. B2_API void b2LinearStiffness(float& stiffness, float& damping,
  4002.     float frequencyHertz, float dampingRatio,
  4003.     const b2Body* bodyA, const b2Body* bodyB);
  4004.  
  4005. /// Utility to compute rotational stiffness values frequency and damping ratio
  4006. B2_API void b2AngularStiffness(float& stiffness, float& damping,
  4007.     float frequencyHertz, float dampingRatio,
  4008.     const b2Body* bodyA, const b2Body* bodyB);
  4009.  
  4010. /// The base joint class. Joints are used to constraint two bodies together in
  4011. /// various fashions. Some joints also feature limits and motors.
  4012. class B2_API b2Joint {
  4013. public:
  4014.  
  4015.     /// Get the type of the concrete joint.
  4016.     b2JointType GetType() const;
  4017.  
  4018.     /// Get the first body attached to this joint.
  4019.     b2Body* GetBodyA();
  4020.  
  4021.     /// Get the second body attached to this joint.
  4022.     b2Body* GetBodyB();
  4023.  
  4024.     /// Get the anchor point on bodyA in world coordinates.
  4025.     virtual b2Vec2 GetAnchorA() const = 0;
  4026.  
  4027.     /// Get the anchor point on bodyB in world coordinates.
  4028.     virtual b2Vec2 GetAnchorB() const = 0;
  4029.  
  4030.     /// Get the reaction force on bodyB at the joint anchor in Newtons.
  4031.     virtual b2Vec2 GetReactionForce(float inv_dt) const = 0;
  4032.  
  4033.     /// Get the reaction torque on bodyB in N*m.
  4034.     virtual float GetReactionTorque(float inv_dt) const = 0;
  4035.  
  4036.     /// Get the next joint the world joint list.
  4037.     b2Joint* GetNext();
  4038.     const b2Joint* GetNext() const;
  4039.  
  4040.     /// Get the user data pointer.
  4041.     b2JointUserData& GetUserData();
  4042.  
  4043.     /// Short-cut function to determine if either body is enabled.
  4044.     bool IsEnabled() const;
  4045.  
  4046.     /// Get collide connected.
  4047.     /// Note: modifying the collide connect flag won't work correctly because
  4048.     /// the flag is only checked when fixture AABBs begin to overlap.
  4049.     bool GetCollideConnected() const;
  4050.  
  4051.     /// Dump this joint to the log file.
  4052.     virtual void Dump() { b2Dump("// Dump is not supported for this joint type.\n"); }
  4053.  
  4054.     /// Shift the origin for any points stored in world coordinates.
  4055.     virtual void ShiftOrigin(const b2Vec2& newOrigin) { B2_NOT_USED(newOrigin); }
  4056.  
  4057.     /// Debug draw this joint
  4058.     virtual void Draw(b2Draw* draw) const;
  4059.  
  4060. protected:
  4061.     friend class b2World;
  4062.     friend class b2Body;
  4063.     friend class b2Island;
  4064.     friend class b2GearJoint;
  4065.  
  4066.     static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator);
  4067.     static void Destroy(b2Joint* joint, b2BlockAllocator* allocator);
  4068.  
  4069.     b2Joint(const b2JointDef* def);
  4070.     virtual ~b2Joint() {}
  4071.  
  4072.     virtual void InitVelocityConstraints(const b2SolverData& data) = 0;
  4073.     virtual void SolveVelocityConstraints(const b2SolverData& data) = 0;
  4074.  
  4075.     // This returns true if the position errors are within tolerance.
  4076.     virtual bool SolvePositionConstraints(const b2SolverData& data) = 0;
  4077.  
  4078.     b2JointType m_type;
  4079.     b2Joint* m_prev;
  4080.     b2Joint* m_next;
  4081.     b2JointEdge m_edgeA;
  4082.     b2JointEdge m_edgeB;
  4083.     b2Body* m_bodyA;
  4084.     b2Body* m_bodyB;
  4085.  
  4086.     int32 m_index;
  4087.  
  4088.     bool m_islandFlag;
  4089.     bool m_collideConnected;
  4090.  
  4091.     b2JointUserData m_userData;
  4092. };
  4093.  
  4094. inline b2JointType b2Joint::GetType() const {
  4095.     return m_type;
  4096. }
  4097.  
  4098. inline b2Body* b2Joint::GetBodyA() {
  4099.     return m_bodyA;
  4100. }
  4101.  
  4102. inline b2Body* b2Joint::GetBodyB() {
  4103.     return m_bodyB;
  4104. }
  4105.  
  4106. inline b2Joint* b2Joint::GetNext() {
  4107.     return m_next;
  4108. }
  4109.  
  4110. inline const b2Joint* b2Joint::GetNext() const {
  4111.     return m_next;
  4112. }
  4113.  
  4114. inline b2JointUserData& b2Joint::GetUserData() {
  4115.     return m_userData;
  4116. }
  4117.  
  4118. inline bool b2Joint::GetCollideConnected() const {
  4119.     return m_collideConnected;
  4120. }
  4121.  
  4122. #endif
  4123. // MIT License
  4124.  
  4125. // Copyright (c) 2019 Erin Catto
  4126.  
  4127. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4128. // of this software and associated documentation files (the "Software"), to deal
  4129. // in the Software without restriction, including without limitation the rights
  4130. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4131. // copies of the Software, and to permit persons to whom the Software is
  4132. // furnished to do so, subject to the following conditions:
  4133.  
  4134. // The above copyright notice and this permission notice shall be included in all
  4135. // copies or substantial portions of the Software.
  4136.  
  4137. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4138. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4139. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4140. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4141. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4142. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4143. // SOFTWARE.
  4144.  
  4145. #ifndef B2_DISTANCE_JOINT_H
  4146. #define B2_DISTANCE_JOINT_H
  4147.  
  4148. //#include "b2_api.h"
  4149. //#include "b2_joint.h"
  4150.  
  4151. /// Distance joint definition. This requires defining an anchor point on both
  4152. /// bodies and the non-zero distance of the distance joint. The definition uses
  4153. /// local anchor points so that the initial configuration can violate the
  4154. /// constraint slightly. This helps when saving and loading a game.
  4155. struct B2_API b2DistanceJointDef : public b2JointDef {
  4156.     b2DistanceJointDef() {
  4157.         type = e_distanceJoint;
  4158.         localAnchorA.Set(0.0f, 0.0f);
  4159.         localAnchorB.Set(0.0f, 0.0f);
  4160.         length = 1.0f;
  4161.         minLength = 0.0f;
  4162.         maxLength = FLT_MAX;
  4163.         stiffness = 0.0f;
  4164.         damping = 0.0f;
  4165.     }
  4166.  
  4167.     /// Initialize the bodies, anchors, and rest length using world space anchors.
  4168.     /// The minimum and maximum lengths are set to the rest length.
  4169.     void Initialize(b2Body* bodyA, b2Body* bodyB,
  4170.         const b2Vec2& anchorA, const b2Vec2& anchorB);
  4171.  
  4172.     /// The local anchor point relative to bodyA's origin.
  4173.     b2Vec2 localAnchorA;
  4174.  
  4175.     /// The local anchor point relative to bodyB's origin.
  4176.     b2Vec2 localAnchorB;
  4177.  
  4178.     /// The rest length of this joint. Clamped to a stable minimum value.
  4179.     float length;
  4180.  
  4181.     /// Minimum length. Clamped to a stable minimum value.
  4182.     float minLength;
  4183.  
  4184.     /// Maximum length. Must be greater than or equal to the minimum length.
  4185.     float maxLength;
  4186.  
  4187.     /// The linear stiffness in N/m.
  4188.     float stiffness;
  4189.  
  4190.     /// The linear damping in N*s/m.
  4191.     float damping;
  4192. };
  4193.  
  4194. /// A distance joint constrains two points on two bodies to remain at a fixed
  4195. /// distance from each other. You can view this as a massless, rigid rod.
  4196. class B2_API b2DistanceJoint : public b2Joint {
  4197. public:
  4198.  
  4199.     b2Vec2 GetAnchorA() const override;
  4200.     b2Vec2 GetAnchorB() const override;
  4201.  
  4202.     /// Get the reaction force given the inverse time step.
  4203.     /// Unit is N.
  4204.     b2Vec2 GetReactionForce(float inv_dt) const override;
  4205.  
  4206.     /// Get the reaction torque given the inverse time step.
  4207.     /// Unit is N*m. This is always zero for a distance joint.
  4208.     float GetReactionTorque(float inv_dt) const override;
  4209.  
  4210.     /// The local anchor point relative to bodyA's origin.
  4211.     const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
  4212.  
  4213.     /// The local anchor point relative to bodyB's origin.
  4214.     const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
  4215.  
  4216.     /// Get the rest length
  4217.     float GetLength() const { return m_length; }
  4218.  
  4219.     /// Set the rest length
  4220.     /// @returns clamped rest length
  4221.     float SetLength(float length);
  4222.  
  4223.     /// Get the minimum length
  4224.     float GetMinLength() const { return m_minLength; }
  4225.  
  4226.     /// Set the minimum length
  4227.     /// @returns the clamped minimum length
  4228.     float SetMinLength(float minLength);
  4229.  
  4230.     /// Get the maximum length
  4231.     float GetMaxLength() const { return m_maxLength; }
  4232.  
  4233.     /// Set the maximum length
  4234.     /// @returns the clamped maximum length
  4235.     float SetMaxLength(float maxLength);
  4236.  
  4237.     /// Get the current length
  4238.     float GetCurrentLength() const;
  4239.  
  4240.     /// Set/get the linear stiffness in N/m
  4241.     void SetStiffness(float stiffness) { m_stiffness = stiffness; }
  4242.     float GetStiffness() const { return m_stiffness; }
  4243.  
  4244.     /// Set/get linear damping in N*s/m
  4245.     void SetDamping(float damping) { m_damping = damping; }
  4246.     float GetDamping() const { return m_damping; }
  4247.  
  4248.     /// Dump joint to dmLog
  4249.     void Dump() override;
  4250.  
  4251.     ///
  4252.     void Draw(b2Draw* draw) const override;
  4253.  
  4254. protected:
  4255.  
  4256.     friend class b2Joint;
  4257.     b2DistanceJoint(const b2DistanceJointDef* data);
  4258.  
  4259.     void InitVelocityConstraints(const b2SolverData& data) override;
  4260.     void SolveVelocityConstraints(const b2SolverData& data) override;
  4261.     bool SolvePositionConstraints(const b2SolverData& data) override;
  4262.  
  4263.     float m_stiffness;
  4264.     float m_damping;
  4265.     float m_bias;
  4266.     float m_length;
  4267.     float m_minLength;
  4268.     float m_maxLength;
  4269.  
  4270.     // Solver shared
  4271.     b2Vec2 m_localAnchorA;
  4272.     b2Vec2 m_localAnchorB;
  4273.     float m_gamma;
  4274.     float m_impulse;
  4275.     float m_lowerImpulse;
  4276.     float m_upperImpulse;
  4277.  
  4278.     // Solver temp
  4279.     int32 m_indexA;
  4280.     int32 m_indexB;
  4281.     b2Vec2 m_u;
  4282.     b2Vec2 m_rA;
  4283.     b2Vec2 m_rB;
  4284.     b2Vec2 m_localCenterA;
  4285.     b2Vec2 m_localCenterB;
  4286.     float m_currentLength;
  4287.     float m_invMassA;
  4288.     float m_invMassB;
  4289.     float m_invIA;
  4290.     float m_invIB;
  4291.     float m_softMass;
  4292.     float m_mass;
  4293. };
  4294.  
  4295. #endif
  4296. // MIT License
  4297.  
  4298. // Copyright (c) 2019 Erin Catto
  4299.  
  4300. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4301. // of this software and associated documentation files (the "Software"), to deal
  4302. // in the Software without restriction, including without limitation the rights
  4303. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4304. // copies of the Software, and to permit persons to whom the Software is
  4305. // furnished to do so, subject to the following conditions:
  4306.  
  4307. // The above copyright notice and this permission notice shall be included in all
  4308. // copies or substantial portions of the Software.
  4309.  
  4310. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4311. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4312. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4313. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4314. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4315. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4316. // SOFTWARE.
  4317.  
  4318. #ifndef B2_DRAW_H
  4319. #define B2_DRAW_H
  4320.  
  4321. //#include "b2_api.h"
  4322. //#include "b2_math.h"
  4323.  
  4324. /// Color for debug drawing. Each value has the range [0,1].
  4325. struct B2_API b2Color {
  4326.     b2Color() {}
  4327.     b2Color(float rIn, float gIn, float bIn, float aIn = 1.0f) {
  4328.         r = rIn; g = gIn; b = bIn; a = aIn;
  4329.     }
  4330.  
  4331.     void Set(float rIn, float gIn, float bIn, float aIn = 1.0f) {
  4332.         r = rIn; g = gIn; b = bIn; a = aIn;
  4333.     }
  4334.  
  4335.     float r, g, b, a;
  4336. };
  4337.  
  4338. /// Implement and register this class with a b2World to provide debug drawing of physics
  4339. /// entities in your game.
  4340. class B2_API b2Draw {
  4341. public:
  4342.     b2Draw();
  4343.  
  4344.     virtual ~b2Draw() {}
  4345.  
  4346.     enum {
  4347.         e_shapeBit = 0x0001,    ///< draw shapes
  4348.         e_jointBit = 0x0002,    ///< draw joint connections
  4349.         e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes
  4350.         e_pairBit = 0x0008, ///< draw broad-phase pairs
  4351.         e_centerOfMassBit = 0x0010  ///< draw center of mass frame
  4352.     };
  4353.  
  4354.     /// Set the drawing flags.
  4355.     void SetFlags(uint32 flags);
  4356.  
  4357.     /// Get the drawing flags.
  4358.     uint32 GetFlags() const;
  4359.  
  4360.     /// Append flags to the current flags.
  4361.     void AppendFlags(uint32 flags);
  4362.  
  4363.     /// Clear flags from the current flags.
  4364.     void ClearFlags(uint32 flags);
  4365.  
  4366.     /// Draw a closed polygon provided in CCW order.
  4367.     virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
  4368.  
  4369.     /// Draw a solid closed polygon provided in CCW order.
  4370.     virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
  4371.  
  4372.     /// Draw a circle.
  4373.     virtual void DrawCircle(const b2Vec2& center, float radius, const b2Color& color) = 0;
  4374.  
  4375.     /// Draw a solid circle.
  4376.     virtual void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) = 0;
  4377.  
  4378.     /// Draw a line segment.
  4379.     virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0;
  4380.  
  4381.     /// Draw a transform. Choose your own length scale.
  4382.     /// @param xf a transform.
  4383.     virtual void DrawTransform(const b2Transform& xf) = 0;
  4384.  
  4385.     /// Draw a point.
  4386.     virtual void DrawPoint(const b2Vec2& p, float size, const b2Color& color) = 0;
  4387.  
  4388. protected:
  4389.     uint32 m_drawFlags;
  4390. };
  4391.  
  4392. #endif
  4393. // MIT License
  4394.  
  4395. // Copyright (c) 2019 Erin Catto
  4396.  
  4397. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4398. // of this software and associated documentation files (the "Software"), to deal
  4399. // in the Software without restriction, including without limitation the rights
  4400. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4401. // copies of the Software, and to permit persons to whom the Software is
  4402. // furnished to do so, subject to the following conditions:
  4403.  
  4404. // The above copyright notice and this permission notice shall be included in all
  4405. // copies or substantial portions of the Software.
  4406.  
  4407. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4408. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4409. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4410. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4411. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4412. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4413. // SOFTWARE.
  4414.  
  4415. #ifndef B2_EDGE_SHAPE_H
  4416. #define B2_EDGE_SHAPE_H
  4417.  
  4418. //#include "b2_api.h"
  4419. //#include "b2_shape.h"
  4420.  
  4421. /// A line segment (edge) shape. These can be connected in chains or loops
  4422. /// to other edge shapes. Edges created independently are two-sided and do
  4423. /// no provide smooth movement across junctions.
  4424. class B2_API b2EdgeShape : public b2Shape {
  4425. public:
  4426.     b2EdgeShape();
  4427.  
  4428.     /// Set this as a part of a sequence. Vertex v0 precedes the edge and vertex v3
  4429.     /// follows. These extra vertices are used to provide smooth movement
  4430.     /// across junctions. This also makes the collision one-sided. The edge
  4431.     /// normal points to the right looking from v1 to v2.
  4432.     void SetOneSided(const b2Vec2& v0, const b2Vec2& v1, const b2Vec2& v2, const b2Vec2& v3);
  4433.  
  4434.     /// Set this as an isolated edge. Collision is two-sided.
  4435.     void SetTwoSided(const b2Vec2& v1, const b2Vec2& v2);
  4436.  
  4437.     /// Implement b2Shape.
  4438.     b2Shape* Clone(b2BlockAllocator* allocator) const override;
  4439.  
  4440.     /// @see b2Shape::GetChildCount
  4441.     int32 GetChildCount() const override;
  4442.  
  4443.     /// @see b2Shape::TestPoint
  4444.     bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override;
  4445.  
  4446.     /// Implement b2Shape.
  4447.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  4448.         const b2Transform& transform, int32 childIndex) const override;
  4449.  
  4450.     /// @see b2Shape::ComputeAABB
  4451.     void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override;
  4452.  
  4453.     /// @see b2Shape::ComputeMass
  4454.     void ComputeMass(b2MassData* massData, float density) const override;
  4455.  
  4456.     /// These are the edge vertices
  4457.     b2Vec2 m_vertex1, m_vertex2;
  4458.  
  4459.     /// Optional adjacent vertices. These are used for smooth collision.
  4460.     b2Vec2 m_vertex0, m_vertex3;
  4461.  
  4462.     /// Uses m_vertex0 and m_vertex3 to create smooth collision.
  4463.     bool m_oneSided;
  4464. };
  4465.  
  4466. inline b2EdgeShape::b2EdgeShape() {
  4467.     m_type = e_edge;
  4468.     m_radius = b2_polygonRadius;
  4469.     m_vertex0.x = 0.0f;
  4470.     m_vertex0.y = 0.0f;
  4471.     m_vertex3.x = 0.0f;
  4472.     m_vertex3.y = 0.0f;
  4473.     m_oneSided = false;
  4474. }
  4475.  
  4476. #endif
  4477. // MIT License
  4478.  
  4479. // Copyright (c) 2019 Erin Catto
  4480.  
  4481. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4482. // of this software and associated documentation files (the "Software"), to deal
  4483. // in the Software without restriction, including without limitation the rights
  4484. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4485. // copies of the Software, and to permit persons to whom the Software is
  4486. // furnished to do so, subject to the following conditions:
  4487.  
  4488. // The above copyright notice and this permission notice shall be included in all
  4489. // copies or substantial portions of the Software.
  4490.  
  4491. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4492. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4493. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4494. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4495. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4496. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4497. // SOFTWARE.
  4498.  
  4499. #ifndef B2_FRICTION_JOINT_H
  4500. #define B2_FRICTION_JOINT_H
  4501.  
  4502. //#include "b2_api.h"
  4503. //#include "b2_joint.h"
  4504.  
  4505. /// Friction joint definition.
  4506. struct B2_API b2FrictionJointDef : public b2JointDef {
  4507.     b2FrictionJointDef() {
  4508.         type = e_frictionJoint;
  4509.         localAnchorA.SetZero();
  4510.         localAnchorB.SetZero();
  4511.         maxForce = 0.0f;
  4512.         maxTorque = 0.0f;
  4513.     }
  4514.  
  4515.     /// Initialize the bodies, anchors, axis, and reference angle using the world
  4516.     /// anchor and world axis.
  4517.     void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
  4518.  
  4519.     /// The local anchor point relative to bodyA's origin.
  4520.     b2Vec2 localAnchorA;
  4521.  
  4522.     /// The local anchor point relative to bodyB's origin.
  4523.     b2Vec2 localAnchorB;
  4524.  
  4525.     /// The maximum friction force in N.
  4526.     float maxForce;
  4527.  
  4528.     /// The maximum friction torque in N-m.
  4529.     float maxTorque;
  4530. };
  4531.  
  4532. /// Friction joint. This is used for top-down friction.
  4533. /// It provides 2D translational friction and angular friction.
  4534. class B2_API b2FrictionJoint : public b2Joint {
  4535. public:
  4536.     b2Vec2 GetAnchorA() const override;
  4537.     b2Vec2 GetAnchorB() const override;
  4538.  
  4539.     b2Vec2 GetReactionForce(float inv_dt) const override;
  4540.     float GetReactionTorque(float inv_dt) const override;
  4541.  
  4542.     /// The local anchor point relative to bodyA's origin.
  4543.     const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
  4544.  
  4545.     /// The local anchor point relative to bodyB's origin.
  4546.     const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
  4547.  
  4548.     /// Set the maximum friction force in N.
  4549.     void SetMaxForce(float force);
  4550.  
  4551.     /// Get the maximum friction force in N.
  4552.     float GetMaxForce() const;
  4553.  
  4554.     /// Set the maximum friction torque in N*m.
  4555.     void SetMaxTorque(float torque);
  4556.  
  4557.     /// Get the maximum friction torque in N*m.
  4558.     float GetMaxTorque() const;
  4559.  
  4560.     /// Dump joint to dmLog
  4561.     void Dump() override;
  4562.  
  4563. protected:
  4564.  
  4565.     friend class b2Joint;
  4566.  
  4567.     b2FrictionJoint(const b2FrictionJointDef* def);
  4568.  
  4569.     void InitVelocityConstraints(const b2SolverData& data) override;
  4570.     void SolveVelocityConstraints(const b2SolverData& data) override;
  4571.     bool SolvePositionConstraints(const b2SolverData& data) override;
  4572.  
  4573.     b2Vec2 m_localAnchorA;
  4574.     b2Vec2 m_localAnchorB;
  4575.  
  4576.     // Solver shared
  4577.     b2Vec2 m_linearImpulse;
  4578.     float m_angularImpulse;
  4579.     float m_maxForce;
  4580.     float m_maxTorque;
  4581.  
  4582.     // Solver temp
  4583.     int32 m_indexA;
  4584.     int32 m_indexB;
  4585.     b2Vec2 m_rA;
  4586.     b2Vec2 m_rB;
  4587.     b2Vec2 m_localCenterA;
  4588.     b2Vec2 m_localCenterB;
  4589.     float m_invMassA;
  4590.     float m_invMassB;
  4591.     float m_invIA;
  4592.     float m_invIB;
  4593.     b2Mat22 m_linearMass;
  4594.     float m_angularMass;
  4595. };
  4596.  
  4597. #endif
  4598. // MIT License
  4599.  
  4600. // Copyright (c) 2019 Erin Catto
  4601.  
  4602. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4603. // of this software and associated documentation files (the "Software"), to deal
  4604. // in the Software without restriction, including without limitation the rights
  4605. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4606. // copies of the Software, and to permit persons to whom the Software is
  4607. // furnished to do so, subject to the following conditions:
  4608.  
  4609. // The above copyright notice and this permission notice shall be included in all
  4610. // copies or substantial portions of the Software.
  4611.  
  4612. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4613. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4614. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4615. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4616. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4617. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4618. // SOFTWARE.
  4619.  
  4620. #ifndef B2_GEAR_JOINT_H
  4621. #define B2_GEAR_JOINT_H
  4622.  
  4623. //#include "b2_joint.h"
  4624.  
  4625. /// Gear joint definition. This definition requires two existing
  4626. /// revolute or prismatic joints (any combination will work).
  4627. /// @warning bodyB on the input joints must both be dynamic
  4628. struct B2_API b2GearJointDef : public b2JointDef {
  4629.     b2GearJointDef() {
  4630.         type = e_gearJoint;
  4631.         joint1 = nullptr;
  4632.         joint2 = nullptr;
  4633.         ratio = 1.0f;
  4634.     }
  4635.  
  4636.     /// The first revolute/prismatic joint attached to the gear joint.
  4637.     b2Joint* joint1;
  4638.  
  4639.     /// The second revolute/prismatic joint attached to the gear joint.
  4640.     b2Joint* joint2;
  4641.  
  4642.     /// The gear ratio.
  4643.     /// @see b2GearJoint for explanation.
  4644.     float ratio;
  4645. };
  4646.  
  4647. /// A gear joint is used to connect two joints together. Either joint
  4648. /// can be a revolute or prismatic joint. You specify a gear ratio
  4649. /// to bind the motions together:
  4650. /// coordinate1 + ratio * coordinate2 = constant
  4651. /// The ratio can be negative or positive. If one joint is a revolute joint
  4652. /// and the other joint is a prismatic joint, then the ratio will have units
  4653. /// of length or units of 1/length.
  4654. /// @warning You have to manually destroy the gear joint if joint1 or joint2
  4655. /// is destroyed.
  4656. class B2_API b2GearJoint : public b2Joint {
  4657. public:
  4658.     b2Vec2 GetAnchorA() const override;
  4659.     b2Vec2 GetAnchorB() const override;
  4660.  
  4661.     b2Vec2 GetReactionForce(float inv_dt) const override;
  4662.     float GetReactionTorque(float inv_dt) const override;
  4663.  
  4664.     /// Get the first joint.
  4665.     b2Joint* GetJoint1() { return m_joint1; }
  4666.  
  4667.     /// Get the second joint.
  4668.     b2Joint* GetJoint2() { return m_joint2; }
  4669.  
  4670.     /// Set/Get the gear ratio.
  4671.     void SetRatio(float ratio);
  4672.     float GetRatio() const;
  4673.  
  4674.     /// Dump joint to dmLog
  4675.     void Dump() override;
  4676.  
  4677. protected:
  4678.  
  4679.     friend class b2Joint;
  4680.     b2GearJoint(const b2GearJointDef* data);
  4681.  
  4682.     void InitVelocityConstraints(const b2SolverData& data) override;
  4683.     void SolveVelocityConstraints(const b2SolverData& data) override;
  4684.     bool SolvePositionConstraints(const b2SolverData& data) override;
  4685.  
  4686.     b2Joint* m_joint1;
  4687.     b2Joint* m_joint2;
  4688.  
  4689.     b2JointType m_typeA;
  4690.     b2JointType m_typeB;
  4691.  
  4692.     // Body A is connected to body C
  4693.     // Body B is connected to body D
  4694.     b2Body* m_bodyC;
  4695.     b2Body* m_bodyD;
  4696.  
  4697.     // Solver shared
  4698.     b2Vec2 m_localAnchorA;
  4699.     b2Vec2 m_localAnchorB;
  4700.     b2Vec2 m_localAnchorC;
  4701.     b2Vec2 m_localAnchorD;
  4702.  
  4703.     b2Vec2 m_localAxisC;
  4704.     b2Vec2 m_localAxisD;
  4705.  
  4706.     float m_referenceAngleA;
  4707.     float m_referenceAngleB;
  4708.  
  4709.     float m_constant;
  4710.     float m_ratio;
  4711.  
  4712.     float m_impulse;
  4713.  
  4714.     // Solver temp
  4715.     int32 m_indexA, m_indexB, m_indexC, m_indexD;
  4716.     b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD;
  4717.     float m_mA, m_mB, m_mC, m_mD;
  4718.     float m_iA, m_iB, m_iC, m_iD;
  4719.     b2Vec2 m_JvAC, m_JvBD;
  4720.     float m_JwA, m_JwB, m_JwC, m_JwD;
  4721.     float m_mass;
  4722. };
  4723.  
  4724. #endif
  4725. // MIT License
  4726.  
  4727. // Copyright (c) 2019 Erin Catto
  4728.  
  4729. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4730. // of this software and associated documentation files (the "Software"), to deal
  4731. // in the Software without restriction, including without limitation the rights
  4732. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4733. // copies of the Software, and to permit persons to whom the Software is
  4734. // furnished to do so, subject to the following conditions:
  4735.  
  4736. // The above copyright notice and this permission notice shall be included in all
  4737. // copies or substantial portions of the Software.
  4738.  
  4739. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4740. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4741. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4742. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4743. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4744. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4745. // SOFTWARE.
  4746.  
  4747. #ifndef B2_MOTOR_JOINT_H
  4748. #define B2_MOTOR_JOINT_H
  4749.  
  4750. //#include "b2_api.h"
  4751. //#include "b2_joint.h"
  4752.  
  4753. /// Motor joint definition.
  4754. struct B2_API b2MotorJointDef : public b2JointDef {
  4755.     b2MotorJointDef() {
  4756.         type = e_motorJoint;
  4757.         linearOffset.SetZero();
  4758.         angularOffset = 0.0f;
  4759.         maxForce = 1.0f;
  4760.         maxTorque = 1.0f;
  4761.         correctionFactor = 0.3f;
  4762.     }
  4763.  
  4764.     /// Initialize the bodies and offsets using the current transforms.
  4765.     void Initialize(b2Body* bodyA, b2Body* bodyB);
  4766.  
  4767.     /// Position of bodyB minus the position of bodyA, in bodyA's frame, in meters.
  4768.     b2Vec2 linearOffset;
  4769.  
  4770.     /// The bodyB angle minus bodyA angle in radians.
  4771.     float angularOffset;
  4772.  
  4773.     /// The maximum motor force in N.
  4774.     float maxForce;
  4775.  
  4776.     /// The maximum motor torque in N-m.
  4777.     float maxTorque;
  4778.  
  4779.     /// Position correction factor in the range [0,1].
  4780.     float correctionFactor;
  4781. };
  4782.  
  4783. /// A motor joint is used to control the relative motion
  4784. /// between two bodies. A typical usage is to control the movement
  4785. /// of a dynamic body with respect to the ground.
  4786. class B2_API b2MotorJoint : public b2Joint {
  4787. public:
  4788.     b2Vec2 GetAnchorA() const override;
  4789.     b2Vec2 GetAnchorB() const override;
  4790.  
  4791.     b2Vec2 GetReactionForce(float inv_dt) const override;
  4792.     float GetReactionTorque(float inv_dt) const override;
  4793.  
  4794.     /// Set/get the target linear offset, in frame A, in meters.
  4795.     void SetLinearOffset(const b2Vec2& linearOffset);
  4796.     const b2Vec2& GetLinearOffset() const;
  4797.  
  4798.     /// Set/get the target angular offset, in radians.
  4799.     void SetAngularOffset(float angularOffset);
  4800.     float GetAngularOffset() const;
  4801.  
  4802.     /// Set the maximum friction force in N.
  4803.     void SetMaxForce(float force);
  4804.  
  4805.     /// Get the maximum friction force in N.
  4806.     float GetMaxForce() const;
  4807.  
  4808.     /// Set the maximum friction torque in N*m.
  4809.     void SetMaxTorque(float torque);
  4810.  
  4811.     /// Get the maximum friction torque in N*m.
  4812.     float GetMaxTorque() const;
  4813.  
  4814.     /// Set the position correction factor in the range [0,1].
  4815.     void SetCorrectionFactor(float factor);
  4816.  
  4817.     /// Get the position correction factor in the range [0,1].
  4818.     float GetCorrectionFactor() const;
  4819.  
  4820.     /// Dump to b2Log
  4821.     void Dump() override;
  4822.  
  4823. protected:
  4824.  
  4825.     friend class b2Joint;
  4826.  
  4827.     b2MotorJoint(const b2MotorJointDef* def);
  4828.  
  4829.     void InitVelocityConstraints(const b2SolverData& data) override;
  4830.     void SolveVelocityConstraints(const b2SolverData& data) override;
  4831.     bool SolvePositionConstraints(const b2SolverData& data) override;
  4832.  
  4833.     // Solver shared
  4834.     b2Vec2 m_linearOffset;
  4835.     float m_angularOffset;
  4836.     b2Vec2 m_linearImpulse;
  4837.     float m_angularImpulse;
  4838.     float m_maxForce;
  4839.     float m_maxTorque;
  4840.     float m_correctionFactor;
  4841.  
  4842.     // Solver temp
  4843.     int32 m_indexA;
  4844.     int32 m_indexB;
  4845.     b2Vec2 m_rA;
  4846.     b2Vec2 m_rB;
  4847.     b2Vec2 m_localCenterA;
  4848.     b2Vec2 m_localCenterB;
  4849.     b2Vec2 m_linearError;
  4850.     float m_angularError;
  4851.     float m_invMassA;
  4852.     float m_invMassB;
  4853.     float m_invIA;
  4854.     float m_invIB;
  4855.     b2Mat22 m_linearMass;
  4856.     float m_angularMass;
  4857. };
  4858.  
  4859. #endif
  4860. // MIT License
  4861.  
  4862. // Copyright (c) 2019 Erin Catto
  4863.  
  4864. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4865. // of this software and associated documentation files (the "Software"), to deal
  4866. // in the Software without restriction, including without limitation the rights
  4867. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4868. // copies of the Software, and to permit persons to whom the Software is
  4869. // furnished to do so, subject to the following conditions:
  4870.  
  4871. // The above copyright notice and this permission notice shall be included in all
  4872. // copies or substantial portions of the Software.
  4873.  
  4874. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4875. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4876. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4877. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4878. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4879. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4880. // SOFTWARE.
  4881.  
  4882. #ifndef B2_MOUSE_JOINT_H
  4883. #define B2_MOUSE_JOINT_H
  4884.  
  4885. //#include "b2_api.h"
  4886. //#include "b2_joint.h"
  4887.  
  4888. /// Mouse joint definition. This requires a world target point,
  4889. /// tuning parameters, and the time step.
  4890. struct B2_API b2MouseJointDef : public b2JointDef {
  4891.     b2MouseJointDef() {
  4892.         type = e_mouseJoint;
  4893.         target.Set(0.0f, 0.0f);
  4894.         maxForce = 0.0f;
  4895.         stiffness = 0.0f;
  4896.         damping = 0.0f;
  4897.     }
  4898.  
  4899.     /// The initial world target point. This is assumed
  4900.     /// to coincide with the body anchor initially.
  4901.     b2Vec2 target;
  4902.  
  4903.     /// The maximum constraint force that can be exerted
  4904.     /// to move the candidate body. Usually you will express
  4905.     /// as some multiple of the weight (multiplier * mass * gravity).
  4906.     float maxForce;
  4907.  
  4908.     /// The linear stiffness in N/m
  4909.     float stiffness;
  4910.  
  4911.     /// The linear damping in N*s/m
  4912.     float damping;
  4913. };
  4914.  
  4915. /// A mouse joint is used to make a point on a body track a
  4916. /// specified world point. This a soft constraint with a maximum
  4917. /// force. This allows the constraint to stretch and without
  4918. /// applying huge forces.
  4919. /// NOTE: this joint is not documented in the manual because it was
  4920. /// developed to be used in the testbed. If you want to learn how to
  4921. /// use the mouse joint, look at the testbed.
  4922. class B2_API b2MouseJoint : public b2Joint {
  4923. public:
  4924.  
  4925.     /// Implements b2Joint.
  4926.     b2Vec2 GetAnchorA() const override;
  4927.  
  4928.     /// Implements b2Joint.
  4929.     b2Vec2 GetAnchorB() const override;
  4930.  
  4931.     /// Implements b2Joint.
  4932.     b2Vec2 GetReactionForce(float inv_dt) const override;
  4933.  
  4934.     /// Implements b2Joint.
  4935.     float GetReactionTorque(float inv_dt) const override;
  4936.  
  4937.     /// Use this to update the target point.
  4938.     void SetTarget(const b2Vec2& target);
  4939.     const b2Vec2& GetTarget() const;
  4940.  
  4941.     /// Set/get the maximum force in Newtons.
  4942.     void SetMaxForce(float force);
  4943.     float GetMaxForce() const;
  4944.  
  4945.     /// Set/get the linear stiffness in N/m
  4946.     void SetStiffness(float stiffness) { m_stiffness = stiffness; }
  4947.     float GetStiffness() const { return m_stiffness; }
  4948.  
  4949.     /// Set/get linear damping in N*s/m
  4950.     void SetDamping(float damping) { m_damping = damping; }
  4951.     float GetDamping() const { return m_damping; }
  4952.  
  4953.     /// The mouse joint does not support dumping.
  4954.     void Dump() override { b2Log("Mouse joint dumping is not supported.\n"); }
  4955.  
  4956.     /// Implement b2Joint::ShiftOrigin
  4957.     void ShiftOrigin(const b2Vec2& newOrigin) override;
  4958.  
  4959. protected:
  4960.     friend class b2Joint;
  4961.  
  4962.     b2MouseJoint(const b2MouseJointDef* def);
  4963.  
  4964.     void InitVelocityConstraints(const b2SolverData& data) override;
  4965.     void SolveVelocityConstraints(const b2SolverData& data) override;
  4966.     bool SolvePositionConstraints(const b2SolverData& data) override;
  4967.  
  4968.     b2Vec2 m_localAnchorB;
  4969.     b2Vec2 m_targetA;
  4970.     float m_stiffness;
  4971.     float m_damping;
  4972.     float m_beta;
  4973.  
  4974.     // Solver shared
  4975.     b2Vec2 m_impulse;
  4976.     float m_maxForce;
  4977.     float m_gamma;
  4978.  
  4979.     // Solver temp
  4980.     int32 m_indexA;
  4981.     int32 m_indexB;
  4982.     b2Vec2 m_rB;
  4983.     b2Vec2 m_localCenterB;
  4984.     float m_invMassB;
  4985.     float m_invIB;
  4986.     b2Mat22 m_mass;
  4987.     b2Vec2 m_C;
  4988. };
  4989.  
  4990. #endif
  4991. // MIT License
  4992.  
  4993. // Copyright (c) 2019 Erin Catto
  4994.  
  4995. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4996. // of this software and associated documentation files (the "Software"), to deal
  4997. // in the Software without restriction, including without limitation the rights
  4998. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4999. // copies of the Software, and to permit persons to whom the Software is
  5000. // furnished to do so, subject to the following conditions:
  5001.  
  5002. // The above copyright notice and this permission notice shall be included in all
  5003. // copies or substantial portions of the Software.
  5004.  
  5005. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5006. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5007. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5008. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5009. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5010. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5011. // SOFTWARE.
  5012. #ifndef B2_POLYGON_SHAPE_H
  5013. #define B2_POLYGON_SHAPE_H
  5014.  
  5015. //#include "b2_api.h"
  5016. //#include "b2_shape.h"
  5017.  
  5018. /// A solid convex polygon. It is assumed that the interior of the polygon is to
  5019. /// the left of each edge.
  5020. /// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices.
  5021. /// In most cases you should not need many vertices for a convex polygon.
  5022. class B2_API b2PolygonShape : public b2Shape {
  5023. public:
  5024.     b2PolygonShape();
  5025.  
  5026.     /// Implement b2Shape.
  5027.     b2Shape* Clone(b2BlockAllocator* allocator) const override;
  5028.  
  5029.     /// @see b2Shape::GetChildCount
  5030.     int32 GetChildCount() const override;
  5031.  
  5032.     /// Create a convex hull from the given array of local points.
  5033.     /// The count must be in the range [3, b2_maxPolygonVertices].
  5034.     /// @warning the points may be re-ordered, even if they form a convex polygon
  5035.     /// @warning collinear points are handled but not removed. Collinear points
  5036.     /// may lead to poor stacking behavior.
  5037.     void Set(const b2Vec2* points, int32 count);
  5038.  
  5039.     /// Build vertices to represent an axis-aligned box centered on the local origin.
  5040.     /// @param hx the half-width.
  5041.     /// @param hy the half-height.
  5042.     void SetAsBox(float hx, float hy);
  5043.  
  5044.     /// Build vertices to represent an oriented box.
  5045.     /// @param hx the half-width.
  5046.     /// @param hy the half-height.
  5047.     /// @param center the center of the box in local coordinates.
  5048.     /// @param angle the rotation of the box in local coordinates.
  5049.     void SetAsBox(float hx, float hy, const b2Vec2& center, float angle);
  5050.  
  5051.     /// @see b2Shape::TestPoint
  5052.     bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override;
  5053.  
  5054.     /// Implement b2Shape.
  5055.     /// @note because the polygon is solid, rays that start inside do not hit because the normal is
  5056.     /// not defined.
  5057.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  5058.         const b2Transform& transform, int32 childIndex) const override;
  5059.  
  5060.     /// @see b2Shape::ComputeAABB
  5061.     void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override;
  5062.  
  5063.     /// @see b2Shape::ComputeMass
  5064.     void ComputeMass(b2MassData* massData, float density) const override;
  5065.  
  5066.     /// Validate convexity. This is a very time consuming operation.
  5067.     /// @returns true if valid
  5068.     bool Validate() const;
  5069.  
  5070.     b2Vec2 m_centroid;
  5071.     b2Vec2 m_vertices[b2_maxPolygonVertices];
  5072.     b2Vec2 m_normals[b2_maxPolygonVertices];
  5073.     int32 m_count;
  5074. };
  5075.  
  5076. inline b2PolygonShape::b2PolygonShape() {
  5077.     m_type = e_polygon;
  5078.     m_radius = b2_polygonRadius;
  5079.     m_count = 0;
  5080.     m_centroid.SetZero();
  5081. }
  5082.  
  5083. #endif
  5084. // MIT License
  5085.  
  5086. // Copyright (c) 2019 Erin Catto
  5087.  
  5088. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5089. // of this software and associated documentation files (the "Software"), to deal
  5090. // in the Software without restriction, including without limitation the rights
  5091. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5092. // copies of the Software, and to permit persons to whom the Software is
  5093. // furnished to do so, subject to the following conditions:
  5094.  
  5095. // The above copyright notice and this permission notice shall be included in all
  5096. // copies or substantial portions of the Software.
  5097.  
  5098. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5099. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5100. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5101. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5102. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5103. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5104. // SOFTWARE.
  5105.  
  5106. #ifndef B2_PRISMATIC_JOINT_H
  5107. #define B2_PRISMATIC_JOINT_H
  5108.  
  5109. //#include "b2_api.h"
  5110. //#include "b2_joint.h"
  5111.  
  5112. /// Prismatic joint definition. This requires defining a line of
  5113. /// motion using an axis and an anchor point. The definition uses local
  5114. /// anchor points and a local axis so that the initial configuration
  5115. /// can violate the constraint slightly. The joint translation is zero
  5116. /// when the local anchor points coincide in world space. Using local
  5117. /// anchors and a local axis helps when saving and loading a game.
  5118. struct B2_API b2PrismaticJointDef : public b2JointDef {
  5119.     b2PrismaticJointDef() {
  5120.         type = e_prismaticJoint;
  5121.         localAnchorA.SetZero();
  5122.         localAnchorB.SetZero();
  5123.         localAxisA.Set(1.0f, 0.0f);
  5124.         referenceAngle = 0.0f;
  5125.         enableLimit = false;
  5126.         lowerTranslation = 0.0f;
  5127.         upperTranslation = 0.0f;
  5128.         enableMotor = false;
  5129.         maxMotorForce = 0.0f;
  5130.         motorSpeed = 0.0f;
  5131.     }
  5132.  
  5133.     /// Initialize the bodies, anchors, axis, and reference angle using the world
  5134.     /// anchor and unit world axis.
  5135.     void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
  5136.  
  5137.     /// The local anchor point relative to bodyA's origin.
  5138.     b2Vec2 localAnchorA;
  5139.  
  5140.     /// The local anchor point relative to bodyB's origin.
  5141.     b2Vec2 localAnchorB;
  5142.  
  5143.     /// The local translation unit axis in bodyA.
  5144.     b2Vec2 localAxisA;
  5145.  
  5146.     /// The constrained angle between the bodies: bodyB_angle - bodyA_angle.
  5147.     float referenceAngle;
  5148.  
  5149.     /// Enable/disable the joint limit.
  5150.     bool enableLimit;
  5151.  
  5152.     /// The lower translation limit, usually in meters.
  5153.     float lowerTranslation;
  5154.  
  5155.     /// The upper translation limit, usually in meters.
  5156.     float upperTranslation;
  5157.  
  5158.     /// Enable/disable the joint motor.
  5159.     bool enableMotor;
  5160.  
  5161.     /// The maximum motor torque, usually in N-m.
  5162.     float maxMotorForce;
  5163.  
  5164.     /// The desired motor speed in radians per second.
  5165.     float motorSpeed;
  5166. };
  5167.  
  5168. /// A prismatic joint. This joint provides one degree of freedom: translation
  5169. /// along an axis fixed in bodyA. Relative rotation is prevented. You can
  5170. /// use a joint limit to restrict the range of motion and a joint motor to
  5171. /// drive the motion or to model joint friction.
  5172. class B2_API b2PrismaticJoint : public b2Joint {
  5173. public:
  5174.     b2Vec2 GetAnchorA() const override;
  5175.     b2Vec2 GetAnchorB() const override;
  5176.  
  5177.     b2Vec2 GetReactionForce(float inv_dt) const override;
  5178.     float GetReactionTorque(float inv_dt) const override;
  5179.  
  5180.     /// The local anchor point relative to bodyA's origin.
  5181.     const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
  5182.  
  5183.     /// The local anchor point relative to bodyB's origin.
  5184.     const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
  5185.  
  5186.     /// The local joint axis relative to bodyA.
  5187.     const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; }
  5188.  
  5189.     /// Get the reference angle.
  5190.     float GetReferenceAngle() const { return m_referenceAngle; }
  5191.  
  5192.     /// Get the current joint translation, usually in meters.
  5193.     float GetJointTranslation() const;
  5194.  
  5195.     /// Get the current joint translation speed, usually in meters per second.
  5196.     float GetJointSpeed() const;
  5197.  
  5198.     /// Is the joint limit enabled?
  5199.     bool IsLimitEnabled() const;
  5200.  
  5201.     /// Enable/disable the joint limit.
  5202.     void EnableLimit(bool flag);
  5203.  
  5204.     /// Get the lower joint limit, usually in meters.
  5205.     float GetLowerLimit() const;
  5206.  
  5207.     /// Get the upper joint limit, usually in meters.
  5208.     float GetUpperLimit() const;
  5209.  
  5210.     /// Set the joint limits, usually in meters.
  5211.     void SetLimits(float lower, float upper);
  5212.  
  5213.     /// Is the joint motor enabled?
  5214.     bool IsMotorEnabled() const;
  5215.  
  5216.     /// Enable/disable the joint motor.
  5217.     void EnableMotor(bool flag);
  5218.  
  5219.     /// Set the motor speed, usually in meters per second.
  5220.     void SetMotorSpeed(float speed);
  5221.  
  5222.     /// Get the motor speed, usually in meters per second.
  5223.     float GetMotorSpeed() const;
  5224.  
  5225.     /// Set the maximum motor force, usually in N.
  5226.     void SetMaxMotorForce(float force);
  5227.     float GetMaxMotorForce() const { return m_maxMotorForce; }
  5228.  
  5229.     /// Get the current motor force given the inverse time step, usually in N.
  5230.     float GetMotorForce(float inv_dt) const;
  5231.  
  5232.     /// Dump to b2Log
  5233.     void Dump() override;
  5234.  
  5235.     ///
  5236.     void Draw(b2Draw* draw) const override;
  5237.  
  5238. protected:
  5239.     friend class b2Joint;
  5240.     friend class b2GearJoint;
  5241.     b2PrismaticJoint(const b2PrismaticJointDef* def);
  5242.  
  5243.     void InitVelocityConstraints(const b2SolverData& data) override;
  5244.     void SolveVelocityConstraints(const b2SolverData& data) override;
  5245.     bool SolvePositionConstraints(const b2SolverData& data) override;
  5246.  
  5247.     b2Vec2 m_localAnchorA;
  5248.     b2Vec2 m_localAnchorB;
  5249.     b2Vec2 m_localXAxisA;
  5250.     b2Vec2 m_localYAxisA;
  5251.     float m_referenceAngle;
  5252.     b2Vec2 m_impulse;
  5253.     float m_motorImpulse;
  5254.     float m_lowerImpulse;
  5255.     float m_upperImpulse;
  5256.     float m_lowerTranslation;
  5257.     float m_upperTranslation;
  5258.     float m_maxMotorForce;
  5259.     float m_motorSpeed;
  5260.     bool m_enableLimit;
  5261.     bool m_enableMotor;
  5262.  
  5263.     // Solver temp
  5264.     int32 m_indexA;
  5265.     int32 m_indexB;
  5266.     b2Vec2 m_localCenterA;
  5267.     b2Vec2 m_localCenterB;
  5268.     float m_invMassA;
  5269.     float m_invMassB;
  5270.     float m_invIA;
  5271.     float m_invIB;
  5272.     b2Vec2 m_axis, m_perp;
  5273.     float m_s1, m_s2;
  5274.     float m_a1, m_a2;
  5275.     b2Mat22 m_K;
  5276.     float m_translation;
  5277.     float m_axialMass;
  5278. };
  5279.  
  5280. inline float b2PrismaticJoint::GetMotorSpeed() const {
  5281.     return m_motorSpeed;
  5282. }
  5283.  
  5284. #endif
  5285. // MIT License
  5286.  
  5287. // Copyright (c) 2019 Erin Catto
  5288.  
  5289. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5290. // of this software and associated documentation files (the "Software"), to deal
  5291. // in the Software without restriction, including without limitation the rights
  5292. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5293. // copies of the Software, and to permit persons to whom the Software is
  5294. // furnished to do so, subject to the following conditions:
  5295.  
  5296. // The above copyright notice and this permission notice shall be included in all
  5297. // copies or substantial portions of the Software.
  5298.  
  5299. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5300. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5301. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5302. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5303. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5304. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5305. // SOFTWARE.
  5306.  
  5307. #ifndef B2_PULLEY_JOINT_H
  5308. #define B2_PULLEY_JOINT_H
  5309.  
  5310. //#include "b2_api.h"
  5311. //#include "b2_joint.h"
  5312.  
  5313. const float b2_minPulleyLength = 2.0f;
  5314.  
  5315. /// Pulley joint definition. This requires two ground anchors,
  5316. /// two dynamic body anchor points, and a pulley ratio.
  5317. struct B2_API b2PulleyJointDef : public b2JointDef {
  5318.     b2PulleyJointDef() {
  5319.         type = e_pulleyJoint;
  5320.         groundAnchorA.Set(-1.0f, 1.0f);
  5321.         groundAnchorB.Set(1.0f, 1.0f);
  5322.         localAnchorA.Set(-1.0f, 0.0f);
  5323.         localAnchorB.Set(1.0f, 0.0f);
  5324.         lengthA = 0.0f;
  5325.         lengthB = 0.0f;
  5326.         ratio = 1.0f;
  5327.         collideConnected = true;
  5328.     }
  5329.  
  5330.     /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
  5331.     void Initialize(b2Body* bodyA, b2Body* bodyB,
  5332.         const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB,
  5333.         const b2Vec2& anchorA, const b2Vec2& anchorB,
  5334.         float ratio);
  5335.  
  5336.     /// The first ground anchor in world coordinates. This point never moves.
  5337.     b2Vec2 groundAnchorA;
  5338.  
  5339.     /// The second ground anchor in world coordinates. This point never moves.
  5340.     b2Vec2 groundAnchorB;
  5341.  
  5342.     /// The local anchor point relative to bodyA's origin.
  5343.     b2Vec2 localAnchorA;
  5344.  
  5345.     /// The local anchor point relative to bodyB's origin.
  5346.     b2Vec2 localAnchorB;
  5347.  
  5348.     /// The a reference length for the segment attached to bodyA.
  5349.     float lengthA;
  5350.  
  5351.     /// The a reference length for the segment attached to bodyB.
  5352.     float lengthB;
  5353.  
  5354.     /// The pulley ratio, used to simulate a block-and-tackle.
  5355.     float ratio;
  5356. };
  5357.  
  5358. /// The pulley joint is connected to two bodies and two fixed ground points.
  5359. /// The pulley supports a ratio such that:
  5360. /// length1 + ratio * length2 <= constant
  5361. /// Yes, the force transmitted is scaled by the ratio.
  5362. /// Warning: the pulley joint can get a bit squirrelly by itself. They often
  5363. /// work better when combined with prismatic joints. You should also cover the
  5364. /// the anchor points with static shapes to prevent one side from going to
  5365. /// zero length.
  5366. class B2_API b2PulleyJoint : public b2Joint {
  5367. public:
  5368.     b2Vec2 GetAnchorA() const override;
  5369.     b2Vec2 GetAnchorB() const override;
  5370.  
  5371.     b2Vec2 GetReactionForce(float inv_dt) const override;
  5372.     float GetReactionTorque(float inv_dt) const override;
  5373.  
  5374.     /// Get the first ground anchor.
  5375.     b2Vec2 GetGroundAnchorA() const;
  5376.  
  5377.     /// Get the second ground anchor.
  5378.     b2Vec2 GetGroundAnchorB() const;
  5379.  
  5380.     /// Get the current length of the segment attached to bodyA.
  5381.     float GetLengthA() const;
  5382.  
  5383.     /// Get the current length of the segment attached to bodyB.
  5384.     float GetLengthB() const;
  5385.  
  5386.     /// Get the pulley ratio.
  5387.     float GetRatio() const;
  5388.  
  5389.     /// Get the current length of the segment attached to bodyA.
  5390.     float GetCurrentLengthA() const;
  5391.  
  5392.     /// Get the current length of the segment attached to bodyB.
  5393.     float GetCurrentLengthB() const;
  5394.  
  5395.     /// Dump joint to dmLog
  5396.     void Dump() override;
  5397.  
  5398.     /// Implement b2Joint::ShiftOrigin
  5399.     void ShiftOrigin(const b2Vec2& newOrigin) override;
  5400.  
  5401. protected:
  5402.  
  5403.     friend class b2Joint;
  5404.     b2PulleyJoint(const b2PulleyJointDef* data);
  5405.  
  5406.     void InitVelocityConstraints(const b2SolverData& data) override;
  5407.     void SolveVelocityConstraints(const b2SolverData& data) override;
  5408.     bool SolvePositionConstraints(const b2SolverData& data) override;
  5409.  
  5410.     b2Vec2 m_groundAnchorA;
  5411.     b2Vec2 m_groundAnchorB;
  5412.     float m_lengthA;
  5413.     float m_lengthB;
  5414.  
  5415.     // Solver shared
  5416.     b2Vec2 m_localAnchorA;
  5417.     b2Vec2 m_localAnchorB;
  5418.     float m_constant;
  5419.     float m_ratio;
  5420.     float m_impulse;
  5421.  
  5422.     // Solver temp
  5423.     int32 m_indexA;
  5424.     int32 m_indexB;
  5425.     b2Vec2 m_uA;
  5426.     b2Vec2 m_uB;
  5427.     b2Vec2 m_rA;
  5428.     b2Vec2 m_rB;
  5429.     b2Vec2 m_localCenterA;
  5430.     b2Vec2 m_localCenterB;
  5431.     float m_invMassA;
  5432.     float m_invMassB;
  5433.     float m_invIA;
  5434.     float m_invIB;
  5435.     float m_mass;
  5436. };
  5437.  
  5438. #endif
  5439. // MIT License
  5440.  
  5441. // Copyright (c) 2019 Erin Catto
  5442.  
  5443. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5444. // of this software and associated documentation files (the "Software"), to deal
  5445. // in the Software without restriction, including without limitation the rights
  5446. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5447. // copies of the Software, and to permit persons to whom the Software is
  5448. // furnished to do so, subject to the following conditions:
  5449.  
  5450. // The above copyright notice and this permission notice shall be included in all
  5451. // copies or substantial portions of the Software.
  5452.  
  5453. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5454. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5455. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5456. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5457. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5458. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5459. // SOFTWARE.
  5460.  
  5461. #ifndef B2_REVOLUTE_JOINT_H
  5462. #define B2_REVOLUTE_JOINT_H
  5463.  
  5464. //#include "b2_api.h"
  5465. //#include "b2_joint.h"
  5466.  
  5467. /// Revolute joint definition. This requires defining an anchor point where the
  5468. /// bodies are joined. The definition uses local anchor points so that the
  5469. /// initial configuration can violate the constraint slightly. You also need to
  5470. /// specify the initial relative angle for joint limits. This helps when saving
  5471. /// and loading a game.
  5472. /// The local anchor points are measured from the body's origin
  5473. /// rather than the center of mass because:
  5474. /// 1. you might not know where the center of mass will be.
  5475. /// 2. if you add/remove shapes from a body and recompute the mass,
  5476. ///    the joints will be broken.
  5477. struct B2_API b2RevoluteJointDef : public b2JointDef {
  5478.     b2RevoluteJointDef() {
  5479.         type = e_revoluteJoint;
  5480.         localAnchorA.Set(0.0f, 0.0f);
  5481.         localAnchorB.Set(0.0f, 0.0f);
  5482.         referenceAngle = 0.0f;
  5483.         lowerAngle = 0.0f;
  5484.         upperAngle = 0.0f;
  5485.         maxMotorTorque = 0.0f;
  5486.         motorSpeed = 0.0f;
  5487.         enableLimit = false;
  5488.         enableMotor = false;
  5489.     }
  5490.  
  5491.     /// Initialize the bodies, anchors, and reference angle using a world
  5492.     /// anchor point.
  5493.     void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
  5494.  
  5495.     /// The local anchor point relative to bodyA's origin.
  5496.     b2Vec2 localAnchorA;
  5497.  
  5498.     /// The local anchor point relative to bodyB's origin.
  5499.     b2Vec2 localAnchorB;
  5500.  
  5501.     /// The bodyB angle minus bodyA angle in the reference state (radians).
  5502.     float referenceAngle;
  5503.  
  5504.     /// A flag to enable joint limits.
  5505.     bool enableLimit;
  5506.  
  5507.     /// The lower angle for the joint limit (radians).
  5508.     float lowerAngle;
  5509.  
  5510.     /// The upper angle for the joint limit (radians).
  5511.     float upperAngle;
  5512.  
  5513.     /// A flag to enable the joint motor.
  5514.     bool enableMotor;
  5515.  
  5516.     /// The desired motor speed. Usually in radians per second.
  5517.     float motorSpeed;
  5518.  
  5519.     /// The maximum motor torque used to achieve the desired motor speed.
  5520.     /// Usually in N-m.
  5521.     float maxMotorTorque;
  5522. };
  5523.  
  5524. /// A revolute joint constrains two bodies to share a common point while they
  5525. /// are free to rotate about the point. The relative rotation about the shared
  5526. /// point is the joint angle. You can limit the relative rotation with
  5527. /// a joint limit that specifies a lower and upper angle. You can use a motor
  5528. /// to drive the relative rotation about the shared point. A maximum motor torque
  5529. /// is provided so that infinite forces are not generated.
  5530. class B2_API b2RevoluteJoint : public b2Joint {
  5531. public:
  5532.     b2Vec2 GetAnchorA() const override;
  5533.     b2Vec2 GetAnchorB() const override;
  5534.  
  5535.     /// The local anchor point relative to bodyA's origin.
  5536.     const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
  5537.  
  5538.     /// The local anchor point relative to bodyB's origin.
  5539.     const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
  5540.  
  5541.     /// Get the reference angle.
  5542.     float GetReferenceAngle() const { return m_referenceAngle; }
  5543.  
  5544.     /// Get the current joint angle in radians.
  5545.     float GetJointAngle() const;
  5546.  
  5547.     /// Get the current joint angle speed in radians per second.
  5548.     float GetJointSpeed() const;
  5549.  
  5550.     /// Is the joint limit enabled?
  5551.     bool IsLimitEnabled() const;
  5552.  
  5553.     /// Enable/disable the joint limit.
  5554.     void EnableLimit(bool flag);
  5555.  
  5556.     /// Get the lower joint limit in radians.
  5557.     float GetLowerLimit() const;
  5558.  
  5559.     /// Get the upper joint limit in radians.
  5560.     float GetUpperLimit() const;
  5561.  
  5562.     /// Set the joint limits in radians.
  5563.     void SetLimits(float lower, float upper);
  5564.  
  5565.     /// Is the joint motor enabled?
  5566.     bool IsMotorEnabled() const;
  5567.  
  5568.     /// Enable/disable the joint motor.
  5569.     void EnableMotor(bool flag);
  5570.  
  5571.     /// Set the motor speed in radians per second.
  5572.     void SetMotorSpeed(float speed);
  5573.  
  5574.     /// Get the motor speed in radians per second.
  5575.     float GetMotorSpeed() const;
  5576.  
  5577.     /// Set the maximum motor torque, usually in N-m.
  5578.     void SetMaxMotorTorque(float torque);
  5579.     float GetMaxMotorTorque() const { return m_maxMotorTorque; }
  5580.  
  5581.     /// Get the reaction force given the inverse time step.
  5582.     /// Unit is N.
  5583.     b2Vec2 GetReactionForce(float inv_dt) const override;
  5584.  
  5585.     /// Get the reaction torque due to the joint limit given the inverse time step.
  5586.     /// Unit is N*m.
  5587.     float GetReactionTorque(float inv_dt) const override;
  5588.  
  5589.     /// Get the current motor torque given the inverse time step.
  5590.     /// Unit is N*m.
  5591.     float GetMotorTorque(float inv_dt) const;
  5592.  
  5593.     /// Dump to b2Log.
  5594.     void Dump() override;
  5595.  
  5596.     ///
  5597.     void Draw(b2Draw* draw) const override;
  5598.  
  5599. protected:
  5600.  
  5601.     friend class b2Joint;
  5602.     friend class b2GearJoint;
  5603.  
  5604.     b2RevoluteJoint(const b2RevoluteJointDef* def);
  5605.  
  5606.     void InitVelocityConstraints(const b2SolverData& data) override;
  5607.     void SolveVelocityConstraints(const b2SolverData& data) override;
  5608.     bool SolvePositionConstraints(const b2SolverData& data) override;
  5609.  
  5610.     // Solver shared
  5611.     b2Vec2 m_localAnchorA;
  5612.     b2Vec2 m_localAnchorB;
  5613.     b2Vec2 m_impulse;
  5614.     float m_motorImpulse;
  5615.     float m_lowerImpulse;
  5616.     float m_upperImpulse;
  5617.     bool m_enableMotor;
  5618.     float m_maxMotorTorque;
  5619.     float m_motorSpeed;
  5620.     bool m_enableLimit;
  5621.     float m_referenceAngle;
  5622.     float m_lowerAngle;
  5623.     float m_upperAngle;
  5624.  
  5625.     // Solver temp
  5626.     int32 m_indexA;
  5627.     int32 m_indexB;
  5628.     b2Vec2 m_rA;
  5629.     b2Vec2 m_rB;
  5630.     b2Vec2 m_localCenterA;
  5631.     b2Vec2 m_localCenterB;
  5632.     float m_invMassA;
  5633.     float m_invMassB;
  5634.     float m_invIA;
  5635.     float m_invIB;
  5636.     b2Mat22 m_K;
  5637.     float m_angle;
  5638.     float m_axialMass;
  5639. };
  5640.  
  5641. inline float b2RevoluteJoint::GetMotorSpeed() const {
  5642.     return m_motorSpeed;
  5643. }
  5644.  
  5645. #endif
  5646. // MIT License
  5647.  
  5648. // Copyright (c) 2019 Erin Catto
  5649.  
  5650. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5651. // of this software and associated documentation files (the "Software"), to deal
  5652. // in the Software without restriction, including without limitation the rights
  5653. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5654. // copies of the Software, and to permit persons to whom the Software is
  5655. // furnished to do so, subject to the following conditions:
  5656.  
  5657. // The above copyright notice and this permission notice shall be included in all
  5658. // copies or substantial portions of the Software.
  5659.  
  5660. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5661. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5662. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5663. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5664. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5665. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5666. // SOFTWARE.
  5667.  
  5668. #ifndef B2_ROPE_H
  5669. #define B2_ROPE_H
  5670.  
  5671. //#include "b2_api.h"
  5672. //#include "b2_math.h"
  5673.  
  5674. class b2Draw;
  5675. struct b2RopeStretch;
  5676. struct b2RopeBend;
  5677.  
  5678. enum b2StretchingModel {
  5679.     b2_pbdStretchingModel,
  5680.     b2_xpbdStretchingModel
  5681. };
  5682.  
  5683. enum b2BendingModel {
  5684.     b2_springAngleBendingModel = 0,
  5685.     b2_pbdAngleBendingModel,
  5686.     b2_xpbdAngleBendingModel,
  5687.     b2_pbdDistanceBendingModel,
  5688.     b2_pbdHeightBendingModel,
  5689.     b2_pbdTriangleBendingModel
  5690. };
  5691.  
  5692. ///
  5693. struct B2_API b2RopeTuning {
  5694.     b2RopeTuning() {
  5695.         stretchingModel = b2_pbdStretchingModel;
  5696.         bendingModel = b2_pbdAngleBendingModel;
  5697.         damping = 0.0f;
  5698.         stretchStiffness = 1.0f;
  5699.         bendStiffness = 0.5f;
  5700.         bendHertz = 1.0f;
  5701.         bendDamping = 0.0f;
  5702.         isometric = false;
  5703.         fixedEffectiveMass = false;
  5704.         warmStart = false;
  5705.     }
  5706.  
  5707.     b2StretchingModel stretchingModel;
  5708.     b2BendingModel bendingModel;
  5709.     float damping;
  5710.     float stretchStiffness;
  5711.     float stretchHertz;
  5712.     float stretchDamping;
  5713.     float bendStiffness;
  5714.     float bendHertz;
  5715.     float bendDamping;
  5716.     bool isometric;
  5717.     bool fixedEffectiveMass;
  5718.     bool warmStart;
  5719. };
  5720.  
  5721. ///
  5722. struct B2_API b2RopeDef {
  5723.     b2RopeDef() {
  5724.         position.SetZero();
  5725.         vertices = nullptr;
  5726.         count = 0;
  5727.         masses = nullptr;
  5728.         gravity.SetZero();
  5729.     }
  5730.  
  5731.     b2Vec2 position;
  5732.     b2Vec2* vertices;
  5733.     int32 count;
  5734.     float* masses;
  5735.     b2Vec2 gravity;
  5736.     b2RopeTuning tuning;
  5737. };
  5738.  
  5739. ///
  5740. class B2_API b2Rope {
  5741. public:
  5742.     b2Rope();
  5743.     ~b2Rope();
  5744.  
  5745.     ///
  5746.     void Create(const b2RopeDef& def);
  5747.  
  5748.     ///
  5749.     void SetTuning(const b2RopeTuning& tuning);
  5750.  
  5751.     ///
  5752.     void Step(float timeStep, int32 iterations, const b2Vec2& position);
  5753.  
  5754.     ///
  5755.     void Reset(const b2Vec2& position);
  5756.  
  5757.     ///
  5758.     void Draw(b2Draw* draw) const;
  5759.  
  5760. private:
  5761.  
  5762.     void SolveStretch_PBD();
  5763.     void SolveStretch_XPBD(float dt);
  5764.     void SolveBend_PBD_Angle();
  5765.     void SolveBend_XPBD_Angle(float dt);
  5766.     void SolveBend_PBD_Distance();
  5767.     void SolveBend_PBD_Height();
  5768.     void SolveBend_PBD_Triangle();
  5769.     void ApplyBendForces(float dt);
  5770.  
  5771.     b2Vec2 m_position;
  5772.  
  5773.     int32 m_count;
  5774.     int32 m_stretchCount;
  5775.     int32 m_bendCount;
  5776.  
  5777.     b2RopeStretch* m_stretchConstraints;
  5778.     b2RopeBend* m_bendConstraints;
  5779.  
  5780.     b2Vec2* m_bindPositions;
  5781.     b2Vec2* m_ps;
  5782.     b2Vec2* m_p0s;
  5783.     b2Vec2* m_vs;
  5784.  
  5785.     float* m_invMasses;
  5786.     b2Vec2 m_gravity;
  5787.  
  5788.     b2RopeTuning m_tuning;
  5789. };
  5790.  
  5791. #endif
  5792. // MIT License
  5793.  
  5794. // Copyright (c) 2019 Erin Catto
  5795.  
  5796. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5797. // of this software and associated documentation files (the "Software"), to deal
  5798. // in the Software without restriction, including without limitation the rights
  5799. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5800. // copies of the Software, and to permit persons to whom the Software is
  5801. // furnished to do so, subject to the following conditions:
  5802.  
  5803. // The above copyright notice and this permission notice shall be included in all
  5804. // copies or substantial portions of the Software.
  5805.  
  5806. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5807. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5808. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5809. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5810. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5811. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5812. // SOFTWARE.
  5813.  
  5814. #ifndef B2_TIMER_H
  5815. #define B2_TIMER_H
  5816.  
  5817. //#include "b2_api.h"
  5818. //#include "b2_settings.h"
  5819.  
  5820. /// Timer for profiling. This has platform specific code and may
  5821. /// not work on every platform.
  5822. class B2_API b2Timer {
  5823. public:
  5824.  
  5825.     /// Constructor
  5826.     b2Timer();
  5827.  
  5828.     /// Reset the timer.
  5829.     void Reset();
  5830.  
  5831.     /// Get the time since construction or the last reset.
  5832.     float GetMilliseconds() const;
  5833.  
  5834. private:
  5835.  
  5836. #if defined(_WIN32)
  5837.     double m_start;
  5838.     static double s_invFrequency;
  5839. #elif defined(__linux__) || defined (__APPLE__)
  5840.     unsigned long long m_start_sec;
  5841.     unsigned long long m_start_usec;
  5842. #endif
  5843. };
  5844.  
  5845. #endif
  5846. // MIT License
  5847.  
  5848. // Copyright (c) 2019 Erin Catto
  5849.  
  5850. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5851. // of this software and associated documentation files (the "Software"), to deal
  5852. // in the Software without restriction, including without limitation the rights
  5853. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5854. // copies of the Software, and to permit persons to whom the Software is
  5855. // furnished to do so, subject to the following conditions:
  5856.  
  5857. // The above copyright notice and this permission notice shall be included in all
  5858. // copies or substantial portions of the Software.
  5859.  
  5860. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5861. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5862. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5863. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5864. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5865. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5866. // SOFTWARE.
  5867.  
  5868. #ifndef B2_TIME_OF_IMPACT_H
  5869. #define B2_TIME_OF_IMPACT_H
  5870.  
  5871. //#include "b2_api.h"
  5872. //#include "b2_math.h"
  5873. //#include "b2_distance.h"
  5874.  
  5875. /// Input parameters for b2TimeOfImpact
  5876. struct B2_API b2TOIInput {
  5877.     b2DistanceProxy proxyA;
  5878.     b2DistanceProxy proxyB;
  5879.     b2Sweep sweepA;
  5880.     b2Sweep sweepB;
  5881.     float tMax;     // defines sweep interval [0, tMax]
  5882. };
  5883.  
  5884. /// Output parameters for b2TimeOfImpact.
  5885. struct B2_API b2TOIOutput {
  5886.     enum State {
  5887.         e_unknown,
  5888.         e_failed,
  5889.         e_overlapped,
  5890.         e_touching,
  5891.         e_separated
  5892.     };
  5893.  
  5894.     State state;
  5895.     float t;
  5896. };
  5897.  
  5898. /// Compute the upper bound on time before two shapes penetrate. Time is represented as
  5899. /// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
  5900. /// non-tunneling collisions. If you change the time interval, you should call this function
  5901. /// again.
  5902. /// Note: use b2Distance to compute the contact point and normal at the time of impact.
  5903. B2_API void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input);
  5904.  
  5905. #endif
  5906. // MIT License
  5907.  
  5908. // Copyright (c) 2019 Erin Catto
  5909.  
  5910. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5911. // of this software and associated documentation files (the "Software"), to deal
  5912. // in the Software without restriction, including without limitation the rights
  5913. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5914. // copies of the Software, and to permit persons to whom the Software is
  5915. // furnished to do so, subject to the following conditions:
  5916.  
  5917. // The above copyright notice and this permission notice shall be included in all
  5918. // copies or substantial portions of the Software.
  5919.  
  5920. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5921. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5922. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5923. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5924. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5925. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5926. // SOFTWARE.
  5927. #ifndef B2_TIME_STEP_H
  5928. #define B2_TIME_STEP_H
  5929.  
  5930. //#include "b2_api.h"
  5931. //#include "b2_math.h"
  5932.  
  5933. /// Profiling data. Times are in milliseconds.
  5934. struct B2_API b2Profile {
  5935.     float step;
  5936.     float collide;
  5937.     float solve;
  5938.     float solveInit;
  5939.     float solveVelocity;
  5940.     float solvePosition;
  5941.     float broadphase;
  5942.     float solveTOI;
  5943. };
  5944.  
  5945. /// This is an internal structure.
  5946. struct B2_API b2TimeStep {
  5947.     float dt;           // time step
  5948.     float inv_dt;       // inverse time step (0 if dt == 0).
  5949.     float dtRatio;  // dt * inv_dt0
  5950.     int32 velocityIterations;
  5951.     int32 positionIterations;
  5952.     bool warmStarting;
  5953. };
  5954.  
  5955. /// This is an internal structure.
  5956. struct B2_API b2Position {
  5957.     b2Vec2 c;
  5958.     float a;
  5959. };
  5960.  
  5961. /// This is an internal structure.
  5962. struct B2_API b2Velocity {
  5963.     b2Vec2 v;
  5964.     float w;
  5965. };
  5966.  
  5967. /// Solver Data
  5968. struct B2_API b2SolverData {
  5969.     b2TimeStep step;
  5970.     b2Position* positions;
  5971.     b2Velocity* velocities;
  5972. };
  5973.  
  5974. #endif
  5975. // MIT License
  5976.  
  5977. // Copyright (c) 2019 Erin Catto
  5978.  
  5979. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5980. // of this software and associated documentation files (the "Software"), to deal
  5981. // in the Software without restriction, including without limitation the rights
  5982. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5983. // copies of the Software, and to permit persons to whom the Software is
  5984. // furnished to do so, subject to the following conditions:
  5985.  
  5986. // The above copyright notice and this permission notice shall be included in all
  5987. // copies or substantial portions of the Software.
  5988.  
  5989. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5990. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5991. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5992. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5993. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5994. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  5995. // SOFTWARE.
  5996.  
  5997. #ifndef B2_WELD_JOINT_H
  5998. #define B2_WELD_JOINT_H
  5999.  
  6000. //#include "b2_api.h"
  6001. //#include "b2_joint.h"
  6002.  
  6003. /// Weld joint definition. You need to specify local anchor points
  6004. /// where they are attached and the relative body angle. The position
  6005. /// of the anchor points is important for computing the reaction torque.
  6006. struct B2_API b2WeldJointDef : public b2JointDef {
  6007.     b2WeldJointDef() {
  6008.         type = e_weldJoint;
  6009.         localAnchorA.Set(0.0f, 0.0f);
  6010.         localAnchorB.Set(0.0f, 0.0f);
  6011.         referenceAngle = 0.0f;
  6012.         stiffness = 0.0f;
  6013.         damping = 0.0f;
  6014.     }
  6015.  
  6016.     /// Initialize the bodies, anchors, reference angle, stiffness, and damping.
  6017.     /// @param bodyA the first body connected by this joint
  6018.     /// @param bodyB the second body connected by this joint
  6019.     /// @param anchor the point of connection in world coordinates
  6020.     void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
  6021.  
  6022.     /// The local anchor point relative to bodyA's origin.
  6023.     b2Vec2 localAnchorA;
  6024.  
  6025.     /// The local anchor point relative to bodyB's origin.
  6026.     b2Vec2 localAnchorB;
  6027.  
  6028.     /// The bodyB angle minus bodyA angle in the reference state (radians).
  6029.     float referenceAngle;
  6030.  
  6031.     /// The rotational stiffness in N*m
  6032.     /// Disable softness with a value of 0
  6033.     float stiffness;
  6034.  
  6035.     /// The rotational damping in N*m*s
  6036.     float damping;
  6037. };
  6038.  
  6039. /// A weld joint essentially glues two bodies together. A weld joint may
  6040. /// distort somewhat because the island constraint solver is approximate.
  6041. class B2_API b2WeldJoint : public b2Joint {
  6042. public:
  6043.     b2Vec2 GetAnchorA() const override;
  6044.     b2Vec2 GetAnchorB() const override;
  6045.  
  6046.     b2Vec2 GetReactionForce(float inv_dt) const override;
  6047.     float GetReactionTorque(float inv_dt) const override;
  6048.  
  6049.     /// The local anchor point relative to bodyA's origin.
  6050.     const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
  6051.  
  6052.     /// The local anchor point relative to bodyB's origin.
  6053.     const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
  6054.  
  6055.     /// Get the reference angle.
  6056.     float GetReferenceAngle() const { return m_referenceAngle; }
  6057.  
  6058.     /// Set/get stiffness in N*m
  6059.     void SetStiffness(float hz) { m_stiffness = hz; }
  6060.     float GetStiffness() const { return m_stiffness; }
  6061.  
  6062.     /// Set/get damping in N*m*s
  6063.     void SetDamping(float damping) { m_damping = damping; }
  6064.     float GetDamping() const { return m_damping; }
  6065.  
  6066.     /// Dump to b2Log
  6067.     void Dump() override;
  6068.  
  6069. protected:
  6070.  
  6071.     friend class b2Joint;
  6072.  
  6073.     b2WeldJoint(const b2WeldJointDef* def);
  6074.  
  6075.     void InitVelocityConstraints(const b2SolverData& data) override;
  6076.     void SolveVelocityConstraints(const b2SolverData& data) override;
  6077.     bool SolvePositionConstraints(const b2SolverData& data) override;
  6078.  
  6079.     float m_stiffness;
  6080.     float m_damping;
  6081.     float m_bias;
  6082.  
  6083.     // Solver shared
  6084.     b2Vec2 m_localAnchorA;
  6085.     b2Vec2 m_localAnchorB;
  6086.     float m_referenceAngle;
  6087.     float m_gamma;
  6088.     b2Vec3 m_impulse;
  6089.  
  6090.     // Solver temp
  6091.     int32 m_indexA;
  6092.     int32 m_indexB;
  6093.     b2Vec2 m_rA;
  6094.     b2Vec2 m_rB;
  6095.     b2Vec2 m_localCenterA;
  6096.     b2Vec2 m_localCenterB;
  6097.     float m_invMassA;
  6098.     float m_invMassB;
  6099.     float m_invIA;
  6100.     float m_invIB;
  6101.     b2Mat33 m_mass;
  6102. };
  6103.  
  6104. #endif
  6105. // MIT License
  6106.  
  6107. // Copyright (c) 2019 Erin Catto
  6108.  
  6109. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6110. // of this software and associated documentation files (the "Software"), to deal
  6111. // in the Software without restriction, including without limitation the rights
  6112. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6113. // copies of the Software, and to permit persons to whom the Software is
  6114. // furnished to do so, subject to the following conditions:
  6115.  
  6116. // The above copyright notice and this permission notice shall be included in all
  6117. // copies or substantial portions of the Software.
  6118.  
  6119. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6120. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6121. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  6122. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6123. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6124. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  6125. // SOFTWARE.
  6126.  
  6127. #ifndef B2_WHEEL_JOINT_H
  6128. #define B2_WHEEL_JOINT_H
  6129.  
  6130. //#include "b2_api.h"
  6131. //#include "b2_joint.h"
  6132.  
  6133. /// Wheel joint definition. This requires defining a line of
  6134. /// motion using an axis and an anchor point. The definition uses local
  6135. /// anchor points and a local axis so that the initial configuration
  6136. /// can violate the constraint slightly. The joint translation is zero
  6137. /// when the local anchor points coincide in world space. Using local
  6138. /// anchors and a local axis helps when saving and loading a game.
  6139. struct B2_API b2WheelJointDef : public b2JointDef {
  6140.     b2WheelJointDef() {
  6141.         type = e_wheelJoint;
  6142.         localAnchorA.SetZero();
  6143.         localAnchorB.SetZero();
  6144.         localAxisA.Set(1.0f, 0.0f);
  6145.         enableLimit = false;
  6146.         lowerTranslation = 0.0f;
  6147.         upperTranslation = 0.0f;
  6148.         enableMotor = false;
  6149.         maxMotorTorque = 0.0f;
  6150.         motorSpeed = 0.0f;
  6151.         stiffness = 0.0f;
  6152.         damping = 0.0f;
  6153.     }
  6154.  
  6155.     /// Initialize the bodies, anchors, axis, and reference angle using the world
  6156.     /// anchor and world axis.
  6157.     void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
  6158.  
  6159.     /// The local anchor point relative to bodyA's origin.
  6160.     b2Vec2 localAnchorA;
  6161.  
  6162.     /// The local anchor point relative to bodyB's origin.
  6163.     b2Vec2 localAnchorB;
  6164.  
  6165.     /// The local translation axis in bodyA.
  6166.     b2Vec2 localAxisA;
  6167.  
  6168.     /// Enable/disable the joint limit.
  6169.     bool enableLimit;
  6170.  
  6171.     /// The lower translation limit, usually in meters.
  6172.     float lowerTranslation;
  6173.  
  6174.     /// The upper translation limit, usually in meters.
  6175.     float upperTranslation;
  6176.  
  6177.     /// Enable/disable the joint motor.
  6178.     bool enableMotor;
  6179.  
  6180.     /// The maximum motor torque, usually in N-m.
  6181.     float maxMotorTorque;
  6182.  
  6183.     /// The desired motor speed in radians per second.
  6184.     float motorSpeed;
  6185.  
  6186.     /// Suspension stiffness. Typically in units N/m.
  6187.     float stiffness;
  6188.  
  6189.     /// Suspension damping. Typically in units of N*s/m.
  6190.     float damping;
  6191. };
  6192.  
  6193. /// A wheel joint. This joint provides two degrees of freedom: translation
  6194. /// along an axis fixed in bodyA and rotation in the plane. In other words, it is a point to
  6195. /// line constraint with a rotational motor and a linear spring/damper. The spring/damper is
  6196. /// initialized upon creation. This joint is designed for vehicle suspensions.
  6197. class B2_API b2WheelJoint : public b2Joint {
  6198. public:
  6199.     b2Vec2 GetAnchorA() const override;
  6200.     b2Vec2 GetAnchorB() const override;
  6201.  
  6202.     b2Vec2 GetReactionForce(float inv_dt) const override;
  6203.     float GetReactionTorque(float inv_dt) const override;
  6204.  
  6205.     /// The local anchor point relative to bodyA's origin.
  6206.     const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
  6207.  
  6208.     /// The local anchor point relative to bodyB's origin.
  6209.     const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
  6210.  
  6211.     /// The local joint axis relative to bodyA.
  6212.     const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; }
  6213.  
  6214.     /// Get the current joint translation, usually in meters.
  6215.     float GetJointTranslation() const;
  6216.  
  6217.     /// Get the current joint linear speed, usually in meters per second.
  6218.     float GetJointLinearSpeed() const;
  6219.  
  6220.     /// Get the current joint angle in radians.
  6221.     float GetJointAngle() const;
  6222.  
  6223.     /// Get the current joint angular speed in radians per second.
  6224.     float GetJointAngularSpeed() const;
  6225.  
  6226.     /// Is the joint limit enabled?
  6227.     bool IsLimitEnabled() const;
  6228.  
  6229.     /// Enable/disable the joint translation limit.
  6230.     void EnableLimit(bool flag);
  6231.  
  6232.     /// Get the lower joint translation limit, usually in meters.
  6233.     float GetLowerLimit() const;
  6234.  
  6235.     /// Get the upper joint translation limit, usually in meters.
  6236.     float GetUpperLimit() const;
  6237.  
  6238.     /// Set the joint translation limits, usually in meters.
  6239.     void SetLimits(float lower, float upper);
  6240.  
  6241.     /// Is the joint motor enabled?
  6242.     bool IsMotorEnabled() const;
  6243.  
  6244.     /// Enable/disable the joint motor.
  6245.     void EnableMotor(bool flag);
  6246.  
  6247.     /// Set the motor speed, usually in radians per second.
  6248.     void SetMotorSpeed(float speed);
  6249.  
  6250.     /// Get the motor speed, usually in radians per second.
  6251.     float GetMotorSpeed() const;
  6252.  
  6253.     /// Set/Get the maximum motor force, usually in N-m.
  6254.     void SetMaxMotorTorque(float torque);
  6255.     float GetMaxMotorTorque() const;
  6256.  
  6257.     /// Get the current motor torque given the inverse time step, usually in N-m.
  6258.     float GetMotorTorque(float inv_dt) const;
  6259.  
  6260.     /// Access spring stiffness
  6261.     void SetStiffness(float stiffness);
  6262.     float GetStiffness() const;
  6263.  
  6264.     /// Access damping
  6265.     void SetDamping(float damping);
  6266.     float GetDamping() const;
  6267.  
  6268.     /// Dump to b2Log
  6269.     void Dump() override;
  6270.  
  6271.     ///
  6272.     void Draw(b2Draw* draw) const override;
  6273.  
  6274. protected:
  6275.  
  6276.     friend class b2Joint;
  6277.     b2WheelJoint(const b2WheelJointDef* def);
  6278.  
  6279.     void InitVelocityConstraints(const b2SolverData& data) override;
  6280.     void SolveVelocityConstraints(const b2SolverData& data) override;
  6281.     bool SolvePositionConstraints(const b2SolverData& data) override;
  6282.  
  6283.     b2Vec2 m_localAnchorA;
  6284.     b2Vec2 m_localAnchorB;
  6285.     b2Vec2 m_localXAxisA;
  6286.     b2Vec2 m_localYAxisA;
  6287.  
  6288.     float m_impulse;
  6289.     float m_motorImpulse;
  6290.     float m_springImpulse;
  6291.  
  6292.     float m_lowerImpulse;
  6293.     float m_upperImpulse;
  6294.     float m_translation;
  6295.     float m_lowerTranslation;
  6296.     float m_upperTranslation;
  6297.  
  6298.     float m_maxMotorTorque;
  6299.     float m_motorSpeed;
  6300.  
  6301.     bool m_enableLimit;
  6302.     bool m_enableMotor;
  6303.  
  6304.     float m_stiffness;
  6305.     float m_damping;
  6306.  
  6307.     // Solver temp
  6308.     int32 m_indexA;
  6309.     int32 m_indexB;
  6310.     b2Vec2 m_localCenterA;
  6311.     b2Vec2 m_localCenterB;
  6312.     float m_invMassA;
  6313.     float m_invMassB;
  6314.     float m_invIA;
  6315.     float m_invIB;
  6316.  
  6317.     b2Vec2 m_ax, m_ay;
  6318.     float m_sAx, m_sBx;
  6319.     float m_sAy, m_sBy;
  6320.  
  6321.     float m_mass;
  6322.     float m_motorMass;
  6323.     float m_axialMass;
  6324.     float m_springMass;
  6325.  
  6326.     float m_bias;
  6327.     float m_gamma;
  6328.  
  6329. };
  6330.  
  6331. inline float b2WheelJoint::GetMotorSpeed() const {
  6332.     return m_motorSpeed;
  6333. }
  6334.  
  6335. inline float b2WheelJoint::GetMaxMotorTorque() const {
  6336.     return m_maxMotorTorque;
  6337. }
  6338.  
  6339. #endif
  6340. // MIT License
  6341.  
  6342. // Copyright (c) 2019 Erin Catto
  6343.  
  6344. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6345. // of this software and associated documentation files (the "Software"), to deal
  6346. // in the Software without restriction, including without limitation the rights
  6347. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6348. // copies of the Software, and to permit persons to whom the Software is
  6349. // furnished to do so, subject to the following conditions:
  6350.  
  6351. // The above copyright notice and this permission notice shall be included in all
  6352. // copies or substantial portions of the Software.
  6353.  
  6354. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6355. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6356. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  6357. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6358. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6359. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  6360. // SOFTWARE.
  6361.  
  6362. #ifndef B2_WORLD_CALLBACKS_H
  6363. #define B2_WORLD_CALLBACKS_H
  6364.  
  6365. //#include "b2_api.h"
  6366. //#include "b2_settings.h"
  6367.  
  6368. struct b2Vec2;
  6369. struct b2Transform;
  6370. class b2Fixture;
  6371. class b2Body;
  6372. class b2Joint;
  6373. class b2Contact;
  6374. struct b2ContactResult;
  6375. struct b2Manifold;
  6376.  
  6377. /// Joints and fixtures are destroyed when their associated
  6378. /// body is destroyed. Implement this listener so that you
  6379. /// may nullify references to these joints and shapes.
  6380. class B2_API b2DestructionListener {
  6381. public:
  6382.     virtual ~b2DestructionListener() {}
  6383.  
  6384.     /// Called when any joint is about to be destroyed due
  6385.     /// to the destruction of one of its attached bodies.
  6386.     virtual void SayGoodbye(b2Joint* joint) = 0;
  6387.  
  6388.     /// Called when any fixture is about to be destroyed due
  6389.     /// to the destruction of its parent body.
  6390.     virtual void SayGoodbye(b2Fixture* fixture) = 0;
  6391. };
  6392.  
  6393. /// Implement this class to provide collision filtering. In other words, you can implement
  6394. /// this class if you want finer control over contact creation.
  6395. class B2_API b2ContactFilter {
  6396. public:
  6397.     virtual ~b2ContactFilter() {}
  6398.  
  6399.     /// Return true if contact calculations should be performed between these two shapes.
  6400.     /// @warning for performance reasons this is only called when the AABBs begin to overlap.
  6401.     virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);
  6402. };
  6403.  
  6404. /// Contact impulses for reporting. Impulses are used instead of forces because
  6405. /// sub-step forces may approach infinity for rigid body collisions. These
  6406. /// match up one-to-one with the contact points in b2Manifold.
  6407. struct B2_API b2ContactImpulse {
  6408.     float normalImpulses[b2_maxManifoldPoints];
  6409.     float tangentImpulses[b2_maxManifoldPoints];
  6410.     int32 count;
  6411. };
  6412.  
  6413. /// Implement this class to get contact information. You can use these results for
  6414. /// things like sounds and game logic. You can also get contact results by
  6415. /// traversing the contact lists after the time step. However, you might miss
  6416. /// some contacts because continuous physics leads to sub-stepping.
  6417. /// Additionally you may receive multiple callbacks for the same contact in a
  6418. /// single time step.
  6419. /// You should strive to make your callbacks efficient because there may be
  6420. /// many callbacks per time step.
  6421. /// @warning You cannot create/destroy Box2D entities inside these callbacks.
  6422. class B2_API b2ContactListener {
  6423. public:
  6424.     virtual ~b2ContactListener() {}
  6425.  
  6426.     /// Called when two fixtures begin to touch.
  6427.     virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
  6428.  
  6429.     /// Called when two fixtures cease to touch.
  6430.     virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
  6431.  
  6432.     /// This is called after a contact is updated. This allows you to inspect a
  6433.     /// contact before it goes to the solver. If you are careful, you can modify the
  6434.     /// contact manifold (e.g. disable contact).
  6435.     /// A copy of the old manifold is provided so that you can detect changes.
  6436.     /// Note: this is called only for awake bodies.
  6437.     /// Note: this is called even when the number of contact points is zero.
  6438.     /// Note: this is not called for sensors.
  6439.     /// Note: if you set the number of contact points to zero, you will not
  6440.     /// get an EndContact callback. However, you may get a BeginContact callback
  6441.     /// the next step.
  6442.     virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) {
  6443.         B2_NOT_USED(contact);
  6444.         B2_NOT_USED(oldManifold);
  6445.     }
  6446.  
  6447.     /// This lets you inspect a contact after the solver is finished. This is useful
  6448.     /// for inspecting impulses.
  6449.     /// Note: the contact manifold does not include time of impact impulses, which can be
  6450.     /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
  6451.     /// in a separate data structure.
  6452.     /// Note: this is only called for contacts that are touching, solid, and awake.
  6453.     virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) {
  6454.         B2_NOT_USED(contact);
  6455.         B2_NOT_USED(impulse);
  6456.     }
  6457. };
  6458.  
  6459. /// Callback class for AABB queries.
  6460. /// See b2World::Query
  6461. class B2_API b2QueryCallback {
  6462. public:
  6463.     virtual ~b2QueryCallback() {}
  6464.  
  6465.     /// Called for each fixture found in the query AABB.
  6466.     /// @return false to terminate the query.
  6467.     virtual bool ReportFixture(b2Fixture* fixture) = 0;
  6468. };
  6469.  
  6470. /// Callback class for ray casts.
  6471. /// See b2World::RayCast
  6472. class B2_API b2RayCastCallback {
  6473. public:
  6474.     virtual ~b2RayCastCallback() {}
  6475.  
  6476.     /// Called for each fixture found in the query. You control how the ray cast
  6477.     /// proceeds by returning a float:
  6478.     /// return -1: ignore this fixture and continue
  6479.     /// return 0: terminate the ray cast
  6480.     /// return fraction: clip the ray to this point
  6481.     /// return 1: don't clip the ray and continue
  6482.     /// @param fixture the fixture hit by the ray
  6483.     /// @param point the point of initial intersection
  6484.     /// @param normal the normal vector at the point of intersection
  6485.     /// @param fraction the fraction along the ray at the point of intersection
  6486.     /// @return -1 to filter, 0 to terminate, fraction to clip the ray for
  6487.     /// closest hit, 1 to continue
  6488.     virtual float ReportFixture(b2Fixture* fixture, const b2Vec2& point,
  6489.         const b2Vec2& normal, float fraction) = 0;
  6490. };
  6491.  
  6492. #endif
  6493. // MIT License
  6494.  
  6495. // Copyright (c) 2019 Erin Catto
  6496.  
  6497. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6498. // of this software and associated documentation files (the "Software"), to deal
  6499. // in the Software without restriction, including without limitation the rights
  6500. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6501. // copies of the Software, and to permit persons to whom the Software is
  6502. // furnished to do so, subject to the following conditions:
  6503.  
  6504. // The above copyright notice and this permission notice shall be included in all
  6505. // copies or substantial portions of the Software.
  6506.  
  6507. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6508. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6509. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  6510. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6511. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6512. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  6513. // SOFTWARE.
  6514.  
  6515. #ifndef B2_WORLD_H
  6516. #define B2_WORLD_H
  6517.  
  6518. //#include "b2_api.h"
  6519. //#include "b2_block_allocator.h"
  6520. //#include "b2_contact_manager.h"
  6521. //#include "b2_math.h"
  6522. //#include "b2_stack_allocator.h"
  6523. //#include "b2_time_step.h"
  6524. //#include "b2_world_callbacks.h"
  6525.  
  6526. struct b2AABB;
  6527. struct b2BodyDef;
  6528. struct b2Color;
  6529. struct b2JointDef;
  6530. class b2Body;
  6531. class b2Draw;
  6532. class b2Fixture;
  6533. class b2Joint;
  6534.  
  6535. /// The world class manages all physics entities, dynamic simulation,
  6536. /// and asynchronous queries. The world also contains efficient memory
  6537. /// management facilities.
  6538. class B2_API b2World {
  6539. public:
  6540.     /// Construct a world object.
  6541.     /// @param gravity the world gravity vector.
  6542.     b2World(const b2Vec2& gravity);
  6543.  
  6544.     /// Destruct the world. All physics entities are destroyed and all heap memory is released.
  6545.     ~b2World();
  6546.  
  6547.     /// Register a destruction listener. The listener is owned by you and must
  6548.     /// remain in scope.
  6549.     void SetDestructionListener(b2DestructionListener* listener);
  6550.  
  6551.     /// Register a contact filter to provide specific control over collision.
  6552.     /// Otherwise the default filter is used (b2_defaultFilter). The listener is
  6553.     /// owned by you and must remain in scope.
  6554.     void SetContactFilter(b2ContactFilter* filter);
  6555.  
  6556.     /// Register a contact event listener. The listener is owned by you and must
  6557.     /// remain in scope.
  6558.     void SetContactListener(b2ContactListener* listener);
  6559.  
  6560.     /// Register a routine for debug drawing. The debug draw functions are called
  6561.     /// inside with b2World::DebugDraw method. The debug draw object is owned
  6562.     /// by you and must remain in scope.
  6563.     void SetDebugDraw(b2Draw* debugDraw);
  6564.  
  6565.     /// Create a rigid body given a definition. No reference to the definition
  6566.     /// is retained.
  6567.     /// @warning This function is locked during callbacks.
  6568.     b2Body* CreateBody(const b2BodyDef* def);
  6569.  
  6570.     /// Destroy a rigid body given a definition. No reference to the definition
  6571.     /// is retained. This function is locked during callbacks.
  6572.     /// @warning This automatically deletes all associated shapes and joints.
  6573.     /// @warning This function is locked during callbacks.
  6574.     void DestroyBody(b2Body* body);
  6575.  
  6576.     /// Create a joint to constrain bodies together. No reference to the definition
  6577.     /// is retained. This may cause the connected bodies to cease colliding.
  6578.     /// @warning This function is locked during callbacks.
  6579.     b2Joint* CreateJoint(const b2JointDef* def);
  6580.  
  6581.     /// Destroy a joint. This may cause the connected bodies to begin colliding.
  6582.     /// @warning This function is locked during callbacks.
  6583.     void DestroyJoint(b2Joint* joint);
  6584.  
  6585.     /// Take a time step. This performs collision detection, integration,
  6586.     /// and constraint solution.
  6587.     /// @param timeStep the amount of time to simulate, this should not vary.
  6588.     /// @param velocityIterations for the velocity constraint solver.
  6589.     /// @param positionIterations for the position constraint solver.
  6590.     void Step(float timeStep,
  6591.         int32 velocityIterations,
  6592.         int32 positionIterations);
  6593.  
  6594.     /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically
  6595.     /// after each call to Step. The default behavior is modified by calling SetAutoClearForces.
  6596.     /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain
  6597.     /// a fixed sized time step under a variable frame-rate.
  6598.     /// When you perform sub-stepping you will disable auto clearing of forces and instead call
  6599.     /// ClearForces after all sub-steps are complete in one pass of your game loop.
  6600.     /// @see SetAutoClearForces
  6601.     void ClearForces();
  6602.  
  6603.     /// Call this to draw shapes and other debug draw data. This is intentionally non-const.
  6604.     void DebugDraw();
  6605.  
  6606.     /// Query the world for all fixtures that potentially overlap the
  6607.     /// provided AABB.
  6608.     /// @param callback a user implemented callback class.
  6609.     /// @param aabb the query box.
  6610.     void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
  6611.  
  6612.     /// Ray-cast the world for all fixtures in the path of the ray. Your callback
  6613.     /// controls whether you get the closest point, any point, or n-points.
  6614.     /// The ray-cast ignores shapes that contain the starting point.
  6615.     /// @param callback a user implemented callback class.
  6616.     /// @param point1 the ray starting point
  6617.     /// @param point2 the ray ending point
  6618.     void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;
  6619.  
  6620.     /// Get the world body list. With the returned body, use b2Body::GetNext to get
  6621.     /// the next body in the world list. A nullptr body indicates the end of the list.
  6622.     /// @return the head of the world body list.
  6623.     b2Body* GetBodyList();
  6624.     const b2Body* GetBodyList() const;
  6625.  
  6626.     /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get
  6627.     /// the next joint in the world list. A nullptr joint indicates the end of the list.
  6628.     /// @return the head of the world joint list.
  6629.     b2Joint* GetJointList();
  6630.     const b2Joint* GetJointList() const;
  6631.  
  6632.     /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get
  6633.     /// the next contact in the world list. A nullptr contact indicates the end of the list.
  6634.     /// @return the head of the world contact list.
  6635.     /// @warning contacts are created and destroyed in the middle of a time step.
  6636.     /// Use b2ContactListener to avoid missing contacts.
  6637.     b2Contact* GetContactList();
  6638.     const b2Contact* GetContactList() const;
  6639.  
  6640.     /// Enable/disable sleep.
  6641.     void SetAllowSleeping(bool flag);
  6642.     bool GetAllowSleeping() const { return m_allowSleep; }
  6643.  
  6644.     /// Enable/disable warm starting. For testing.
  6645.     void SetWarmStarting(bool flag) { m_warmStarting = flag; }
  6646.     bool GetWarmStarting() const { return m_warmStarting; }
  6647.  
  6648.     /// Enable/disable continuous physics. For testing.
  6649.     void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
  6650.     bool GetContinuousPhysics() const { return m_continuousPhysics; }
  6651.  
  6652.     /// Enable/disable single stepped continuous physics. For testing.
  6653.     void SetSubStepping(bool flag) { m_subStepping = flag; }
  6654.     bool GetSubStepping() const { return m_subStepping; }
  6655.  
  6656.     /// Get the number of broad-phase proxies.
  6657.     int32 GetProxyCount() const;
  6658.  
  6659.     /// Get the number of bodies.
  6660.     int32 GetBodyCount() const;
  6661.  
  6662.     /// Get the number of joints.
  6663.     int32 GetJointCount() const;
  6664.  
  6665.     /// Get the number of contacts (each may have 0 or more contact points).
  6666.     int32 GetContactCount() const;
  6667.  
  6668.     /// Get the height of the dynamic tree.
  6669.     int32 GetTreeHeight() const;
  6670.  
  6671.     /// Get the balance of the dynamic tree.
  6672.     int32 GetTreeBalance() const;
  6673.  
  6674.     /// Get the quality metric of the dynamic tree. The smaller the better.
  6675.     /// The minimum is 1.
  6676.     float GetTreeQuality() const;
  6677.  
  6678.     /// Change the global gravity vector.
  6679.     void SetGravity(const b2Vec2& gravity);
  6680.  
  6681.     /// Get the global gravity vector.
  6682.     b2Vec2 GetGravity() const;
  6683.  
  6684.     /// Is the world locked (in the middle of a time step).
  6685.     bool IsLocked() const;
  6686.  
  6687.     /// Set flag to control automatic clearing of forces after each time step.
  6688.     void SetAutoClearForces(bool flag);
  6689.  
  6690.     /// Get the flag that controls automatic clearing of forces after each time step.
  6691.     bool GetAutoClearForces() const;
  6692.  
  6693.     /// Shift the world origin. Useful for large worlds.
  6694.     /// The body shift formula is: position -= newOrigin
  6695.     /// @param newOrigin the new origin with respect to the old origin
  6696.     void ShiftOrigin(const b2Vec2& newOrigin);
  6697.  
  6698.     /// Get the contact manager for testing.
  6699.     const b2ContactManager& GetContactManager() const;
  6700.  
  6701.     /// Get the current profile.
  6702.     const b2Profile& GetProfile() const;
  6703.  
  6704.     /// Dump the world into the log file.
  6705.     /// @warning this should be called outside of a time step.
  6706.     void Dump();
  6707.  
  6708. private:
  6709.  
  6710.     friend class b2Body;
  6711.     friend class b2Fixture;
  6712.     friend class b2ContactManager;
  6713.     friend class b2Controller;
  6714.  
  6715.     void Solve(const b2TimeStep& step);
  6716.     void SolveTOI(const b2TimeStep& step);
  6717.  
  6718.     void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color);
  6719.  
  6720.     b2BlockAllocator m_blockAllocator;
  6721.     b2StackAllocator m_stackAllocator;
  6722.  
  6723.     b2ContactManager m_contactManager;
  6724.  
  6725.     b2Body* m_bodyList;
  6726.     b2Joint* m_jointList;
  6727.  
  6728.     int32 m_bodyCount;
  6729.     int32 m_jointCount;
  6730.  
  6731.     b2Vec2 m_gravity;
  6732.     bool m_allowSleep;
  6733.  
  6734.     b2DestructionListener* m_destructionListener;
  6735.     b2Draw* m_debugDraw;
  6736.  
  6737.     // This is used to compute the time step ratio to
  6738.     // support a variable time step.
  6739.     float m_inv_dt0;
  6740.  
  6741.     bool m_newContacts;
  6742.     bool m_locked;
  6743.     bool m_clearForces;
  6744.  
  6745.     // These are for debugging the solver.
  6746.     bool m_warmStarting;
  6747.     bool m_continuousPhysics;
  6748.     bool m_subStepping;
  6749.  
  6750.     bool m_stepComplete;
  6751.  
  6752.     b2Profile m_profile;
  6753. };
  6754.  
  6755. inline b2Body* b2World::GetBodyList() {
  6756.     return m_bodyList;
  6757. }
  6758.  
  6759. inline const b2Body* b2World::GetBodyList() const {
  6760.     return m_bodyList;
  6761. }
  6762.  
  6763. inline b2Joint* b2World::GetJointList() {
  6764.     return m_jointList;
  6765. }
  6766.  
  6767. inline const b2Joint* b2World::GetJointList() const {
  6768.     return m_jointList;
  6769. }
  6770.  
  6771. inline b2Contact* b2World::GetContactList() {
  6772.     return m_contactManager.m_contactList;
  6773. }
  6774.  
  6775. inline const b2Contact* b2World::GetContactList() const {
  6776.     return m_contactManager.m_contactList;
  6777. }
  6778.  
  6779. inline int32 b2World::GetBodyCount() const {
  6780.     return m_bodyCount;
  6781. }
  6782.  
  6783. inline int32 b2World::GetJointCount() const {
  6784.     return m_jointCount;
  6785. }
  6786.  
  6787. inline int32 b2World::GetContactCount() const {
  6788.     return m_contactManager.m_contactCount;
  6789. }
  6790.  
  6791. inline void b2World::SetGravity(const b2Vec2& gravity) {
  6792.     m_gravity = gravity;
  6793. }
  6794.  
  6795. inline b2Vec2 b2World::GetGravity() const {
  6796.     return m_gravity;
  6797. }
  6798.  
  6799. inline bool b2World::IsLocked() const {
  6800.     return m_locked;
  6801. }
  6802.  
  6803. inline void b2World::SetAutoClearForces(bool flag) {
  6804.     m_clearForces = flag;
  6805. }
  6806.  
  6807. /// Get the flag that controls automatic clearing of forces after each time step.
  6808. inline bool b2World::GetAutoClearForces() const {
  6809.     return m_clearForces;
  6810. }
  6811.  
  6812. inline const b2ContactManager& b2World::GetContactManager() const {
  6813.     return m_contactManager;
  6814. }
  6815.  
  6816. inline const b2Profile& b2World::GetProfile() const {
  6817.     return m_profile;
  6818. }
  6819.  
  6820. #endif
  6821. // MIT License
  6822.  
  6823. // Copyright (c) 2019 Erin Catto
  6824.  
  6825. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6826. // of this software and associated documentation files (the "Software"), to deal
  6827. // in the Software without restriction, including without limitation the rights
  6828. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6829. // copies of the Software, and to permit persons to whom the Software is
  6830. // furnished to do so, subject to the following conditions:
  6831.  
  6832. // The above copyright notice and this permission notice shall be included in all
  6833. // copies or substantial portions of the Software.
  6834.  
  6835. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6836. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6837. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  6838. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6839. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6840. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  6841. // SOFTWARE.
  6842.  
  6843. #ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H
  6844. #define B2_CHAIN_AND_CIRCLE_CONTACT_H
  6845.  
  6846. //#include "box2d/b2_contact.h"
  6847.  
  6848. class b2BlockAllocator;
  6849.  
  6850. class b2ChainAndCircleContact : public b2Contact {
  6851. public:
  6852.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA,
  6853.         b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  6854.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  6855.  
  6856.     b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB);
  6857.     ~b2ChainAndCircleContact() {}
  6858.  
  6859.     void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
  6860. };
  6861.  
  6862. #endif
  6863. // MIT License
  6864.  
  6865. // Copyright (c) 2019 Erin Catto
  6866.  
  6867. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6868. // of this software and associated documentation files (the "Software"), to deal
  6869. // in the Software without restriction, including without limitation the rights
  6870. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6871. // copies of the Software, and to permit persons to whom the Software is
  6872. // furnished to do so, subject to the following conditions:
  6873.  
  6874. // The above copyright notice and this permission notice shall be included in all
  6875. // copies or substantial portions of the Software.
  6876.  
  6877. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6878. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6879. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  6880. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6881. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6882. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  6883. // SOFTWARE.
  6884.  
  6885. #ifndef B2_CHAIN_AND_POLYGON_CONTACT_H
  6886. #define B2_CHAIN_AND_POLYGON_CONTACT_H
  6887.  
  6888. //#include "box2d/b2_contact.h"
  6889.  
  6890. class b2BlockAllocator;
  6891.  
  6892. class b2ChainAndPolygonContact : public b2Contact {
  6893. public:
  6894.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA,
  6895.         b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  6896.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  6897.  
  6898.     b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB);
  6899.     ~b2ChainAndPolygonContact() {}
  6900.  
  6901.     void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
  6902. };
  6903.  
  6904. #endif
  6905. // MIT License
  6906.  
  6907. // Copyright (c) 2019 Erin Catto
  6908.  
  6909. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6910. // of this software and associated documentation files (the "Software"), to deal
  6911. // in the Software without restriction, including without limitation the rights
  6912. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6913. // copies of the Software, and to permit persons to whom the Software is
  6914. // furnished to do so, subject to the following conditions:
  6915.  
  6916. // The above copyright notice and this permission notice shall be included in all
  6917. // copies or substantial portions of the Software.
  6918.  
  6919. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6920. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6921. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  6922. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6923. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6924. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  6925. // SOFTWARE.
  6926.  
  6927. #ifndef B2_CIRCLE_CONTACT_H
  6928. #define B2_CIRCLE_CONTACT_H
  6929.  
  6930. //#include "box2d/b2_contact.h"
  6931.  
  6932. class b2BlockAllocator;
  6933.  
  6934. class b2CircleContact : public b2Contact {
  6935. public:
  6936.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA,
  6937.         b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  6938.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  6939.  
  6940.     b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
  6941.     ~b2CircleContact() {}
  6942.  
  6943.     void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
  6944. };
  6945.  
  6946. #endif
  6947. // MIT License
  6948.  
  6949. // Copyright (c) 2019 Erin Catto
  6950.  
  6951. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6952. // of this software and associated documentation files (the "Software"), to deal
  6953. // in the Software without restriction, including without limitation the rights
  6954. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6955. // copies of the Software, and to permit persons to whom the Software is
  6956. // furnished to do so, subject to the following conditions:
  6957.  
  6958. // The above copyright notice and this permission notice shall be included in all
  6959. // copies or substantial portions of the Software.
  6960.  
  6961. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6962. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6963. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  6964. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6965. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6966. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  6967. // SOFTWARE.
  6968.  
  6969. #ifndef B2_CONTACT_SOLVER_H
  6970. #define B2_CONTACT_SOLVER_H
  6971.  
  6972. //#include "box2d/b2_collision.h"
  6973. //#include "box2d/b2_math.h"
  6974. //#include "box2d/b2_time_step.h"
  6975.  
  6976. class b2Contact;
  6977. class b2Body;
  6978. class b2StackAllocator;
  6979. struct b2ContactPositionConstraint;
  6980.  
  6981. struct b2VelocityConstraintPoint {
  6982.     b2Vec2 rA;
  6983.     b2Vec2 rB;
  6984.     float normalImpulse;
  6985.     float tangentImpulse;
  6986.     float normalMass;
  6987.     float tangentMass;
  6988.     float velocityBias;
  6989. };
  6990.  
  6991. struct b2ContactVelocityConstraint {
  6992.     b2VelocityConstraintPoint points[b2_maxManifoldPoints];
  6993.     b2Vec2 normal;
  6994.     b2Mat22 normalMass;
  6995.     b2Mat22 K;
  6996.     int32 indexA;
  6997.     int32 indexB;
  6998.     float invMassA, invMassB;
  6999.     float invIA, invIB;
  7000.     float friction;
  7001.     float restitution;
  7002.     float threshold;
  7003.     float tangentSpeed;
  7004.     int32 pointCount;
  7005.     int32 contactIndex;
  7006. };
  7007.  
  7008. struct b2ContactSolverDef {
  7009.     b2TimeStep step;
  7010.     b2Contact** contacts;
  7011.     int32 count;
  7012.     b2Position* positions;
  7013.     b2Velocity* velocities;
  7014.     b2StackAllocator* allocator;
  7015. };
  7016.  
  7017. class b2ContactSolver {
  7018. public:
  7019.     b2ContactSolver(b2ContactSolverDef* def);
  7020.     ~b2ContactSolver();
  7021.  
  7022.     void InitializeVelocityConstraints();
  7023.  
  7024.     void WarmStart();
  7025.     void SolveVelocityConstraints();
  7026.     void StoreImpulses();
  7027.  
  7028.     bool SolvePositionConstraints();
  7029.     bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB);
  7030.  
  7031.     b2TimeStep m_step;
  7032.     b2Position* m_positions;
  7033.     b2Velocity* m_velocities;
  7034.     b2StackAllocator* m_allocator;
  7035.     b2ContactPositionConstraint* m_positionConstraints;
  7036.     b2ContactVelocityConstraint* m_velocityConstraints;
  7037.     b2Contact** m_contacts;
  7038.     int m_count;
  7039. };
  7040.  
  7041. #endif
  7042.  
  7043. // MIT License
  7044.  
  7045. // Copyright (c) 2019 Erin Catto
  7046.  
  7047. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7048. // of this software and associated documentation files (the "Software"), to deal
  7049. // in the Software without restriction, including without limitation the rights
  7050. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7051. // copies of the Software, and to permit persons to whom the Software is
  7052. // furnished to do so, subject to the following conditions:
  7053.  
  7054. // The above copyright notice and this permission notice shall be included in all
  7055. // copies or substantial portions of the Software.
  7056.  
  7057. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7058. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7059. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7060. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7061. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7062. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7063. // SOFTWARE.
  7064.  
  7065. #ifndef B2_EDGE_AND_CIRCLE_CONTACT_H
  7066. #define B2_EDGE_AND_CIRCLE_CONTACT_H
  7067.  
  7068. //#include "box2d/b2_contact.h"
  7069.  
  7070. class b2BlockAllocator;
  7071.  
  7072. class b2EdgeAndCircleContact : public b2Contact {
  7073. public:
  7074.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA,
  7075.         b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  7076.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  7077.  
  7078.     b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
  7079.     ~b2EdgeAndCircleContact() {}
  7080.  
  7081.     void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
  7082. };
  7083.  
  7084. #endif
  7085. // MIT License
  7086.  
  7087. // Copyright (c) 2019 Erin Catto
  7088.  
  7089. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7090. // of this software and associated documentation files (the "Software"), to deal
  7091. // in the Software without restriction, including without limitation the rights
  7092. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7093. // copies of the Software, and to permit persons to whom the Software is
  7094. // furnished to do so, subject to the following conditions:
  7095.  
  7096. // The above copyright notice and this permission notice shall be included in all
  7097. // copies or substantial portions of the Software.
  7098.  
  7099. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7100. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7101. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7102. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7103. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7104. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7105. // SOFTWARE.
  7106.  
  7107. #ifndef B2_EDGE_AND_POLYGON_CONTACT_H
  7108. #define B2_EDGE_AND_POLYGON_CONTACT_H
  7109.  
  7110. //#include "box2d/b2_contact.h"
  7111.  
  7112. class b2BlockAllocator;
  7113.  
  7114. class b2EdgeAndPolygonContact : public b2Contact {
  7115. public:
  7116.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA,
  7117.         b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  7118.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  7119.  
  7120.     b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
  7121.     ~b2EdgeAndPolygonContact() {}
  7122.  
  7123.     void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
  7124. };
  7125.  
  7126. #endif
  7127. // MIT License
  7128.  
  7129. // Copyright (c) 2019 Erin Catto
  7130.  
  7131. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7132. // of this software and associated documentation files (the "Software"), to deal
  7133. // in the Software without restriction, including without limitation the rights
  7134. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7135. // copies of the Software, and to permit persons to whom the Software is
  7136. // furnished to do so, subject to the following conditions:
  7137.  
  7138. // The above copyright notice and this permission notice shall be included in all
  7139. // copies or substantial portions of the Software.
  7140.  
  7141. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7142. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7143. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7144. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7145. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7146. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7147. // SOFTWARE.
  7148.  
  7149. #ifndef B2_ISLAND_H
  7150. #define B2_ISLAND_H
  7151.  
  7152. //#include "box2d/b2_body.h"
  7153. //#include "box2d/b2_math.h"
  7154. //#include "box2d/b2_time_step.h"
  7155.  
  7156. class b2Contact;
  7157. class b2Joint;
  7158. class b2StackAllocator;
  7159. class b2ContactListener;
  7160. struct b2ContactVelocityConstraint;
  7161. struct b2Profile;
  7162.  
  7163. /// This is an internal class.
  7164. class b2Island {
  7165. public:
  7166.     b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity,
  7167.         b2StackAllocator* allocator, b2ContactListener* listener);
  7168.     ~b2Island();
  7169.  
  7170.     void Clear() {
  7171.         m_bodyCount = 0;
  7172.         m_contactCount = 0;
  7173.         m_jointCount = 0;
  7174.     }
  7175.  
  7176.     void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep);
  7177.  
  7178.     void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB);
  7179.  
  7180.     void Add(b2Body* body) {
  7181.         b2Assert(m_bodyCount < m_bodyCapacity);
  7182.         body->m_islandIndex = m_bodyCount;
  7183.         m_bodies[m_bodyCount] = body;
  7184.         ++m_bodyCount;
  7185.     }
  7186.  
  7187.     void Add(b2Contact* contact) {
  7188.         b2Assert(m_contactCount < m_contactCapacity);
  7189.         m_contacts[m_contactCount++] = contact;
  7190.     }
  7191.  
  7192.     void Add(b2Joint* joint) {
  7193.         b2Assert(m_jointCount < m_jointCapacity);
  7194.         m_joints[m_jointCount++] = joint;
  7195.     }
  7196.  
  7197.     void Report(const b2ContactVelocityConstraint* constraints);
  7198.  
  7199.     b2StackAllocator* m_allocator;
  7200.     b2ContactListener* m_listener;
  7201.  
  7202.     b2Body** m_bodies;
  7203.     b2Contact** m_contacts;
  7204.     b2Joint** m_joints;
  7205.  
  7206.     b2Position* m_positions;
  7207.     b2Velocity* m_velocities;
  7208.  
  7209.     int32 m_bodyCount;
  7210.     int32 m_jointCount;
  7211.     int32 m_contactCount;
  7212.  
  7213.     int32 m_bodyCapacity;
  7214.     int32 m_contactCapacity;
  7215.     int32 m_jointCapacity;
  7216. };
  7217.  
  7218. #endif
  7219. // MIT License
  7220.  
  7221. // Copyright (c) 2019 Erin Catto
  7222.  
  7223. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7224. // of this software and associated documentation files (the "Software"), to deal
  7225. // in the Software without restriction, including without limitation the rights
  7226. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7227. // copies of the Software, and to permit persons to whom the Software is
  7228. // furnished to do so, subject to the following conditions:
  7229.  
  7230. // The above copyright notice and this permission notice shall be included in all
  7231. // copies or substantial portions of the Software.
  7232.  
  7233. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7234. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7235. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7236. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7237. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7238. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7239. // SOFTWARE.
  7240.  
  7241. #ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H
  7242. #define B2_POLYGON_AND_CIRCLE_CONTACT_H
  7243.  
  7244. //#include "box2d/b2_contact.h"
  7245.  
  7246. class b2BlockAllocator;
  7247.  
  7248. class b2PolygonAndCircleContact : public b2Contact {
  7249. public:
  7250.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  7251.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  7252.  
  7253.     b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
  7254.     ~b2PolygonAndCircleContact() {}
  7255.  
  7256.     void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
  7257. };
  7258.  
  7259. #endif
  7260. // MIT License
  7261.  
  7262. // Copyright (c) 2019 Erin Catto
  7263.  
  7264. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7265. // of this software and associated documentation files (the "Software"), to deal
  7266. // in the Software without restriction, including without limitation the rights
  7267. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7268. // copies of the Software, and to permit persons to whom the Software is
  7269. // furnished to do so, subject to the following conditions:
  7270.  
  7271. // The above copyright notice and this permission notice shall be included in all
  7272. // copies or substantial portions of the Software.
  7273.  
  7274. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7275. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7276. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7277. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7278. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7279. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7280. // SOFTWARE.
  7281.  
  7282. #ifndef B2_POLYGON_CONTACT_H
  7283. #define B2_POLYGON_CONTACT_H
  7284.  
  7285. //#include "box2d/b2_contact.h"
  7286.  
  7287. class b2BlockAllocator;
  7288.  
  7289. class b2PolygonContact : public b2Contact {
  7290. public:
  7291.     static b2Contact* Create(b2Fixture* fixtureA, int32 indexA,
  7292.         b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
  7293.     static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
  7294.  
  7295.     b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
  7296.     ~b2PolygonContact() {}
  7297.  
  7298.     void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
  7299. };
  7300.  
  7301. #endif
  7302.  
  7303. #ifndef BOX2D_IMPL
  7304. #define BOX2D_IMPL
  7305.  
  7306. // MIT License
  7307.  
  7308. // Copyright (c) 2019 Erin Catto
  7309.  
  7310. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7311. // of this software and associated documentation files (the "Software"), to deal
  7312. // in the Software without restriction, including without limitation the rights
  7313. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7314. // copies of the Software, and to permit persons to whom the Software is
  7315. // furnished to do so, subject to the following conditions:
  7316.  
  7317. // The above copyright notice and this permission notice shall be included in all
  7318. // copies or substantial portions of the Software.
  7319.  
  7320. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7321. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7322. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7323. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7324. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7325. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7326. // SOFTWARE.
  7327.  
  7328. //#include "box2d/b2_broad_phase.h"
  7329. #include <string.h>
  7330.  
  7331. b2BroadPhase::b2BroadPhase() {
  7332.     m_proxyCount = 0;
  7333.  
  7334.     m_pairCapacity = 16;
  7335.     m_pairCount = 0;
  7336.     m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
  7337.  
  7338.     m_moveCapacity = 16;
  7339.     m_moveCount = 0;
  7340.     m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
  7341. }
  7342.  
  7343. b2BroadPhase::~b2BroadPhase() {
  7344.     b2Free(m_moveBuffer);
  7345.     b2Free(m_pairBuffer);
  7346. }
  7347.  
  7348. int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) {
  7349.     int32 proxyId = m_tree.CreateProxy(aabb, userData);
  7350.     ++m_proxyCount;
  7351.     BufferMove(proxyId);
  7352.     return proxyId;
  7353. }
  7354.  
  7355. void b2BroadPhase::DestroyProxy(int32 proxyId) {
  7356.     UnBufferMove(proxyId);
  7357.     --m_proxyCount;
  7358.     m_tree.DestroyProxy(proxyId);
  7359. }
  7360.  
  7361. void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) {
  7362.     bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement);
  7363.     if (buffer) {
  7364.         BufferMove(proxyId);
  7365.     }
  7366. }
  7367.  
  7368. void b2BroadPhase::TouchProxy(int32 proxyId) {
  7369.     BufferMove(proxyId);
  7370. }
  7371.  
  7372. void b2BroadPhase::BufferMove(int32 proxyId) {
  7373.     if (m_moveCount == m_moveCapacity) {
  7374.         int32* oldBuffer = m_moveBuffer;
  7375.         m_moveCapacity *= 2;
  7376.         m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
  7377.         memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32));
  7378.         b2Free(oldBuffer);
  7379.     }
  7380.  
  7381.     m_moveBuffer[m_moveCount] = proxyId;
  7382.     ++m_moveCount;
  7383. }
  7384.  
  7385. void b2BroadPhase::UnBufferMove(int32 proxyId) {
  7386.     for (int32 i = 0; i < m_moveCount; ++i) {
  7387.         if (m_moveBuffer[i] == proxyId) {
  7388.             m_moveBuffer[i] = e_nullProxy;
  7389.         }
  7390.     }
  7391. }
  7392.  
  7393. // This is called from b2DynamicTree::Query when we are gathering pairs.
  7394. bool b2BroadPhase::QueryCallback(int32 proxyId) {
  7395.     // A proxy cannot form a pair with itself.
  7396.     if (proxyId == m_queryProxyId) {
  7397.         return true;
  7398.     }
  7399.  
  7400.     const bool moved = m_tree.WasMoved(proxyId);
  7401.     if (moved && proxyId > m_queryProxyId) {
  7402.         // Both proxies are moving. Avoid duplicate pairs.
  7403.         return true;
  7404.     }
  7405.  
  7406.     // Grow the pair buffer as needed.
  7407.     if (m_pairCount == m_pairCapacity) {
  7408.         b2Pair* oldBuffer = m_pairBuffer;
  7409.         m_pairCapacity = m_pairCapacity + (m_pairCapacity >> 1);
  7410.         m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
  7411.         memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair));
  7412.         b2Free(oldBuffer);
  7413.     }
  7414.  
  7415.     m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId);
  7416.     m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId);
  7417.     ++m_pairCount;
  7418.  
  7419.     return true;
  7420. }
  7421. // MIT License
  7422.  
  7423. // Copyright (c) 2019 Erin Catto
  7424.  
  7425. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7426. // of this software and associated documentation files (the "Software"), to deal
  7427. // in the Software without restriction, including without limitation the rights
  7428. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7429. // copies of the Software, and to permit persons to whom the Software is
  7430. // furnished to do so, subject to the following conditions:
  7431.  
  7432. // The above copyright notice and this permission notice shall be included in all
  7433. // copies or substantial portions of the Software.
  7434.  
  7435. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7436. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7437. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7438. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7439. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7440. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7441. // SOFTWARE.
  7442.  
  7443. //#include "box2d/b2_chain_shape.h"
  7444. //#include "box2d/b2_edge_shape.h"
  7445.  
  7446. //#include "box2d/b2_block_allocator.h"
  7447.  
  7448. #include <new>
  7449. #include <string.h>
  7450.  
  7451. b2ChainShape::~b2ChainShape() {
  7452.     Clear();
  7453. }
  7454.  
  7455. void b2ChainShape::Clear() {
  7456.     b2Free(m_vertices);
  7457.     m_vertices = nullptr;
  7458.     m_count = 0;
  7459. }
  7460.  
  7461. void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) {
  7462.     b2Assert(m_vertices == nullptr && m_count == 0);
  7463.     b2Assert(count >= 3);
  7464.     if (count < 3) {
  7465.         return;
  7466.     }
  7467.  
  7468.     for (int32 i = 1; i < count; ++i) {
  7469.         b2Vec2 v1 = vertices[i - 1];
  7470.         b2Vec2 v2 = vertices[i];
  7471.         // If the code crashes here, it means your vertices are too close together.
  7472.         b2Assert(b2DistanceSquared(v1, v2) > b2_linearSlop * b2_linearSlop);
  7473.     }
  7474.  
  7475.     m_count = count + 1;
  7476.     m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2));
  7477.     memcpy(m_vertices, vertices, count * sizeof(b2Vec2));
  7478.     m_vertices[count] = m_vertices[0];
  7479.     m_prevVertex = m_vertices[m_count - 2];
  7480.     m_nextVertex = m_vertices[1];
  7481. }
  7482.  
  7483. void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count, const b2Vec2& prevVertex, const b2Vec2& nextVertex) {
  7484.     b2Assert(m_vertices == nullptr && m_count == 0);
  7485.     b2Assert(count >= 2);
  7486.     for (int32 i = 1; i < count; ++i) {
  7487.         // If the code crashes here, it means your vertices are too close together.
  7488.         b2Assert(b2DistanceSquared(vertices[i - 1], vertices[i]) > b2_linearSlop * b2_linearSlop);
  7489.     }
  7490.  
  7491.     m_count = count;
  7492.     m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2));
  7493.     memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2));
  7494.  
  7495.     m_prevVertex = prevVertex;
  7496.     m_nextVertex = nextVertex;
  7497. }
  7498.  
  7499. b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const {
  7500.     void* mem = allocator->Allocate(sizeof(b2ChainShape));
  7501.     b2ChainShape* clone = new (mem) b2ChainShape;
  7502.     clone->CreateChain(m_vertices, m_count, m_prevVertex, m_nextVertex);
  7503.     return clone;
  7504. }
  7505.  
  7506. int32 b2ChainShape::GetChildCount() const {
  7507.     // edge count = vertex count - 1
  7508.     return m_count - 1;
  7509. }
  7510.  
  7511. void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const {
  7512.     b2Assert(0 <= index && index < m_count - 1);
  7513.     edge->m_type = b2Shape::e_edge;
  7514.     edge->m_radius = m_radius;
  7515.  
  7516.     edge->m_vertex1 = m_vertices[index + 0];
  7517.     edge->m_vertex2 = m_vertices[index + 1];
  7518.     edge->m_oneSided = true;
  7519.  
  7520.     if (index > 0) {
  7521.         edge->m_vertex0 = m_vertices[index - 1];
  7522.     } else {
  7523.         edge->m_vertex0 = m_prevVertex;
  7524.     }
  7525.  
  7526.     if (index < m_count - 2) {
  7527.         edge->m_vertex3 = m_vertices[index + 2];
  7528.     } else {
  7529.         edge->m_vertex3 = m_nextVertex;
  7530.     }
  7531. }
  7532.  
  7533. bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const {
  7534.     B2_NOT_USED(xf);
  7535.     B2_NOT_USED(p);
  7536.     return false;
  7537. }
  7538.  
  7539. bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  7540.     const b2Transform& xf, int32 childIndex) const {
  7541.     b2Assert(childIndex < m_count);
  7542.  
  7543.     b2EdgeShape edgeShape;
  7544.  
  7545.     int32 i1 = childIndex;
  7546.     int32 i2 = childIndex + 1;
  7547.     if (i2 == m_count) {
  7548.         i2 = 0;
  7549.     }
  7550.  
  7551.     edgeShape.m_vertex1 = m_vertices[i1];
  7552.     edgeShape.m_vertex2 = m_vertices[i2];
  7553.  
  7554.     return edgeShape.RayCast(output, input, xf, 0);
  7555. }
  7556.  
  7557. void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const {
  7558.     b2Assert(childIndex < m_count);
  7559.  
  7560.     int32 i1 = childIndex;
  7561.     int32 i2 = childIndex + 1;
  7562.     if (i2 == m_count) {
  7563.         i2 = 0;
  7564.     }
  7565.  
  7566.     b2Vec2 v1 = b2Mul(xf, m_vertices[i1]);
  7567.     b2Vec2 v2 = b2Mul(xf, m_vertices[i2]);
  7568.  
  7569.     b2Vec2 lower = b2Min(v1, v2);
  7570.     b2Vec2 upper = b2Max(v1, v2);
  7571.  
  7572.     b2Vec2 r(m_radius, m_radius);
  7573.     aabb->lowerBound = lower - r;
  7574.     aabb->upperBound = upper + r;
  7575. }
  7576.  
  7577. void b2ChainShape::ComputeMass(b2MassData* massData, float density) const {
  7578.     B2_NOT_USED(density);
  7579.  
  7580.     massData->mass = 0.0f;
  7581.     massData->center.SetZero();
  7582.     massData->I = 0.0f;
  7583. }
  7584. // MIT License
  7585.  
  7586. // Copyright (c) 2019 Erin Catto
  7587.  
  7588. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7589. // of this software and associated documentation files (the "Software"), to deal
  7590. // in the Software without restriction, including without limitation the rights
  7591. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7592. // copies of the Software, and to permit persons to whom the Software is
  7593. // furnished to do so, subject to the following conditions:
  7594.  
  7595. // The above copyright notice and this permission notice shall be included in all
  7596. // copies or substantial portions of the Software.
  7597.  
  7598. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7599. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7600. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7601. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7602. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7603. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7604. // SOFTWARE.
  7605.  
  7606. //#include "box2d/b2_circle_shape.h"
  7607. //#include "box2d/b2_block_allocator.h"
  7608.  
  7609. #include <new>
  7610.  
  7611. b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const {
  7612.     void* mem = allocator->Allocate(sizeof(b2CircleShape));
  7613.     b2CircleShape* clone = new (mem) b2CircleShape;
  7614.     *clone = *this;
  7615.     return clone;
  7616. }
  7617.  
  7618. int32 b2CircleShape::GetChildCount() const {
  7619.     return 1;
  7620. }
  7621.  
  7622. bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const {
  7623.     b2Vec2 center = transform.p + b2Mul(transform.q, m_p);
  7624.     b2Vec2 d = p - center;
  7625.     return b2Dot(d, d) <= m_radius * m_radius;
  7626. }
  7627.  
  7628. // Collision Detection in Interactive 3D Environments by Gino van den Bergen
  7629. // From Section 3.1.2
  7630. // x = s + a * r
  7631. // norm(x) = radius
  7632. bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  7633.     const b2Transform& transform, int32 childIndex) const {
  7634.     B2_NOT_USED(childIndex);
  7635.  
  7636.     b2Vec2 position = transform.p + b2Mul(transform.q, m_p);
  7637.     b2Vec2 s = input.p1 - position;
  7638.     float b = b2Dot(s, s) - m_radius * m_radius;
  7639.  
  7640.     // Solve quadratic equation.
  7641.     b2Vec2 r = input.p2 - input.p1;
  7642.     float c = b2Dot(s, r);
  7643.     float rr = b2Dot(r, r);
  7644.     float sigma = c * c - rr * b;
  7645.  
  7646.     // Check for negative discriminant and short segment.
  7647.     if (sigma < 0.0f || rr < b2_epsilon) {
  7648.         return false;
  7649.     }
  7650.  
  7651.     // Find the point of intersection of the line with the circle.
  7652.     float a = -(c + b2Sqrt(sigma));
  7653.  
  7654.     // Is the intersection point on the segment?
  7655.     if (0.0f <= a && a <= input.maxFraction * rr) {
  7656.         a /= rr;
  7657.         output->fraction = a;
  7658.         output->normal = s + a * r;
  7659.         output->normal.Normalize();
  7660.         return true;
  7661.     }
  7662.  
  7663.     return false;
  7664. }
  7665.  
  7666. void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const {
  7667.     B2_NOT_USED(childIndex);
  7668.  
  7669.     b2Vec2 p = transform.p + b2Mul(transform.q, m_p);
  7670.     aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius);
  7671.     aabb->upperBound.Set(p.x + m_radius, p.y + m_radius);
  7672. }
  7673.  
  7674. void b2CircleShape::ComputeMass(b2MassData* massData, float density) const {
  7675.     massData->mass = density * b2_pi * m_radius * m_radius;
  7676.     massData->center = m_p;
  7677.  
  7678.     // inertia about the local origin
  7679.     massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p));
  7680. }
  7681. // MIT License
  7682.  
  7683. // Copyright (c) 2019 Erin Catto
  7684.  
  7685. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7686. // of this software and associated documentation files (the "Software"), to deal
  7687. // in the Software without restriction, including without limitation the rights
  7688. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7689. // copies of the Software, and to permit persons to whom the Software is
  7690. // furnished to do so, subject to the following conditions:
  7691.  
  7692. // The above copyright notice and this permission notice shall be included in all
  7693. // copies or substantial portions of the Software.
  7694.  
  7695. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7696. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7697. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7698. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7699. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7700. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7701. // SOFTWARE.
  7702.  
  7703. //#include "box2d/b2_collision.h"
  7704. //#include "box2d/b2_circle_shape.h"
  7705. //#include "box2d/b2_polygon_shape.h"
  7706.  
  7707. void b2CollideCircles(
  7708.     b2Manifold* manifold,
  7709.     const b2CircleShape* circleA, const b2Transform& xfA,
  7710.     const b2CircleShape* circleB, const b2Transform& xfB) {
  7711.     manifold->pointCount = 0;
  7712.  
  7713.     b2Vec2 pA = b2Mul(xfA, circleA->m_p);
  7714.     b2Vec2 pB = b2Mul(xfB, circleB->m_p);
  7715.  
  7716.     b2Vec2 d = pB - pA;
  7717.     float distSqr = b2Dot(d, d);
  7718.     float rA = circleA->m_radius, rB = circleB->m_radius;
  7719.     float radius = rA + rB;
  7720.     if (distSqr > radius * radius) {
  7721.         return;
  7722.     }
  7723.  
  7724.     manifold->type = b2Manifold::e_circles;
  7725.     manifold->localPoint = circleA->m_p;
  7726.     manifold->localNormal.SetZero();
  7727.     manifold->pointCount = 1;
  7728.  
  7729.     manifold->points[0].localPoint = circleB->m_p;
  7730.     manifold->points[0].id.key = 0;
  7731. }
  7732.  
  7733. void b2CollidePolygonAndCircle(
  7734.     b2Manifold* manifold,
  7735.     const b2PolygonShape* polygonA, const b2Transform& xfA,
  7736.     const b2CircleShape* circleB, const b2Transform& xfB) {
  7737.     manifold->pointCount = 0;
  7738.  
  7739.     // Compute circle position in the frame of the polygon.
  7740.     b2Vec2 c = b2Mul(xfB, circleB->m_p);
  7741.     b2Vec2 cLocal = b2MulT(xfA, c);
  7742.  
  7743.     // Find the min separating edge.
  7744.     int32 normalIndex = 0;
  7745.     float separation = -b2_maxFloat;
  7746.     float radius = polygonA->m_radius + circleB->m_radius;
  7747.     int32 vertexCount = polygonA->m_count;
  7748.     const b2Vec2* vertices = polygonA->m_vertices;
  7749.     const b2Vec2* normals = polygonA->m_normals;
  7750.  
  7751.     for (int32 i = 0; i < vertexCount; ++i) {
  7752.         float s = b2Dot(normals[i], cLocal - vertices[i]);
  7753.  
  7754.         if (s > radius) {
  7755.             // Early out.
  7756.             return;
  7757.         }
  7758.  
  7759.         if (s > separation) {
  7760.             separation = s;
  7761.             normalIndex = i;
  7762.         }
  7763.     }
  7764.  
  7765.     // Vertices that subtend the incident face.
  7766.     int32 vertIndex1 = normalIndex;
  7767.     int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0;
  7768.     b2Vec2 v1 = vertices[vertIndex1];
  7769.     b2Vec2 v2 = vertices[vertIndex2];
  7770.  
  7771.     // If the center is inside the polygon ...
  7772.     if (separation < b2_epsilon) {
  7773.         manifold->pointCount = 1;
  7774.         manifold->type = b2Manifold::e_faceA;
  7775.         manifold->localNormal = normals[normalIndex];
  7776.         manifold->localPoint = 0.5f * (v1 + v2);
  7777.         manifold->points[0].localPoint = circleB->m_p;
  7778.         manifold->points[0].id.key = 0;
  7779.         return;
  7780.     }
  7781.  
  7782.     // Compute barycentric coordinates
  7783.     float u1 = b2Dot(cLocal - v1, v2 - v1);
  7784.     float u2 = b2Dot(cLocal - v2, v1 - v2);
  7785.     if (u1 <= 0.0f) {
  7786.         if (b2DistanceSquared(cLocal, v1) > radius * radius) {
  7787.             return;
  7788.         }
  7789.  
  7790.         manifold->pointCount = 1;
  7791.         manifold->type = b2Manifold::e_faceA;
  7792.         manifold->localNormal = cLocal - v1;
  7793.         manifold->localNormal.Normalize();
  7794.         manifold->localPoint = v1;
  7795.         manifold->points[0].localPoint = circleB->m_p;
  7796.         manifold->points[0].id.key = 0;
  7797.     } else if (u2 <= 0.0f) {
  7798.         if (b2DistanceSquared(cLocal, v2) > radius * radius) {
  7799.             return;
  7800.         }
  7801.  
  7802.         manifold->pointCount = 1;
  7803.         manifold->type = b2Manifold::e_faceA;
  7804.         manifold->localNormal = cLocal - v2;
  7805.         manifold->localNormal.Normalize();
  7806.         manifold->localPoint = v2;
  7807.         manifold->points[0].localPoint = circleB->m_p;
  7808.         manifold->points[0].id.key = 0;
  7809.     } else {
  7810.         b2Vec2 faceCenter = 0.5f * (v1 + v2);
  7811.         float s = b2Dot(cLocal - faceCenter, normals[vertIndex1]);
  7812.         if (s > radius) {
  7813.             return;
  7814.         }
  7815.  
  7816.         manifold->pointCount = 1;
  7817.         manifold->type = b2Manifold::e_faceA;
  7818.         manifold->localNormal = normals[vertIndex1];
  7819.         manifold->localPoint = faceCenter;
  7820.         manifold->points[0].localPoint = circleB->m_p;
  7821.         manifold->points[0].id.key = 0;
  7822.     }
  7823. }
  7824. // MIT License
  7825.  
  7826. // Copyright (c) 2019 Erin Catto
  7827.  
  7828. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7829. // of this software and associated documentation files (the "Software"), to deal
  7830. // in the Software without restriction, including without limitation the rights
  7831. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7832. // copies of the Software, and to permit persons to whom the Software is
  7833. // furnished to do so, subject to the following conditions:
  7834.  
  7835. // The above copyright notice and this permission notice shall be included in all
  7836. // copies or substantial portions of the Software.
  7837.  
  7838. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7839. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7840. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  7841. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7842. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7843. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  7844. // SOFTWARE.
  7845.  
  7846. //#include "box2d/b2_collision.h"
  7847. //#include "box2d/b2_circle_shape.h"
  7848. //#include "box2d/b2_edge_shape.h"
  7849. //#include "box2d/b2_polygon_shape.h"
  7850.  
  7851.  
  7852. // Compute contact points for edge versus circle.
  7853. // This accounts for edge connectivity.
  7854. void b2CollideEdgeAndCircle(b2Manifold* manifold,
  7855.     const b2EdgeShape* edgeA, const b2Transform& xfA,
  7856.     const b2CircleShape* circleB, const b2Transform& xfB) {
  7857.     manifold->pointCount = 0;
  7858.  
  7859.     // Compute circle in frame of edge
  7860.     b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p));
  7861.  
  7862.     b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2;
  7863.     b2Vec2 e = B - A;
  7864.  
  7865.     // Normal points to the right for a CCW winding
  7866.     b2Vec2 n(e.y, -e.x);
  7867.     float offset = b2Dot(n, Q - A);
  7868.  
  7869.     bool oneSided = edgeA->m_oneSided;
  7870.     if (oneSided && offset < 0.0f) {
  7871.         return;
  7872.     }
  7873.  
  7874.     // Barycentric coordinates
  7875.     float u = b2Dot(e, B - Q);
  7876.     float v = b2Dot(e, Q - A);
  7877.  
  7878.     float radius = edgeA->m_radius + circleB->m_radius;
  7879.  
  7880.     b2ContactFeature cf;
  7881.     cf.indexB = 0;
  7882.     cf.typeB = b2ContactFeature::e_vertex;
  7883.  
  7884.     // Region A
  7885.     if (v <= 0.0f) {
  7886.         b2Vec2 P = A;
  7887.         b2Vec2 d = Q - P;
  7888.         float dd = b2Dot(d, d);
  7889.         if (dd > radius * radius) {
  7890.             return;
  7891.         }
  7892.  
  7893.         // Is there an edge connected to A?
  7894.         if (edgeA->m_oneSided) {
  7895.             b2Vec2 A1 = edgeA->m_vertex0;
  7896.             b2Vec2 B1 = A;
  7897.             b2Vec2 e1 = B1 - A1;
  7898.             float u1 = b2Dot(e1, B1 - Q);
  7899.  
  7900.             // Is the circle in Region AB of the previous edge?
  7901.             if (u1 > 0.0f) {
  7902.                 return;
  7903.             }
  7904.         }
  7905.  
  7906.         cf.indexA = 0;
  7907.         cf.typeA = b2ContactFeature::e_vertex;
  7908.         manifold->pointCount = 1;
  7909.         manifold->type = b2Manifold::e_circles;
  7910.         manifold->localNormal.SetZero();
  7911.         manifold->localPoint = P;
  7912.         manifold->points[0].id.key = 0;
  7913.         manifold->points[0].id.cf = cf;
  7914.         manifold->points[0].localPoint = circleB->m_p;
  7915.         return;
  7916.     }
  7917.  
  7918.     // Region B
  7919.     if (u <= 0.0f) {
  7920.         b2Vec2 P = B;
  7921.         b2Vec2 d = Q - P;
  7922.         float dd = b2Dot(d, d);
  7923.         if (dd > radius * radius) {
  7924.             return;
  7925.         }
  7926.  
  7927.         // Is there an edge connected to B?
  7928.         if (edgeA->m_oneSided) {
  7929.             b2Vec2 B2 = edgeA->m_vertex3;
  7930.             b2Vec2 A2 = B;
  7931.             b2Vec2 e2 = B2 - A2;
  7932.             float v2 = b2Dot(e2, Q - A2);
  7933.  
  7934.             // Is the circle in Region AB of the next edge?
  7935.             if (v2 > 0.0f) {
  7936.                 return;
  7937.             }
  7938.         }
  7939.  
  7940.         cf.indexA = 1;
  7941.         cf.typeA = b2ContactFeature::e_vertex;
  7942.         manifold->pointCount = 1;
  7943.         manifold->type = b2Manifold::e_circles;
  7944.         manifold->localNormal.SetZero();
  7945.         manifold->localPoint = P;
  7946.         manifold->points[0].id.key = 0;
  7947.         manifold->points[0].id.cf = cf;
  7948.         manifold->points[0].localPoint = circleB->m_p;
  7949.         return;
  7950.     }
  7951.  
  7952.     // Region AB
  7953.     float den = b2Dot(e, e);
  7954.     b2Assert(den > 0.0f);
  7955.     b2Vec2 P = (1.0f / den) * (u * A + v * B);
  7956.     b2Vec2 d = Q - P;
  7957.     float dd = b2Dot(d, d);
  7958.     if (dd > radius * radius) {
  7959.         return;
  7960.     }
  7961.  
  7962.     if (offset < 0.0f) {
  7963.         n.Set(-n.x, -n.y);
  7964.     }
  7965.     n.Normalize();
  7966.  
  7967.     cf.indexA = 0;
  7968.     cf.typeA = b2ContactFeature::e_face;
  7969.     manifold->pointCount = 1;
  7970.     manifold->type = b2Manifold::e_faceA;
  7971.     manifold->localNormal = n;
  7972.     manifold->localPoint = A;
  7973.     manifold->points[0].id.key = 0;
  7974.     manifold->points[0].id.cf = cf;
  7975.     manifold->points[0].localPoint = circleB->m_p;
  7976. }
  7977.  
  7978. // This structure is used to keep track of the best separating axis.
  7979. struct b2EPAxis {
  7980.     enum Type {
  7981.         e_unknown,
  7982.         e_edgeA,
  7983.         e_edgeB
  7984.     };
  7985.  
  7986.     b2Vec2 normal;
  7987.     Type type;
  7988.     int32 index;
  7989.     float separation;
  7990. };
  7991.  
  7992. // This holds polygon B expressed in frame A.
  7993. struct b2TempPolygon {
  7994.     b2Vec2 vertices[b2_maxPolygonVertices];
  7995.     b2Vec2 normals[b2_maxPolygonVertices];
  7996.     int32 count;
  7997. };
  7998.  
  7999. // Reference face used for clipping
  8000. struct b2ReferenceFace {
  8001.     int32 i1, i2;
  8002.     b2Vec2 v1, v2;
  8003.     b2Vec2 normal;
  8004.  
  8005.     b2Vec2 sideNormal1;
  8006.     float sideOffset1;
  8007.  
  8008.     b2Vec2 sideNormal2;
  8009.     float sideOffset2;
  8010. };
  8011.  
  8012. static b2EPAxis b2ComputeEdgeSeparation(const b2TempPolygon& polygonB, const b2Vec2& v1, const b2Vec2& normal1) {
  8013.     b2EPAxis axis;
  8014.     axis.type = b2EPAxis::e_edgeA;
  8015.     axis.index = -1;
  8016.     axis.separation = -FLT_MAX;
  8017.     axis.normal.SetZero();
  8018.  
  8019.     b2Vec2 axes[2] = { normal1, -normal1 };
  8020.  
  8021.     // Find axis with least overlap (min-max problem)
  8022.     for (int32 j = 0; j < 2; ++j) {
  8023.         float sj = FLT_MAX;
  8024.  
  8025.         // Find deepest polygon vertex along axis j
  8026.         for (int32 i = 0; i < polygonB.count; ++i) {
  8027.             float si = b2Dot(axes[j], polygonB.vertices[i] - v1);
  8028.             if (si < sj) {
  8029.                 sj = si;
  8030.             }
  8031.         }
  8032.  
  8033.         if (sj > axis.separation) {
  8034.             axis.index = j;
  8035.             axis.separation = sj;
  8036.             axis.normal = axes[j];
  8037.         }
  8038.     }
  8039.  
  8040.     return axis;
  8041. }
  8042.  
  8043. static b2EPAxis b2ComputePolygonSeparation(const b2TempPolygon& polygonB, const b2Vec2& v1, const b2Vec2& v2) {
  8044.     b2EPAxis axis;
  8045.     axis.type = b2EPAxis::e_unknown;
  8046.     axis.index = -1;
  8047.     axis.separation = -FLT_MAX;
  8048.     axis.normal.SetZero();
  8049.  
  8050.     for (int32 i = 0; i < polygonB.count; ++i) {
  8051.         b2Vec2 n = -polygonB.normals[i];
  8052.  
  8053.         float s1 = b2Dot(n, polygonB.vertices[i] - v1);
  8054.         float s2 = b2Dot(n, polygonB.vertices[i] - v2);
  8055.         float s = b2Min(s1, s2);
  8056.  
  8057.         if (s > axis.separation) {
  8058.             axis.type = b2EPAxis::e_edgeB;
  8059.             axis.index = i;
  8060.             axis.separation = s;
  8061.             axis.normal = n;
  8062.         }
  8063.     }
  8064.  
  8065.     return axis;
  8066. }
  8067.  
  8068. void b2CollideEdgeAndPolygon(b2Manifold* manifold,
  8069.     const b2EdgeShape* edgeA, const b2Transform& xfA,
  8070.     const b2PolygonShape* polygonB, const b2Transform& xfB) {
  8071.     manifold->pointCount = 0;
  8072.  
  8073.     b2Transform xf = b2MulT(xfA, xfB);
  8074.  
  8075.     b2Vec2 centroidB = b2Mul(xf, polygonB->m_centroid);
  8076.  
  8077.     b2Vec2 v1 = edgeA->m_vertex1;
  8078.     b2Vec2 v2 = edgeA->m_vertex2;
  8079.  
  8080.     b2Vec2 edge1 = v2 - v1;
  8081.     edge1.Normalize();
  8082.  
  8083.     // Normal points to the right for a CCW winding
  8084.     b2Vec2 normal1(edge1.y, -edge1.x);
  8085.     float offset1 = b2Dot(normal1, centroidB - v1);
  8086.  
  8087.     bool oneSided = edgeA->m_oneSided;
  8088.     if (oneSided && offset1 < 0.0f) {
  8089.         return;
  8090.     }
  8091.  
  8092.     // Get polygonB in frameA
  8093.     b2TempPolygon tempPolygonB;
  8094.     tempPolygonB.count = polygonB->m_count;
  8095.     for (int32 i = 0; i < polygonB->m_count; ++i) {
  8096.         tempPolygonB.vertices[i] = b2Mul(xf, polygonB->m_vertices[i]);
  8097.         tempPolygonB.normals[i] = b2Mul(xf.q, polygonB->m_normals[i]);
  8098.     }
  8099.  
  8100.     float radius = polygonB->m_radius + edgeA->m_radius;
  8101.  
  8102.     b2EPAxis edgeAxis = b2ComputeEdgeSeparation(tempPolygonB, v1, normal1);
  8103.     if (edgeAxis.separation > radius) {
  8104.         return;
  8105.     }
  8106.  
  8107.     b2EPAxis polygonAxis = b2ComputePolygonSeparation(tempPolygonB, v1, v2);
  8108.     if (polygonAxis.separation > radius) {
  8109.         return;
  8110.     }
  8111.  
  8112.     // Use hysteresis for jitter reduction.
  8113.     const float k_relativeTol = 0.98f;
  8114.     const float k_absoluteTol = 0.001f;
  8115.  
  8116.     b2EPAxis primaryAxis;
  8117.     if (polygonAxis.separation - radius > k_relativeTol * (edgeAxis.separation - radius) + k_absoluteTol) {
  8118.         primaryAxis = polygonAxis;
  8119.     } else {
  8120.         primaryAxis = edgeAxis;
  8121.     }
  8122.  
  8123.     if (oneSided) {
  8124.         // Smooth collision
  8125.         // See https://box2d.org/posts/2020/06/ghost-collisions/
  8126.  
  8127.         b2Vec2 edge0 = v1 - edgeA->m_vertex0;
  8128.         edge0.Normalize();
  8129.         b2Vec2 normal0(edge0.y, -edge0.x);
  8130.         bool convex1 = b2Cross(edge0, edge1) >= 0.0f;
  8131.  
  8132.         b2Vec2 edge2 = edgeA->m_vertex3 - v2;
  8133.         edge2.Normalize();
  8134.         b2Vec2 normal2(edge2.y, -edge2.x);
  8135.         bool convex2 = b2Cross(edge1, edge2) >= 0.0f;
  8136.  
  8137.         const float sinTol = 0.1f;
  8138.         bool side1 = b2Dot(primaryAxis.normal, edge1) <= 0.0f;
  8139.  
  8140.         // Check Gauss Map
  8141.         if (side1) {
  8142.             if (convex1) {
  8143.                 if (b2Cross(primaryAxis.normal, normal0) > sinTol) {
  8144.                     // Skip region
  8145.                     return;
  8146.                 }
  8147.  
  8148.                 // Admit region
  8149.             } else {
  8150.                 // Snap region
  8151.                 primaryAxis = edgeAxis;
  8152.             }
  8153.         } else {
  8154.             if (convex2) {
  8155.                 if (b2Cross(normal2, primaryAxis.normal) > sinTol) {
  8156.                     // Skip region
  8157.                     return;
  8158.                 }
  8159.  
  8160.                 // Admit region
  8161.             } else {
  8162.                 // Snap region
  8163.                 primaryAxis = edgeAxis;
  8164.             }
  8165.         }
  8166.     }
  8167.  
  8168.     b2ClipVertex clipPoints[2];
  8169.     b2ReferenceFace ref;
  8170.     if (primaryAxis.type == b2EPAxis::e_edgeA) {
  8171.         manifold->type = b2Manifold::e_faceA;
  8172.  
  8173.         // Search for the polygon normal that is most anti-parallel to the edge normal.
  8174.         int32 bestIndex = 0;
  8175.         float bestValue = b2Dot(primaryAxis.normal, tempPolygonB.normals[0]);
  8176.         for (int32 i = 1; i < tempPolygonB.count; ++i) {
  8177.             float value = b2Dot(primaryAxis.normal, tempPolygonB.normals[i]);
  8178.             if (value < bestValue) {
  8179.                 bestValue = value;
  8180.                 bestIndex = i;
  8181.             }
  8182.         }
  8183.  
  8184.         int32 i1 = bestIndex;
  8185.         int32 i2 = i1 + 1 < tempPolygonB.count ? i1 + 1 : 0;
  8186.  
  8187.         clipPoints[0].v = tempPolygonB.vertices[i1];
  8188.         clipPoints[0].id.cf.indexA = 0;
  8189.         clipPoints[0].id.cf.indexB = static_cast<uint8>(i1);
  8190.         clipPoints[0].id.cf.typeA = b2ContactFeature::e_face;
  8191.         clipPoints[0].id.cf.typeB = b2ContactFeature::e_vertex;
  8192.  
  8193.         clipPoints[1].v = tempPolygonB.vertices[i2];
  8194.         clipPoints[1].id.cf.indexA = 0;
  8195.         clipPoints[1].id.cf.indexB = static_cast<uint8>(i2);
  8196.         clipPoints[1].id.cf.typeA = b2ContactFeature::e_face;
  8197.         clipPoints[1].id.cf.typeB = b2ContactFeature::e_vertex;
  8198.  
  8199.         ref.i1 = 0;
  8200.         ref.i2 = 1;
  8201.         ref.v1 = v1;
  8202.         ref.v2 = v2;
  8203.         ref.normal = primaryAxis.normal;
  8204.         ref.sideNormal1 = -edge1;
  8205.         ref.sideNormal2 = edge1;
  8206.     } else {
  8207.         manifold->type = b2Manifold::e_faceB;
  8208.  
  8209.         clipPoints[0].v = v2;
  8210.         clipPoints[0].id.cf.indexA = 1;
  8211.         clipPoints[0].id.cf.indexB = static_cast<uint8>(primaryAxis.index);
  8212.         clipPoints[0].id.cf.typeA = b2ContactFeature::e_vertex;
  8213.         clipPoints[0].id.cf.typeB = b2ContactFeature::e_face;
  8214.  
  8215.         clipPoints[1].v = v1;
  8216.         clipPoints[1].id.cf.indexA = 0;
  8217.         clipPoints[1].id.cf.indexB = static_cast<uint8>(primaryAxis.index);
  8218.         clipPoints[1].id.cf.typeA = b2ContactFeature::e_vertex;
  8219.         clipPoints[1].id.cf.typeB = b2ContactFeature::e_face;
  8220.  
  8221.         ref.i1 = primaryAxis.index;
  8222.         ref.i2 = ref.i1 + 1 < tempPolygonB.count ? ref.i1 + 1 : 0;
  8223.         ref.v1 = tempPolygonB.vertices[ref.i1];
  8224.         ref.v2 = tempPolygonB.vertices[ref.i2];
  8225.         ref.normal = tempPolygonB.normals[ref.i1];
  8226.  
  8227.         // CCW winding
  8228.         ref.sideNormal1.Set(ref.normal.y, -ref.normal.x);
  8229.         ref.sideNormal2 = -ref.sideNormal1;
  8230.     }
  8231.  
  8232.     ref.sideOffset1 = b2Dot(ref.sideNormal1, ref.v1);
  8233.     ref.sideOffset2 = b2Dot(ref.sideNormal2, ref.v2);
  8234.  
  8235.     // Clip incident edge against reference face side planes
  8236.     b2ClipVertex clipPoints1[2];
  8237.     b2ClipVertex clipPoints2[2];
  8238.     int32 np;
  8239.  
  8240.     // Clip to side 1
  8241.     np = b2ClipSegmentToLine(clipPoints1, clipPoints, ref.sideNormal1, ref.sideOffset1, ref.i1);
  8242.  
  8243.     if (np < b2_maxManifoldPoints) {
  8244.         return;
  8245.     }
  8246.  
  8247.     // Clip to side 2
  8248.     np = b2ClipSegmentToLine(clipPoints2, clipPoints1, ref.sideNormal2, ref.sideOffset2, ref.i2);
  8249.  
  8250.     if (np < b2_maxManifoldPoints) {
  8251.         return;
  8252.     }
  8253.  
  8254.     // Now clipPoints2 contains the clipped points.
  8255.     if (primaryAxis.type == b2EPAxis::e_edgeA) {
  8256.         manifold->localNormal = ref.normal;
  8257.         manifold->localPoint = ref.v1;
  8258.     } else {
  8259.         manifold->localNormal = polygonB->m_normals[ref.i1];
  8260.         manifold->localPoint = polygonB->m_vertices[ref.i1];
  8261.     }
  8262.  
  8263.     int32 pointCount = 0;
  8264.     for (int32 i = 0; i < b2_maxManifoldPoints; ++i) {
  8265.         float separation;
  8266.  
  8267.         separation = b2Dot(ref.normal, clipPoints2[i].v - ref.v1);
  8268.  
  8269.         if (separation <= radius) {
  8270.             b2ManifoldPoint* cp = manifold->points + pointCount;
  8271.  
  8272.             if (primaryAxis.type == b2EPAxis::e_edgeA) {
  8273.                 cp->localPoint = b2MulT(xf, clipPoints2[i].v);
  8274.                 cp->id = clipPoints2[i].id;
  8275.             } else {
  8276.                 cp->localPoint = clipPoints2[i].v;
  8277.                 cp->id.cf.typeA = clipPoints2[i].id.cf.typeB;
  8278.                 cp->id.cf.typeB = clipPoints2[i].id.cf.typeA;
  8279.                 cp->id.cf.indexA = clipPoints2[i].id.cf.indexB;
  8280.                 cp->id.cf.indexB = clipPoints2[i].id.cf.indexA;
  8281.             }
  8282.  
  8283.             ++pointCount;
  8284.         }
  8285.     }
  8286.  
  8287.     manifold->pointCount = pointCount;
  8288. }
  8289. // MIT License
  8290.  
  8291. // Copyright (c) 2019 Erin Catto
  8292.  
  8293. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8294. // of this software and associated documentation files (the "Software"), to deal
  8295. // in the Software without restriction, including without limitation the rights
  8296. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8297. // copies of the Software, and to permit persons to whom the Software is
  8298. // furnished to do so, subject to the following conditions:
  8299.  
  8300. // The above copyright notice and this permission notice shall be included in all
  8301. // copies or substantial portions of the Software.
  8302.  
  8303. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8304. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8305. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8306. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8307. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8308. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8309. // SOFTWARE.
  8310.  
  8311. //#include "box2d/b2_collision.h"
  8312. //#include "box2d/b2_polygon_shape.h"
  8313.  
  8314. // Find the max separation between poly1 and poly2 using edge normals from poly1.
  8315. static float b2FindMaxSeparation(int32* edgeIndex,
  8316.     const b2PolygonShape* poly1, const b2Transform& xf1,
  8317.     const b2PolygonShape* poly2, const b2Transform& xf2) {
  8318.     int32 count1 = poly1->m_count;
  8319.     int32 count2 = poly2->m_count;
  8320.     const b2Vec2* n1s = poly1->m_normals;
  8321.     const b2Vec2* v1s = poly1->m_vertices;
  8322.     const b2Vec2* v2s = poly2->m_vertices;
  8323.     b2Transform xf = b2MulT(xf2, xf1);
  8324.  
  8325.     int32 bestIndex = 0;
  8326.     float maxSeparation = -b2_maxFloat;
  8327.     for (int32 i = 0; i < count1; ++i) {
  8328.         // Get poly1 normal in frame2.
  8329.         b2Vec2 n = b2Mul(xf.q, n1s[i]);
  8330.         b2Vec2 v1 = b2Mul(xf, v1s[i]);
  8331.  
  8332.         // Find deepest point for normal i.
  8333.         float si = b2_maxFloat;
  8334.         for (int32 j = 0; j < count2; ++j) {
  8335.             float sij = b2Dot(n, v2s[j] - v1);
  8336.             if (sij < si) {
  8337.                 si = sij;
  8338.             }
  8339.         }
  8340.  
  8341.         if (si > maxSeparation) {
  8342.             maxSeparation = si;
  8343.             bestIndex = i;
  8344.         }
  8345.     }
  8346.  
  8347.     *edgeIndex = bestIndex;
  8348.     return maxSeparation;
  8349. }
  8350.  
  8351. static void b2FindIncidentEdge(b2ClipVertex c[2],
  8352.     const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1,
  8353.     const b2PolygonShape* poly2, const b2Transform& xf2) {
  8354.     const b2Vec2* normals1 = poly1->m_normals;
  8355.  
  8356.     int32 count2 = poly2->m_count;
  8357.     const b2Vec2* vertices2 = poly2->m_vertices;
  8358.     const b2Vec2* normals2 = poly2->m_normals;
  8359.  
  8360.     b2Assert(0 <= edge1 && edge1 < poly1->m_count);
  8361.  
  8362.     // Get the normal of the reference edge in poly2's frame.
  8363.     b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1]));
  8364.  
  8365.     // Find the incident edge on poly2.
  8366.     int32 index = 0;
  8367.     float minDot = b2_maxFloat;
  8368.     for (int32 i = 0; i < count2; ++i) {
  8369.         float dot = b2Dot(normal1, normals2[i]);
  8370.         if (dot < minDot) {
  8371.             minDot = dot;
  8372.             index = i;
  8373.         }
  8374.     }
  8375.  
  8376.     // Build the clip vertices for the incident edge.
  8377.     int32 i1 = index;
  8378.     int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0;
  8379.  
  8380.     c[0].v = b2Mul(xf2, vertices2[i1]);
  8381.     c[0].id.cf.indexA = (uint8)edge1;
  8382.     c[0].id.cf.indexB = (uint8)i1;
  8383.     c[0].id.cf.typeA = b2ContactFeature::e_face;
  8384.     c[0].id.cf.typeB = b2ContactFeature::e_vertex;
  8385.  
  8386.     c[1].v = b2Mul(xf2, vertices2[i2]);
  8387.     c[1].id.cf.indexA = (uint8)edge1;
  8388.     c[1].id.cf.indexB = (uint8)i2;
  8389.     c[1].id.cf.typeA = b2ContactFeature::e_face;
  8390.     c[1].id.cf.typeB = b2ContactFeature::e_vertex;
  8391. }
  8392.  
  8393. // Find edge normal of max separation on A - return if separating axis is found
  8394. // Find edge normal of max separation on B - return if separation axis is found
  8395. // Choose reference edge as min(minA, minB)
  8396. // Find incident edge
  8397. // Clip
  8398.  
  8399. // The normal points from 1 to 2
  8400. void b2CollidePolygons(b2Manifold* manifold,
  8401.     const b2PolygonShape* polyA, const b2Transform& xfA,
  8402.     const b2PolygonShape* polyB, const b2Transform& xfB) {
  8403.     manifold->pointCount = 0;
  8404.     float totalRadius = polyA->m_radius + polyB->m_radius;
  8405.  
  8406.     int32 edgeA = 0;
  8407.     float separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB);
  8408.     if (separationA > totalRadius)
  8409.         return;
  8410.  
  8411.     int32 edgeB = 0;
  8412.     float separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA);
  8413.     if (separationB > totalRadius)
  8414.         return;
  8415.  
  8416.     const b2PolygonShape* poly1;    // reference polygon
  8417.     const b2PolygonShape* poly2;    // incident polygon
  8418.     b2Transform xf1, xf2;
  8419.     int32 edge1;                    // reference edge
  8420.     uint8 flip;
  8421.     const float k_tol = 0.1f * b2_linearSlop;
  8422.  
  8423.     if (separationB > separationA + k_tol) {
  8424.         poly1 = polyB;
  8425.         poly2 = polyA;
  8426.         xf1 = xfB;
  8427.         xf2 = xfA;
  8428.         edge1 = edgeB;
  8429.         manifold->type = b2Manifold::e_faceB;
  8430.         flip = 1;
  8431.     } else {
  8432.         poly1 = polyA;
  8433.         poly2 = polyB;
  8434.         xf1 = xfA;
  8435.         xf2 = xfB;
  8436.         edge1 = edgeA;
  8437.         manifold->type = b2Manifold::e_faceA;
  8438.         flip = 0;
  8439.     }
  8440.  
  8441.     b2ClipVertex incidentEdge[2];
  8442.     b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
  8443.  
  8444.     int32 count1 = poly1->m_count;
  8445.     const b2Vec2* vertices1 = poly1->m_vertices;
  8446.  
  8447.     int32 iv1 = edge1;
  8448.     int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0;
  8449.  
  8450.     b2Vec2 v11 = vertices1[iv1];
  8451.     b2Vec2 v12 = vertices1[iv2];
  8452.  
  8453.     b2Vec2 localTangent = v12 - v11;
  8454.     localTangent.Normalize();
  8455.  
  8456.     b2Vec2 localNormal = b2Cross(localTangent, 1.0f);
  8457.     b2Vec2 planePoint = 0.5f * (v11 + v12);
  8458.  
  8459.     b2Vec2 tangent = b2Mul(xf1.q, localTangent);
  8460.     b2Vec2 normal = b2Cross(tangent, 1.0f);
  8461.  
  8462.     v11 = b2Mul(xf1, v11);
  8463.     v12 = b2Mul(xf1, v12);
  8464.  
  8465.     // Face offset.
  8466.     float frontOffset = b2Dot(normal, v11);
  8467.  
  8468.     // Side offsets, extended by polytope skin thickness.
  8469.     float sideOffset1 = -b2Dot(tangent, v11) + totalRadius;
  8470.     float sideOffset2 = b2Dot(tangent, v12) + totalRadius;
  8471.  
  8472.     // Clip incident edge against extruded edge1 side edges.
  8473.     b2ClipVertex clipPoints1[2];
  8474.     b2ClipVertex clipPoints2[2];
  8475.     int np;
  8476.  
  8477.     // Clip to box side 1
  8478.     np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1);
  8479.  
  8480.     if (np < 2)
  8481.         return;
  8482.  
  8483.     // Clip to negative box side 1
  8484.     np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2);
  8485.  
  8486.     if (np < 2) {
  8487.         return;
  8488.     }
  8489.  
  8490.     // Now clipPoints2 contains the clipped points.
  8491.     manifold->localNormal = localNormal;
  8492.     manifold->localPoint = planePoint;
  8493.  
  8494.     int32 pointCount = 0;
  8495.     for (int32 i = 0; i < b2_maxManifoldPoints; ++i) {
  8496.         float separation = b2Dot(normal, clipPoints2[i].v) - frontOffset;
  8497.  
  8498.         if (separation <= totalRadius) {
  8499.             b2ManifoldPoint* cp = manifold->points + pointCount;
  8500.             cp->localPoint = b2MulT(xf2, clipPoints2[i].v);
  8501.             cp->id = clipPoints2[i].id;
  8502.             if (flip) {
  8503.                 // Swap features
  8504.                 b2ContactFeature cf = cp->id.cf;
  8505.                 cp->id.cf.indexA = cf.indexB;
  8506.                 cp->id.cf.indexB = cf.indexA;
  8507.                 cp->id.cf.typeA = cf.typeB;
  8508.                 cp->id.cf.typeB = cf.typeA;
  8509.             }
  8510.             ++pointCount;
  8511.         }
  8512.     }
  8513.  
  8514.     manifold->pointCount = pointCount;
  8515. }
  8516. // MIT License
  8517.  
  8518. // Copyright (c) 2019 Erin Catto
  8519.  
  8520. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8521. // of this software and associated documentation files (the "Software"), to deal
  8522. // in the Software without restriction, including without limitation the rights
  8523. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8524. // copies of the Software, and to permit persons to whom the Software is
  8525. // furnished to do so, subject to the following conditions:
  8526.  
  8527. // The above copyright notice and this permission notice shall be included in all
  8528. // copies or substantial portions of the Software.
  8529.  
  8530. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8531. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8532. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8533. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8534. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8535. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8536. // SOFTWARE.
  8537.  
  8538. //#include "box2d/b2_collision.h"
  8539. //#include "box2d/b2_distance.h"
  8540.  
  8541. void b2WorldManifold::Initialize(const b2Manifold* manifold,
  8542.     const b2Transform& xfA, float radiusA,
  8543.     const b2Transform& xfB, float radiusB) {
  8544.     if (manifold->pointCount == 0) {
  8545.         return;
  8546.     }
  8547.  
  8548.     switch (manifold->type) {
  8549.     case b2Manifold::e_circles:
  8550.     {
  8551.         normal.Set(1.0f, 0.0f);
  8552.         b2Vec2 pointA = b2Mul(xfA, manifold->localPoint);
  8553.         b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint);
  8554.         if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) {
  8555.             normal = pointB - pointA;
  8556.             normal.Normalize();
  8557.         }
  8558.  
  8559.         b2Vec2 cA = pointA + radiusA * normal;
  8560.         b2Vec2 cB = pointB - radiusB * normal;
  8561.         points[0] = 0.5f * (cA + cB);
  8562.         separations[0] = b2Dot(cB - cA, normal);
  8563.     }
  8564.     break;
  8565.  
  8566.     case b2Manifold::e_faceA:
  8567.     {
  8568.         normal = b2Mul(xfA.q, manifold->localNormal);
  8569.         b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint);
  8570.  
  8571.         for (int32 i = 0; i < manifold->pointCount; ++i) {
  8572.             b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint);
  8573.             b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal;
  8574.             b2Vec2 cB = clipPoint - radiusB * normal;
  8575.             points[i] = 0.5f * (cA + cB);
  8576.             separations[i] = b2Dot(cB - cA, normal);
  8577.         }
  8578.     }
  8579.     break;
  8580.  
  8581.     case b2Manifold::e_faceB:
  8582.     {
  8583.         normal = b2Mul(xfB.q, manifold->localNormal);
  8584.         b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint);
  8585.  
  8586.         for (int32 i = 0; i < manifold->pointCount; ++i) {
  8587.             b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint);
  8588.             b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal;
  8589.             b2Vec2 cA = clipPoint - radiusA * normal;
  8590.             points[i] = 0.5f * (cA + cB);
  8591.             separations[i] = b2Dot(cA - cB, normal);
  8592.         }
  8593.  
  8594.         // Ensure normal points from A to B.
  8595.         normal = -normal;
  8596.     }
  8597.     break;
  8598.     }
  8599. }
  8600.  
  8601. void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints],
  8602.     const b2Manifold* manifold1, const b2Manifold* manifold2) {
  8603.     for (int32 i = 0; i < b2_maxManifoldPoints; ++i) {
  8604.         state1[i] = b2_nullState;
  8605.         state2[i] = b2_nullState;
  8606.     }
  8607.  
  8608.     // Detect persists and removes.
  8609.     for (int32 i = 0; i < manifold1->pointCount; ++i) {
  8610.         b2ContactID id = manifold1->points[i].id;
  8611.  
  8612.         state1[i] = b2_removeState;
  8613.  
  8614.         for (int32 j = 0; j < manifold2->pointCount; ++j) {
  8615.             if (manifold2->points[j].id.key == id.key) {
  8616.                 state1[i] = b2_persistState;
  8617.                 break;
  8618.             }
  8619.         }
  8620.     }
  8621.  
  8622.     // Detect persists and adds.
  8623.     for (int32 i = 0; i < manifold2->pointCount; ++i) {
  8624.         b2ContactID id = manifold2->points[i].id;
  8625.  
  8626.         state2[i] = b2_addState;
  8627.  
  8628.         for (int32 j = 0; j < manifold1->pointCount; ++j) {
  8629.             if (manifold1->points[j].id.key == id.key) {
  8630.                 state2[i] = b2_persistState;
  8631.                 break;
  8632.             }
  8633.         }
  8634.     }
  8635. }
  8636.  
  8637. // From Real-time Collision Detection, p179.
  8638. bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const {
  8639.     float tmin = -b2_maxFloat;
  8640.     float tmax = b2_maxFloat;
  8641.  
  8642.     b2Vec2 p = input.p1;
  8643.     b2Vec2 d = input.p2 - input.p1;
  8644.     b2Vec2 absD = b2Abs(d);
  8645.  
  8646.     b2Vec2 normal;
  8647.  
  8648.     for (int32 i = 0; i < 2; ++i) {
  8649.         if (absD(i) < b2_epsilon) {
  8650.             // Parallel.
  8651.             if (p(i) < lowerBound(i) || upperBound(i) < p(i)) {
  8652.                 return false;
  8653.             }
  8654.         } else {
  8655.             float inv_d = 1.0f / d(i);
  8656.             float t1 = (lowerBound(i) - p(i)) * inv_d;
  8657.             float t2 = (upperBound(i) - p(i)) * inv_d;
  8658.  
  8659.             // Sign of the normal vector.
  8660.             float s = -1.0f;
  8661.  
  8662.             if (t1 > t2) {
  8663.                 b2Swap(t1, t2);
  8664.                 s = 1.0f;
  8665.             }
  8666.  
  8667.             // Push the min up
  8668.             if (t1 > tmin) {
  8669.                 normal.SetZero();
  8670.                 normal(i) = s;
  8671.                 tmin = t1;
  8672.             }
  8673.  
  8674.             // Pull the max down
  8675.             tmax = b2Min(tmax, t2);
  8676.  
  8677.             if (tmin > tmax) {
  8678.                 return false;
  8679.             }
  8680.         }
  8681.     }
  8682.  
  8683.     // Does the ray start inside the box?
  8684.     // Does the ray intersect beyond the max fraction?
  8685.     if (tmin < 0.0f || input.maxFraction < tmin) {
  8686.         return false;
  8687.     }
  8688.  
  8689.     // Intersection.
  8690.     output->fraction = tmin;
  8691.     output->normal = normal;
  8692.     return true;
  8693. }
  8694.  
  8695. // Sutherland-Hodgman clipping.
  8696. int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2],
  8697.     const b2Vec2& normal, float offset, int32 vertexIndexA) {
  8698.     // Start with no output points
  8699.     int32 count = 0;
  8700.  
  8701.     // Calculate the distance of end points to the line
  8702.     float distance0 = b2Dot(normal, vIn[0].v) - offset;
  8703.     float distance1 = b2Dot(normal, vIn[1].v) - offset;
  8704.  
  8705.     // If the points are behind the plane
  8706.     if (distance0 <= 0.0f) vOut[count++] = vIn[0];
  8707.     if (distance1 <= 0.0f) vOut[count++] = vIn[1];
  8708.  
  8709.     // If the points are on different sides of the plane
  8710.     if (distance0 * distance1 < 0.0f) {
  8711.         // Find intersection point of edge and plane
  8712.         float interp = distance0 / (distance0 - distance1);
  8713.         vOut[count].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v);
  8714.  
  8715.         // VertexA is hitting edgeB.
  8716.         vOut[count].id.cf.indexA = static_cast<uint8>(vertexIndexA);
  8717.         vOut[count].id.cf.indexB = vIn[0].id.cf.indexB;
  8718.         vOut[count].id.cf.typeA = b2ContactFeature::e_vertex;
  8719.         vOut[count].id.cf.typeB = b2ContactFeature::e_face;
  8720.         ++count;
  8721.  
  8722.         b2Assert(count == 2);
  8723.     }
  8724.  
  8725.     return count;
  8726. }
  8727.  
  8728. bool b2TestOverlap(const b2Shape* shapeA, int32 indexA,
  8729.     const b2Shape* shapeB, int32 indexB,
  8730.     const b2Transform& xfA, const b2Transform& xfB) {
  8731.     b2DistanceInput input;
  8732.     input.proxyA.Set(shapeA, indexA);
  8733.     input.proxyB.Set(shapeB, indexB);
  8734.     input.transformA = xfA;
  8735.     input.transformB = xfB;
  8736.     input.useRadii = true;
  8737.  
  8738.     b2SimplexCache cache;
  8739.     cache.count = 0;
  8740.  
  8741.     b2DistanceOutput output;
  8742.  
  8743.     b2Distance(&output, &cache, &input);
  8744.  
  8745.     return output.distance < 10.0f * b2_epsilon;
  8746. }
  8747. // MIT License
  8748.  
  8749. // Copyright (c) 2019 Erin Catto
  8750.  
  8751. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8752. // of this software and associated documentation files (the "Software"), to deal
  8753. // in the Software without restriction, including without limitation the rights
  8754. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8755. // copies of the Software, and to permit persons to whom the Software is
  8756. // furnished to do so, subject to the following conditions:
  8757.  
  8758. // The above copyright notice and this permission notice shall be included in all
  8759. // copies or substantial portions of the Software.
  8760.  
  8761. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8762. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8763. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8764. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8765. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8766. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8767. // SOFTWARE.
  8768.  
  8769. //#include "box2d/b2_circle_shape.h"
  8770. //#include "box2d/b2_distance.h"
  8771. //#include "box2d/b2_edge_shape.h"
  8772. //#include "box2d/b2_chain_shape.h"
  8773. //#include "box2d/b2_polygon_shape.h"
  8774.  
  8775. // GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates.
  8776. B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
  8777.  
  8778. void b2DistanceProxy::Set(const b2Shape* shape, int32 index) {
  8779.     switch (shape->GetType()) {
  8780.     case b2Shape::e_circle:
  8781.     {
  8782.         const b2CircleShape* circle = static_cast<const b2CircleShape*>(shape);
  8783.         m_vertices = &circle->m_p;
  8784.         m_count = 1;
  8785.         m_radius = circle->m_radius;
  8786.     }
  8787.     break;
  8788.  
  8789.     case b2Shape::e_polygon:
  8790.     {
  8791.         const b2PolygonShape* polygon = static_cast<const b2PolygonShape*>(shape);
  8792.         m_vertices = polygon->m_vertices;
  8793.         m_count = polygon->m_count;
  8794.         m_radius = polygon->m_radius;
  8795.     }
  8796.     break;
  8797.  
  8798.     case b2Shape::e_chain:
  8799.     {
  8800.         const b2ChainShape* chain = static_cast<const b2ChainShape*>(shape);
  8801.         b2Assert(0 <= index && index < chain->m_count);
  8802.  
  8803.         m_buffer[0] = chain->m_vertices[index];
  8804.         if (index + 1 < chain->m_count) {
  8805.             m_buffer[1] = chain->m_vertices[index + 1];
  8806.         } else {
  8807.             m_buffer[1] = chain->m_vertices[0];
  8808.         }
  8809.  
  8810.         m_vertices = m_buffer;
  8811.         m_count = 2;
  8812.         m_radius = chain->m_radius;
  8813.     }
  8814.     break;
  8815.  
  8816.     case b2Shape::e_edge:
  8817.     {
  8818.         const b2EdgeShape* edge = static_cast<const b2EdgeShape*>(shape);
  8819.         m_vertices = &edge->m_vertex1;
  8820.         m_count = 2;
  8821.         m_radius = edge->m_radius;
  8822.     }
  8823.     break;
  8824.  
  8825.     default:
  8826.         b2Assert(false);
  8827.     }
  8828. }
  8829.  
  8830. void b2DistanceProxy::Set(const b2Vec2* vertices, int32 count, float radius) {
  8831.     m_vertices = vertices;
  8832.     m_count = count;
  8833.     m_radius = radius;
  8834. }
  8835.  
  8836. struct b2SimplexVertex {
  8837.     b2Vec2 wA;      // support point in proxyA
  8838.     b2Vec2 wB;      // support point in proxyB
  8839.     b2Vec2 w;       // wB - wA
  8840.     float a;        // barycentric coordinate for closest point
  8841.     int32 indexA;   // wA index
  8842.     int32 indexB;   // wB index
  8843. };
  8844.  
  8845. struct b2Simplex {
  8846.     void ReadCache(const b2SimplexCache* cache,
  8847.         const b2DistanceProxy* proxyA, const b2Transform& transformA,
  8848.         const b2DistanceProxy* proxyB, const b2Transform& transformB) {
  8849.         b2Assert(cache->count <= 3);
  8850.  
  8851.         // Copy data from cache.
  8852.         m_count = cache->count;
  8853.         b2SimplexVertex* vertices = &m_v1;
  8854.         for (int32 i = 0; i < m_count; ++i) {
  8855.             b2SimplexVertex* v = vertices + i;
  8856.             v->indexA = cache->indexA[i];
  8857.             v->indexB = cache->indexB[i];
  8858.             b2Vec2 wALocal = proxyA->GetVertex(v->indexA);
  8859.             b2Vec2 wBLocal = proxyB->GetVertex(v->indexB);
  8860.             v->wA = b2Mul(transformA, wALocal);
  8861.             v->wB = b2Mul(transformB, wBLocal);
  8862.             v->w = v->wB - v->wA;
  8863.             v->a = 0.0f;
  8864.         }
  8865.  
  8866.         // Compute the new simplex metric, if it is substantially different than
  8867.         // old metric then flush the simplex.
  8868.         if (m_count > 1) {
  8869.             float metric1 = cache->metric;
  8870.             float metric2 = GetMetric();
  8871.             if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) {
  8872.                 // Reset the simplex.
  8873.                 m_count = 0;
  8874.             }
  8875.         }
  8876.  
  8877.         // If the cache is empty or invalid ...
  8878.         if (m_count == 0) {
  8879.             b2SimplexVertex* v = vertices + 0;
  8880.             v->indexA = 0;
  8881.             v->indexB = 0;
  8882.             b2Vec2 wALocal = proxyA->GetVertex(0);
  8883.             b2Vec2 wBLocal = proxyB->GetVertex(0);
  8884.             v->wA = b2Mul(transformA, wALocal);
  8885.             v->wB = b2Mul(transformB, wBLocal);
  8886.             v->w = v->wB - v->wA;
  8887.             v->a = 1.0f;
  8888.             m_count = 1;
  8889.         }
  8890.     }
  8891.  
  8892.     void WriteCache(b2SimplexCache* cache) const {
  8893.         cache->metric = GetMetric();
  8894.         cache->count = uint16(m_count);
  8895.         const b2SimplexVertex* vertices = &m_v1;
  8896.         for (int32 i = 0; i < m_count; ++i) {
  8897.             cache->indexA[i] = uint8(vertices[i].indexA);
  8898.             cache->indexB[i] = uint8(vertices[i].indexB);
  8899.         }
  8900.     }
  8901.  
  8902.     b2Vec2 GetSearchDirection() const {
  8903.         switch (m_count) {
  8904.         case 1:
  8905.             return -m_v1.w;
  8906.  
  8907.         case 2:
  8908.         {
  8909.             b2Vec2 e12 = m_v2.w - m_v1.w;
  8910.             float sgn = b2Cross(e12, -m_v1.w);
  8911.             if (sgn > 0.0f) {
  8912.                 // Origin is left of e12.
  8913.                 return b2Cross(1.0f, e12);
  8914.             } else {
  8915.                 // Origin is right of e12.
  8916.                 return b2Cross(e12, 1.0f);
  8917.             }
  8918.         }
  8919.  
  8920.         default:
  8921.             b2Assert(false);
  8922.             return b2Vec2_zero;
  8923.         }
  8924.     }
  8925.  
  8926.     b2Vec2 GetClosestPoint() const {
  8927.         switch (m_count) {
  8928.         case 0:
  8929.             b2Assert(false);
  8930.             return b2Vec2_zero;
  8931.  
  8932.         case 1:
  8933.             return m_v1.w;
  8934.  
  8935.         case 2:
  8936.             return m_v1.a * m_v1.w + m_v2.a * m_v2.w;
  8937.  
  8938.         case 3:
  8939.             return b2Vec2_zero;
  8940.  
  8941.         default:
  8942.             b2Assert(false);
  8943.             return b2Vec2_zero;
  8944.         }
  8945.     }
  8946.  
  8947.     void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const {
  8948.         switch (m_count) {
  8949.         case 0:
  8950.             b2Assert(false);
  8951.             break;
  8952.  
  8953.         case 1:
  8954.             *pA = m_v1.wA;
  8955.             *pB = m_v1.wB;
  8956.             break;
  8957.  
  8958.         case 2:
  8959.             *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA;
  8960.             *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB;
  8961.             break;
  8962.  
  8963.         case 3:
  8964.             *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA;
  8965.             *pB = *pA;
  8966.             break;
  8967.  
  8968.         default:
  8969.             b2Assert(false);
  8970.             break;
  8971.         }
  8972.     }
  8973.  
  8974.     float GetMetric() const {
  8975.         switch (m_count) {
  8976.         case 0:
  8977.             b2Assert(false);
  8978.             return 0.0f;
  8979.  
  8980.         case 1:
  8981.             return 0.0f;
  8982.  
  8983.         case 2:
  8984.             return b2Distance(m_v1.w, m_v2.w);
  8985.  
  8986.         case 3:
  8987.             return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w);
  8988.  
  8989.         default:
  8990.             b2Assert(false);
  8991.             return 0.0f;
  8992.         }
  8993.     }
  8994.  
  8995.     void Solve2();
  8996.     void Solve3();
  8997.  
  8998.     b2SimplexVertex m_v1, m_v2, m_v3;
  8999.     int32 m_count;
  9000. };
  9001.  
  9002.  
  9003. // Solve a line segment using barycentric coordinates.
  9004. //
  9005. // p = a1 * w1 + a2 * w2
  9006. // a1 + a2 = 1
  9007. //
  9008. // The vector from the origin to the closest point on the line is
  9009. // perpendicular to the line.
  9010. // e12 = w2 - w1
  9011. // dot(p, e) = 0
  9012. // a1 * dot(w1, e) + a2 * dot(w2, e) = 0
  9013. //
  9014. // 2-by-2 linear system
  9015. // [1      1     ][a1] = [1]
  9016. // [w1.e12 w2.e12][a2] = [0]
  9017. //
  9018. // Define
  9019. // d12_1 =  dot(w2, e12)
  9020. // d12_2 = -dot(w1, e12)
  9021. // d12 = d12_1 + d12_2
  9022. //
  9023. // Solution
  9024. // a1 = d12_1 / d12
  9025. // a2 = d12_2 / d12
  9026. void b2Simplex::Solve2() {
  9027.     b2Vec2 w1 = m_v1.w;
  9028.     b2Vec2 w2 = m_v2.w;
  9029.     b2Vec2 e12 = w2 - w1;
  9030.  
  9031.     // w1 region
  9032.     float d12_2 = -b2Dot(w1, e12);
  9033.     if (d12_2 <= 0.0f) {
  9034.         // a2 <= 0, so we clamp it to 0
  9035.         m_v1.a = 1.0f;
  9036.         m_count = 1;
  9037.         return;
  9038.     }
  9039.  
  9040.     // w2 region
  9041.     float d12_1 = b2Dot(w2, e12);
  9042.     if (d12_1 <= 0.0f) {
  9043.         // a1 <= 0, so we clamp it to 0
  9044.         m_v2.a = 1.0f;
  9045.         m_count = 1;
  9046.         m_v1 = m_v2;
  9047.         return;
  9048.     }
  9049.  
  9050.     // Must be in e12 region.
  9051.     float inv_d12 = 1.0f / (d12_1 + d12_2);
  9052.     m_v1.a = d12_1 * inv_d12;
  9053.     m_v2.a = d12_2 * inv_d12;
  9054.     m_count = 2;
  9055. }
  9056.  
  9057. // Possible regions:
  9058. // - points[2]
  9059. // - edge points[0]-points[2]
  9060. // - edge points[1]-points[2]
  9061. // - inside the triangle
  9062. void b2Simplex::Solve3() {
  9063.     b2Vec2 w1 = m_v1.w;
  9064.     b2Vec2 w2 = m_v2.w;
  9065.     b2Vec2 w3 = m_v3.w;
  9066.  
  9067.     // Edge12
  9068.     // [1      1     ][a1] = [1]
  9069.     // [w1.e12 w2.e12][a2] = [0]
  9070.     // a3 = 0
  9071.     b2Vec2 e12 = w2 - w1;
  9072.     float w1e12 = b2Dot(w1, e12);
  9073.     float w2e12 = b2Dot(w2, e12);
  9074.     float d12_1 = w2e12;
  9075.     float d12_2 = -w1e12;
  9076.  
  9077.     // Edge13
  9078.     // [1      1     ][a1] = [1]
  9079.     // [w1.e13 w3.e13][a3] = [0]
  9080.     // a2 = 0
  9081.     b2Vec2 e13 = w3 - w1;
  9082.     float w1e13 = b2Dot(w1, e13);
  9083.     float w3e13 = b2Dot(w3, e13);
  9084.     float d13_1 = w3e13;
  9085.     float d13_2 = -w1e13;
  9086.  
  9087.     // Edge23
  9088.     // [1      1     ][a2] = [1]
  9089.     // [w2.e23 w3.e23][a3] = [0]
  9090.     // a1 = 0
  9091.     b2Vec2 e23 = w3 - w2;
  9092.     float w2e23 = b2Dot(w2, e23);
  9093.     float w3e23 = b2Dot(w3, e23);
  9094.     float d23_1 = w3e23;
  9095.     float d23_2 = -w2e23;
  9096.  
  9097.     // Triangle123
  9098.     float n123 = b2Cross(e12, e13);
  9099.  
  9100.     float d123_1 = n123 * b2Cross(w2, w3);
  9101.     float d123_2 = n123 * b2Cross(w3, w1);
  9102.     float d123_3 = n123 * b2Cross(w1, w2);
  9103.  
  9104.     // w1 region
  9105.     if (d12_2 <= 0.0f && d13_2 <= 0.0f) {
  9106.         m_v1.a = 1.0f;
  9107.         m_count = 1;
  9108.         return;
  9109.     }
  9110.  
  9111.     // e12
  9112.     if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) {
  9113.         float inv_d12 = 1.0f / (d12_1 + d12_2);
  9114.         m_v1.a = d12_1 * inv_d12;
  9115.         m_v2.a = d12_2 * inv_d12;
  9116.         m_count = 2;
  9117.         return;
  9118.     }
  9119.  
  9120.     // e13
  9121.     if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) {
  9122.         float inv_d13 = 1.0f / (d13_1 + d13_2);
  9123.         m_v1.a = d13_1 * inv_d13;
  9124.         m_v3.a = d13_2 * inv_d13;
  9125.         m_count = 2;
  9126.         m_v2 = m_v3;
  9127.         return;
  9128.     }
  9129.  
  9130.     // w2 region
  9131.     if (d12_1 <= 0.0f && d23_2 <= 0.0f) {
  9132.         m_v2.a = 1.0f;
  9133.         m_count = 1;
  9134.         m_v1 = m_v2;
  9135.         return;
  9136.     }
  9137.  
  9138.     // w3 region
  9139.     if (d13_1 <= 0.0f && d23_1 <= 0.0f) {
  9140.         m_v3.a = 1.0f;
  9141.         m_count = 1;
  9142.         m_v1 = m_v3;
  9143.         return;
  9144.     }
  9145.  
  9146.     // e23
  9147.     if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) {
  9148.         float inv_d23 = 1.0f / (d23_1 + d23_2);
  9149.         m_v2.a = d23_1 * inv_d23;
  9150.         m_v3.a = d23_2 * inv_d23;
  9151.         m_count = 2;
  9152.         m_v1 = m_v3;
  9153.         return;
  9154.     }
  9155.  
  9156.     // Must be in triangle123
  9157.     float inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3);
  9158.     m_v1.a = d123_1 * inv_d123;
  9159.     m_v2.a = d123_2 * inv_d123;
  9160.     m_v3.a = d123_3 * inv_d123;
  9161.     m_count = 3;
  9162. }
  9163.  
  9164. void b2Distance(b2DistanceOutput* output,
  9165.     b2SimplexCache* cache,
  9166.     const b2DistanceInput* input) {
  9167.     ++b2_gjkCalls;
  9168.  
  9169.     const b2DistanceProxy* proxyA = &input->proxyA;
  9170.     const b2DistanceProxy* proxyB = &input->proxyB;
  9171.  
  9172.     b2Transform transformA = input->transformA;
  9173.     b2Transform transformB = input->transformB;
  9174.  
  9175.     // Initialize the simplex.
  9176.     b2Simplex simplex;
  9177.     simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB);
  9178.  
  9179.     // Get simplex vertices as an array.
  9180.     b2SimplexVertex* vertices = &simplex.m_v1;
  9181.     const int32 k_maxIters = 20;
  9182.  
  9183.     // These store the vertices of the last simplex so that we
  9184.     // can check for duplicates and prevent cycling.
  9185.     int32 saveA[3], saveB[3];
  9186.     int32 saveCount = 0;
  9187.  
  9188.     // Main iteration loop.
  9189.     int32 iter = 0;
  9190.     while (iter < k_maxIters) {
  9191.         // Copy simplex so we can identify duplicates.
  9192.         saveCount = simplex.m_count;
  9193.         for (int32 i = 0; i < saveCount; ++i) {
  9194.             saveA[i] = vertices[i].indexA;
  9195.             saveB[i] = vertices[i].indexB;
  9196.         }
  9197.  
  9198.         switch (simplex.m_count) {
  9199.         case 1:
  9200.             break;
  9201.  
  9202.         case 2:
  9203.             simplex.Solve2();
  9204.             break;
  9205.  
  9206.         case 3:
  9207.             simplex.Solve3();
  9208.             break;
  9209.  
  9210.         default:
  9211.             b2Assert(false);
  9212.         }
  9213.  
  9214.         // If we have 3 points, then the origin is in the corresponding triangle.
  9215.         if (simplex.m_count == 3) {
  9216.             break;
  9217.         }
  9218.  
  9219.         // Get search direction.
  9220.         b2Vec2 d = simplex.GetSearchDirection();
  9221.  
  9222.         // Ensure the search direction is numerically fit.
  9223.         if (d.LengthSquared() < b2_epsilon * b2_epsilon) {
  9224.             // The origin is probably contained by a line segment
  9225.             // or triangle. Thus the shapes are overlapped.
  9226.  
  9227.             // We can't return zero here even though there may be overlap.
  9228.             // In case the simplex is a point, segment, or triangle it is difficult
  9229.             // to determine if the origin is contained in the CSO or very close to it.
  9230.             break;
  9231.         }
  9232.  
  9233.         // Compute a tentative new simplex vertex using support points.
  9234.         b2SimplexVertex* vertex = vertices + simplex.m_count;
  9235.         vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d));
  9236.         vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA));
  9237.         vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d));
  9238.         vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB));
  9239.         vertex->w = vertex->wB - vertex->wA;
  9240.  
  9241.         // Iteration count is equated to the number of support point calls.
  9242.         ++iter;
  9243.         ++b2_gjkIters;
  9244.  
  9245.         // Check for duplicate support points. This is the main termination criteria.
  9246.         bool duplicate = false;
  9247.         for (int32 i = 0; i < saveCount; ++i) {
  9248.             if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) {
  9249.                 duplicate = true;
  9250.                 break;
  9251.             }
  9252.         }
  9253.  
  9254.         // If we found a duplicate support point we must exit to avoid cycling.
  9255.         if (duplicate) {
  9256.             break;
  9257.         }
  9258.  
  9259.         // New vertex is ok and needed.
  9260.         ++simplex.m_count;
  9261.     }
  9262.  
  9263.     b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter);
  9264.  
  9265.     // Prepare output.
  9266.     simplex.GetWitnessPoints(&output->pointA, &output->pointB);
  9267.     output->distance = b2Distance(output->pointA, output->pointB);
  9268.     output->iterations = iter;
  9269.  
  9270.     // Cache the simplex.
  9271.     simplex.WriteCache(cache);
  9272.  
  9273.     // Apply radii if requested.
  9274.     if (input->useRadii) {
  9275.         float rA = proxyA->m_radius;
  9276.         float rB = proxyB->m_radius;
  9277.  
  9278.         if (output->distance > rA + rB && output->distance > b2_epsilon) {
  9279.             // Shapes are still no overlapped.
  9280.             // Move the witness points to the outer surface.
  9281.             output->distance -= rA + rB;
  9282.             b2Vec2 normal = output->pointB - output->pointA;
  9283.             normal.Normalize();
  9284.             output->pointA += rA * normal;
  9285.             output->pointB -= rB * normal;
  9286.         } else {
  9287.             // Shapes are overlapped when radii are considered.
  9288.             // Move the witness points to the middle.
  9289.             b2Vec2 p = 0.5f * (output->pointA + output->pointB);
  9290.             output->pointA = p;
  9291.             output->pointB = p;
  9292.             output->distance = 0.0f;
  9293.         }
  9294.     }
  9295. }
  9296.  
  9297. // GJK-raycast
  9298. // Algorithm by Gino van den Bergen.
  9299. // "Smooth Mesh Contacts with GJK" in Game Physics Pearls. 2010
  9300. bool b2ShapeCast(b2ShapeCastOutput* output, const b2ShapeCastInput* input) {
  9301.     output->iterations = 0;
  9302.     output->lambda = 1.0f;
  9303.     output->normal.SetZero();
  9304.     output->point.SetZero();
  9305.  
  9306.     const b2DistanceProxy* proxyA = &input->proxyA;
  9307.     const b2DistanceProxy* proxyB = &input->proxyB;
  9308.  
  9309.     float radiusA = b2Max(proxyA->m_radius, b2_polygonRadius);
  9310.     float radiusB = b2Max(proxyB->m_radius, b2_polygonRadius);
  9311.     float radius = radiusA + radiusB;
  9312.  
  9313.     b2Transform xfA = input->transformA;
  9314.     b2Transform xfB = input->transformB;
  9315.  
  9316.     b2Vec2 r = input->translationB;
  9317.     b2Vec2 n(0.0f, 0.0f);
  9318.     float lambda = 0.0f;
  9319.  
  9320.     // Initial simplex
  9321.     b2Simplex simplex;
  9322.     simplex.m_count = 0;
  9323.  
  9324.     // Get simplex vertices as an array.
  9325.     b2SimplexVertex* vertices = &simplex.m_v1;
  9326.  
  9327.     // Get support point in -r direction
  9328.     int32 indexA = proxyA->GetSupport(b2MulT(xfA.q, -r));
  9329.     b2Vec2 wA = b2Mul(xfA, proxyA->GetVertex(indexA));
  9330.     int32 indexB = proxyB->GetSupport(b2MulT(xfB.q, r));
  9331.     b2Vec2 wB = b2Mul(xfB, proxyB->GetVertex(indexB));
  9332.     b2Vec2 v = wA - wB;
  9333.  
  9334.     // Sigma is the target distance between polygons
  9335.     float sigma = b2Max(b2_polygonRadius, radius - b2_polygonRadius);
  9336.     const float tolerance = 0.5f * b2_linearSlop;
  9337.  
  9338.     // Main iteration loop.
  9339.     const int32 k_maxIters = 20;
  9340.     int32 iter = 0;
  9341.     while (iter < k_maxIters && v.Length() - sigma > tolerance) {
  9342.         b2Assert(simplex.m_count < 3);
  9343.  
  9344.         output->iterations += 1;
  9345.  
  9346.         // Support in direction -v (A - B)
  9347.         indexA = proxyA->GetSupport(b2MulT(xfA.q, -v));
  9348.         wA = b2Mul(xfA, proxyA->GetVertex(indexA));
  9349.         indexB = proxyB->GetSupport(b2MulT(xfB.q, v));
  9350.         wB = b2Mul(xfB, proxyB->GetVertex(indexB));
  9351.         b2Vec2 p = wA - wB;
  9352.  
  9353.         // -v is a normal at p
  9354.         v.Normalize();
  9355.  
  9356.         // Intersect ray with plane
  9357.         float vp = b2Dot(v, p);
  9358.         float vr = b2Dot(v, r);
  9359.         if (vp - sigma > lambda * vr) {
  9360.             if (vr <= 0.0f) {
  9361.                 return false;
  9362.             }
  9363.  
  9364.             lambda = (vp - sigma) / vr;
  9365.             if (lambda > 1.0f) {
  9366.                 return false;
  9367.             }
  9368.  
  9369.             n = -v;
  9370.             simplex.m_count = 0;
  9371.         }
  9372.  
  9373.         // Reverse simplex since it works with B - A.
  9374.         // Shift by lambda * r because we want the closest point to the current clip point.
  9375.         // Note that the support point p is not shifted because we want the plane equation
  9376.         // to be formed in unshifted space.
  9377.         b2SimplexVertex* vertex = vertices + simplex.m_count;
  9378.         vertex->indexA = indexB;
  9379.         vertex->wA = wB + lambda * r;
  9380.         vertex->indexB = indexA;
  9381.         vertex->wB = wA;
  9382.         vertex->w = vertex->wB - vertex->wA;
  9383.         vertex->a = 1.0f;
  9384.         simplex.m_count += 1;
  9385.  
  9386.         switch (simplex.m_count) {
  9387.         case 1:
  9388.             break;
  9389.  
  9390.         case 2:
  9391.             simplex.Solve2();
  9392.             break;
  9393.  
  9394.         case 3:
  9395.             simplex.Solve3();
  9396.             break;
  9397.  
  9398.         default:
  9399.             b2Assert(false);
  9400.         }
  9401.  
  9402.         // If we have 3 points, then the origin is in the corresponding triangle.
  9403.         if (simplex.m_count == 3) {
  9404.             // Overlap
  9405.             return false;
  9406.         }
  9407.  
  9408.         // Get search direction.
  9409.         v = simplex.GetClosestPoint();
  9410.  
  9411.         // Iteration count is equated to the number of support point calls.
  9412.         ++iter;
  9413.     }
  9414.  
  9415.     if (iter == 0) {
  9416.         // Initial overlap
  9417.         return false;
  9418.     }
  9419.  
  9420.     // Prepare output.
  9421.     b2Vec2 pointA, pointB;
  9422.     simplex.GetWitnessPoints(&pointB, &pointA);
  9423.  
  9424.     if (v.LengthSquared() > 0.0f) {
  9425.         n = -v;
  9426.         n.Normalize();
  9427.     }
  9428.  
  9429.     output->point = pointA + radiusA * n;
  9430.     output->normal = n;
  9431.     output->lambda = lambda;
  9432.     output->iterations = iter;
  9433.     return true;
  9434. }
  9435. // MIT License
  9436.  
  9437. // Copyright (c) 2019 Erin Catto
  9438.  
  9439. // Permission is hereby granted, free of charge, to any person obtaining a copy
  9440. // of this software and associated documentation files (the "Software"), to deal
  9441. // in the Software without restriction, including without limitation the rights
  9442. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9443. // copies of the Software, and to permit persons to whom the Software is
  9444. // furnished to do so, subject to the following conditions:
  9445.  
  9446. // The above copyright notice and this permission notice shall be included in all
  9447. // copies or substantial portions of the Software.
  9448.  
  9449. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  9450. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  9451. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  9452. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  9453. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  9454. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  9455. // SOFTWARE.
  9456. //#include "box2d/b2_dynamic_tree.h"
  9457. #include <string.h>
  9458.  
  9459. b2DynamicTree::b2DynamicTree() {
  9460.     m_root = b2_nullNode;
  9461.  
  9462.     m_nodeCapacity = 16;
  9463.     m_nodeCount = 0;
  9464.     m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode));
  9465.     memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode));
  9466.  
  9467.     // Build a linked list for the free list.
  9468.     for (int32 i = 0; i < m_nodeCapacity - 1; ++i) {
  9469.         m_nodes[i].next = i + 1;
  9470.         m_nodes[i].height = -1;
  9471.     }
  9472.     m_nodes[m_nodeCapacity - 1].next = b2_nullNode;
  9473.     m_nodes[m_nodeCapacity - 1].height = -1;
  9474.     m_freeList = 0;
  9475.  
  9476.     m_insertionCount = 0;
  9477. }
  9478.  
  9479. b2DynamicTree::~b2DynamicTree() {
  9480.     // This frees the entire tree in one shot.
  9481.     b2Free(m_nodes);
  9482. }
  9483.  
  9484. // Allocate a node from the pool. Grow the pool if necessary.
  9485. int32 b2DynamicTree::AllocateNode() {
  9486.     // Expand the node pool as needed.
  9487.     if (m_freeList == b2_nullNode) {
  9488.         b2Assert(m_nodeCount == m_nodeCapacity);
  9489.  
  9490.         // The free list is empty. Rebuild a bigger pool.
  9491.         b2TreeNode* oldNodes = m_nodes;
  9492.         m_nodeCapacity *= 2;
  9493.         m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode));
  9494.         memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode));
  9495.         b2Free(oldNodes);
  9496.  
  9497.         // Build a linked list for the free list. The parent
  9498.         // pointer becomes the "next" pointer.
  9499.         for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) {
  9500.             m_nodes[i].next = i + 1;
  9501.             m_nodes[i].height = -1;
  9502.         }
  9503.         m_nodes[m_nodeCapacity - 1].next = b2_nullNode;
  9504.         m_nodes[m_nodeCapacity - 1].height = -1;
  9505.         m_freeList = m_nodeCount;
  9506.     }
  9507.  
  9508.     // Peel a node off the free list.
  9509.     int32 nodeId = m_freeList;
  9510.     m_freeList = m_nodes[nodeId].next;
  9511.     m_nodes[nodeId].parent = b2_nullNode;
  9512.     m_nodes[nodeId].child1 = b2_nullNode;
  9513.     m_nodes[nodeId].child2 = b2_nullNode;
  9514.     m_nodes[nodeId].height = 0;
  9515.     m_nodes[nodeId].userData = nullptr;
  9516.     m_nodes[nodeId].moved = false;
  9517.     ++m_nodeCount;
  9518.     return nodeId;
  9519. }
  9520.  
  9521. // Return a node to the pool.
  9522. void b2DynamicTree::FreeNode(int32 nodeId) {
  9523.     b2Assert(0 <= nodeId && nodeId < m_nodeCapacity);
  9524.     b2Assert(0 < m_nodeCount);
  9525.     m_nodes[nodeId].next = m_freeList;
  9526.     m_nodes[nodeId].height = -1;
  9527.     m_freeList = nodeId;
  9528.     --m_nodeCount;
  9529. }
  9530.  
  9531. // Create a proxy in the tree as a leaf node. We return the index
  9532. // of the node instead of a pointer so that we can grow
  9533. // the node pool.
  9534. int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) {
  9535.     int32 proxyId = AllocateNode();
  9536.  
  9537.     // Fatten the aabb.
  9538.     b2Vec2 r(b2_aabbExtension, b2_aabbExtension);
  9539.     m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r;
  9540.     m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r;
  9541.     m_nodes[proxyId].userData = userData;
  9542.     m_nodes[proxyId].height = 0;
  9543.     m_nodes[proxyId].moved = true;
  9544.  
  9545.     InsertLeaf(proxyId);
  9546.  
  9547.     return proxyId;
  9548. }
  9549.  
  9550. void b2DynamicTree::DestroyProxy(int32 proxyId) {
  9551.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
  9552.     b2Assert(m_nodes[proxyId].IsLeaf());
  9553.  
  9554.     RemoveLeaf(proxyId);
  9555.     FreeNode(proxyId);
  9556. }
  9557.  
  9558. bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) {
  9559.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
  9560.  
  9561.     b2Assert(m_nodes[proxyId].IsLeaf());
  9562.  
  9563.     // Extend AABB
  9564.     b2AABB fatAABB;
  9565.     b2Vec2 r(b2_aabbExtension, b2_aabbExtension);
  9566.     fatAABB.lowerBound = aabb.lowerBound - r;
  9567.     fatAABB.upperBound = aabb.upperBound + r;
  9568.  
  9569.     // Predict AABB movement
  9570.     b2Vec2 d = b2_aabbMultiplier * displacement;
  9571.  
  9572.     if (d.x < 0.0f) {
  9573.         fatAABB.lowerBound.x += d.x;
  9574.     } else {
  9575.         fatAABB.upperBound.x += d.x;
  9576.     }
  9577.  
  9578.     if (d.y < 0.0f) {
  9579.         fatAABB.lowerBound.y += d.y;
  9580.     } else {
  9581.         fatAABB.upperBound.y += d.y;
  9582.     }
  9583.  
  9584.     const b2AABB& treeAABB = m_nodes[proxyId].aabb;
  9585.     if (treeAABB.Contains(aabb)) {
  9586.         // The tree AABB still contains the object, but it might be too large.
  9587.         // Perhaps the object was moving fast but has since gone to sleep.
  9588.         // The huge AABB is larger than the new fat AABB.
  9589.         b2AABB hugeAABB;
  9590.         hugeAABB.lowerBound = fatAABB.lowerBound - 4.0f * r;
  9591.         hugeAABB.upperBound = fatAABB.upperBound + 4.0f * r;
  9592.  
  9593.         if (hugeAABB.Contains(treeAABB)) {
  9594.             // The tree AABB contains the object AABB and the tree AABB is
  9595.             // not too large. No tree update needed.
  9596.             return false;
  9597.         }
  9598.  
  9599.         // Otherwise the tree AABB is huge and needs to be shrunk
  9600.     }
  9601.  
  9602.     RemoveLeaf(proxyId);
  9603.  
  9604.     m_nodes[proxyId].aabb = fatAABB;
  9605.  
  9606.     InsertLeaf(proxyId);
  9607.  
  9608.     m_nodes[proxyId].moved = true;
  9609.  
  9610.     return true;
  9611. }
  9612.  
  9613. void b2DynamicTree::InsertLeaf(int32 leaf) {
  9614.     ++m_insertionCount;
  9615.  
  9616.     if (m_root == b2_nullNode) {
  9617.         m_root = leaf;
  9618.         m_nodes[m_root].parent = b2_nullNode;
  9619.         return;
  9620.     }
  9621.  
  9622.     // Find the best sibling for this node
  9623.     b2AABB leafAABB = m_nodes[leaf].aabb;
  9624.     int32 index = m_root;
  9625.     while (m_nodes[index].IsLeaf() == false) {
  9626.         int32 child1 = m_nodes[index].child1;
  9627.         int32 child2 = m_nodes[index].child2;
  9628.  
  9629.         float area = m_nodes[index].aabb.GetPerimeter();
  9630.  
  9631.         b2AABB combinedAABB;
  9632.         combinedAABB.Combine(m_nodes[index].aabb, leafAABB);
  9633.         float combinedArea = combinedAABB.GetPerimeter();
  9634.  
  9635.         // Cost of creating a new parent for this node and the new leaf
  9636.         float cost = 2.0f * combinedArea;
  9637.  
  9638.         // Minimum cost of pushing the leaf further down the tree
  9639.         float inheritanceCost = 2.0f * (combinedArea - area);
  9640.  
  9641.         // Cost of descending into child1
  9642.         float cost1;
  9643.         if (m_nodes[child1].IsLeaf()) {
  9644.             b2AABB aabb;
  9645.             aabb.Combine(leafAABB, m_nodes[child1].aabb);
  9646.             cost1 = aabb.GetPerimeter() + inheritanceCost;
  9647.         } else {
  9648.             b2AABB aabb;
  9649.             aabb.Combine(leafAABB, m_nodes[child1].aabb);
  9650.             float oldArea = m_nodes[child1].aabb.GetPerimeter();
  9651.             float newArea = aabb.GetPerimeter();
  9652.             cost1 = (newArea - oldArea) + inheritanceCost;
  9653.         }
  9654.  
  9655.         // Cost of descending into child2
  9656.         float cost2;
  9657.         if (m_nodes[child2].IsLeaf()) {
  9658.             b2AABB aabb;
  9659.             aabb.Combine(leafAABB, m_nodes[child2].aabb);
  9660.             cost2 = aabb.GetPerimeter() + inheritanceCost;
  9661.         } else {
  9662.             b2AABB aabb;
  9663.             aabb.Combine(leafAABB, m_nodes[child2].aabb);
  9664.             float oldArea = m_nodes[child2].aabb.GetPerimeter();
  9665.             float newArea = aabb.GetPerimeter();
  9666.             cost2 = newArea - oldArea + inheritanceCost;
  9667.         }
  9668.  
  9669.         // Descend according to the minimum cost.
  9670.         if (cost < cost1 && cost < cost2) {
  9671.             break;
  9672.         }
  9673.  
  9674.         // Descend
  9675.         if (cost1 < cost2) {
  9676.             index = child1;
  9677.         } else {
  9678.             index = child2;
  9679.         }
  9680.     }
  9681.  
  9682.     int32 sibling = index;
  9683.  
  9684.     // Create a new parent.
  9685.     int32 oldParent = m_nodes[sibling].parent;
  9686.     int32 newParent = AllocateNode();
  9687.     m_nodes[newParent].parent = oldParent;
  9688.     m_nodes[newParent].userData = nullptr;
  9689.     m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb);
  9690.     m_nodes[newParent].height = m_nodes[sibling].height + 1;
  9691.  
  9692.     if (oldParent != b2_nullNode) {
  9693.         // The sibling was not the root.
  9694.         if (m_nodes[oldParent].child1 == sibling) {
  9695.             m_nodes[oldParent].child1 = newParent;
  9696.         } else {
  9697.             m_nodes[oldParent].child2 = newParent;
  9698.         }
  9699.  
  9700.         m_nodes[newParent].child1 = sibling;
  9701.         m_nodes[newParent].child2 = leaf;
  9702.         m_nodes[sibling].parent = newParent;
  9703.         m_nodes[leaf].parent = newParent;
  9704.     } else {
  9705.         // The sibling was the root.
  9706.         m_nodes[newParent].child1 = sibling;
  9707.         m_nodes[newParent].child2 = leaf;
  9708.         m_nodes[sibling].parent = newParent;
  9709.         m_nodes[leaf].parent = newParent;
  9710.         m_root = newParent;
  9711.     }
  9712.  
  9713.     // Walk back up the tree fixing heights and AABBs
  9714.     index = m_nodes[leaf].parent;
  9715.     while (index != b2_nullNode) {
  9716.         index = Balance(index);
  9717.  
  9718.         int32 child1 = m_nodes[index].child1;
  9719.         int32 child2 = m_nodes[index].child2;
  9720.  
  9721.         b2Assert(child1 != b2_nullNode);
  9722.         b2Assert(child2 != b2_nullNode);
  9723.  
  9724.         m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);
  9725.         m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);
  9726.  
  9727.         index = m_nodes[index].parent;
  9728.     }
  9729.  
  9730.     //Validate();
  9731. }
  9732.  
  9733. void b2DynamicTree::RemoveLeaf(int32 leaf) {
  9734.     if (leaf == m_root) {
  9735.         m_root = b2_nullNode;
  9736.         return;
  9737.     }
  9738.  
  9739.     int32 parent = m_nodes[leaf].parent;
  9740.     int32 grandParent = m_nodes[parent].parent;
  9741.     int32 sibling;
  9742.     if (m_nodes[parent].child1 == leaf) {
  9743.         sibling = m_nodes[parent].child2;
  9744.     } else {
  9745.         sibling = m_nodes[parent].child1;
  9746.     }
  9747.  
  9748.     if (grandParent != b2_nullNode) {
  9749.         // Destroy parent and connect sibling to grandParent.
  9750.         if (m_nodes[grandParent].child1 == parent) {
  9751.             m_nodes[grandParent].child1 = sibling;
  9752.         } else {
  9753.             m_nodes[grandParent].child2 = sibling;
  9754.         }
  9755.         m_nodes[sibling].parent = grandParent;
  9756.         FreeNode(parent);
  9757.  
  9758.         // Adjust ancestor bounds.
  9759.         int32 index = grandParent;
  9760.         while (index != b2_nullNode) {
  9761.             index = Balance(index);
  9762.  
  9763.             int32 child1 = m_nodes[index].child1;
  9764.             int32 child2 = m_nodes[index].child2;
  9765.  
  9766.             m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);
  9767.             m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);
  9768.  
  9769.             index = m_nodes[index].parent;
  9770.         }
  9771.     } else {
  9772.         m_root = sibling;
  9773.         m_nodes[sibling].parent = b2_nullNode;
  9774.         FreeNode(parent);
  9775.     }
  9776.  
  9777.     //Validate();
  9778. }
  9779.  
  9780. // Perform a left or right rotation if node A is imbalanced.
  9781. // Returns the new root index.
  9782. int32 b2DynamicTree::Balance(int32 iA) {
  9783.     b2Assert(iA != b2_nullNode);
  9784.  
  9785.     b2TreeNode* A = m_nodes + iA;
  9786.     if (A->IsLeaf() || A->height < 2) {
  9787.         return iA;
  9788.     }
  9789.  
  9790.     int32 iB = A->child1;
  9791.     int32 iC = A->child2;
  9792.     b2Assert(0 <= iB && iB < m_nodeCapacity);
  9793.     b2Assert(0 <= iC && iC < m_nodeCapacity);
  9794.  
  9795.     b2TreeNode* B = m_nodes + iB;
  9796.     b2TreeNode* C = m_nodes + iC;
  9797.  
  9798.     int32 balance = C->height - B->height;
  9799.  
  9800.     // Rotate C up
  9801.     if (balance > 1) {
  9802.         int32 iF = C->child1;
  9803.         int32 iG = C->child2;
  9804.         b2TreeNode* F = m_nodes + iF;
  9805.         b2TreeNode* G = m_nodes + iG;
  9806.         b2Assert(0 <= iF && iF < m_nodeCapacity);
  9807.         b2Assert(0 <= iG && iG < m_nodeCapacity);
  9808.  
  9809.         // Swap A and C
  9810.         C->child1 = iA;
  9811.         C->parent = A->parent;
  9812.         A->parent = iC;
  9813.  
  9814.         // A's old parent should point to C
  9815.         if (C->parent != b2_nullNode) {
  9816.             if (m_nodes[C->parent].child1 == iA) {
  9817.                 m_nodes[C->parent].child1 = iC;
  9818.             } else {
  9819.                 b2Assert(m_nodes[C->parent].child2 == iA);
  9820.                 m_nodes[C->parent].child2 = iC;
  9821.             }
  9822.         } else {
  9823.             m_root = iC;
  9824.         }
  9825.  
  9826.         // Rotate
  9827.         if (F->height > G->height) {
  9828.             C->child2 = iF;
  9829.             A->child2 = iG;
  9830.             G->parent = iA;
  9831.             A->aabb.Combine(B->aabb, G->aabb);
  9832.             C->aabb.Combine(A->aabb, F->aabb);
  9833.  
  9834.             A->height = 1 + b2Max(B->height, G->height);
  9835.             C->height = 1 + b2Max(A->height, F->height);
  9836.         } else {
  9837.             C->child2 = iG;
  9838.             A->child2 = iF;
  9839.             F->parent = iA;
  9840.             A->aabb.Combine(B->aabb, F->aabb);
  9841.             C->aabb.Combine(A->aabb, G->aabb);
  9842.  
  9843.             A->height = 1 + b2Max(B->height, F->height);
  9844.             C->height = 1 + b2Max(A->height, G->height);
  9845.         }
  9846.  
  9847.         return iC;
  9848.     }
  9849.  
  9850.     // Rotate B up
  9851.     if (balance < -1) {
  9852.         int32 iD = B->child1;
  9853.         int32 iE = B->child2;
  9854.         b2TreeNode* D = m_nodes + iD;
  9855.         b2TreeNode* E = m_nodes + iE;
  9856.         b2Assert(0 <= iD && iD < m_nodeCapacity);
  9857.         b2Assert(0 <= iE && iE < m_nodeCapacity);
  9858.  
  9859.         // Swap A and B
  9860.         B->child1 = iA;
  9861.         B->parent = A->parent;
  9862.         A->parent = iB;
  9863.  
  9864.         // A's old parent should point to B
  9865.         if (B->parent != b2_nullNode) {
  9866.             if (m_nodes[B->parent].child1 == iA) {
  9867.                 m_nodes[B->parent].child1 = iB;
  9868.             } else {
  9869.                 b2Assert(m_nodes[B->parent].child2 == iA);
  9870.                 m_nodes[B->parent].child2 = iB;
  9871.             }
  9872.         } else {
  9873.             m_root = iB;
  9874.         }
  9875.  
  9876.         // Rotate
  9877.         if (D->height > E->height) {
  9878.             B->child2 = iD;
  9879.             A->child1 = iE;
  9880.             E->parent = iA;
  9881.             A->aabb.Combine(C->aabb, E->aabb);
  9882.             B->aabb.Combine(A->aabb, D->aabb);
  9883.  
  9884.             A->height = 1 + b2Max(C->height, E->height);
  9885.             B->height = 1 + b2Max(A->height, D->height);
  9886.         } else {
  9887.             B->child2 = iE;
  9888.             A->child1 = iD;
  9889.             D->parent = iA;
  9890.             A->aabb.Combine(C->aabb, D->aabb);
  9891.             B->aabb.Combine(A->aabb, E->aabb);
  9892.  
  9893.             A->height = 1 + b2Max(C->height, D->height);
  9894.             B->height = 1 + b2Max(A->height, E->height);
  9895.         }
  9896.  
  9897.         return iB;
  9898.     }
  9899.  
  9900.     return iA;
  9901. }
  9902.  
  9903. int32 b2DynamicTree::GetHeight() const {
  9904.     if (m_root == b2_nullNode) {
  9905.         return 0;
  9906.     }
  9907.  
  9908.     return m_nodes[m_root].height;
  9909. }
  9910.  
  9911. //
  9912. float b2DynamicTree::GetAreaRatio() const {
  9913.     if (m_root == b2_nullNode) {
  9914.         return 0.0f;
  9915.     }
  9916.  
  9917.     const b2TreeNode* root = m_nodes + m_root;
  9918.     float rootArea = root->aabb.GetPerimeter();
  9919.  
  9920.     float totalArea = 0.0f;
  9921.     for (int32 i = 0; i < m_nodeCapacity; ++i) {
  9922.         const b2TreeNode* node = m_nodes + i;
  9923.         if (node->height < 0) {
  9924.             // Free node in pool
  9925.             continue;
  9926.         }
  9927.  
  9928.         totalArea += node->aabb.GetPerimeter();
  9929.     }
  9930.  
  9931.     return totalArea / rootArea;
  9932. }
  9933.  
  9934. // Compute the height of a sub-tree.
  9935. int32 b2DynamicTree::ComputeHeight(int32 nodeId) const {
  9936.     b2Assert(0 <= nodeId && nodeId < m_nodeCapacity);
  9937.     b2TreeNode* node = m_nodes + nodeId;
  9938.  
  9939.     if (node->IsLeaf()) {
  9940.         return 0;
  9941.     }
  9942.  
  9943.     int32 height1 = ComputeHeight(node->child1);
  9944.     int32 height2 = ComputeHeight(node->child2);
  9945.     return 1 + b2Max(height1, height2);
  9946. }
  9947.  
  9948. int32 b2DynamicTree::ComputeHeight() const {
  9949.     int32 height = ComputeHeight(m_root);
  9950.     return height;
  9951. }
  9952.  
  9953. void b2DynamicTree::ValidateStructure(int32 index) const {
  9954.     if (index == b2_nullNode) {
  9955.         return;
  9956.     }
  9957.  
  9958.     if (index == m_root) {
  9959.         b2Assert(m_nodes[index].parent == b2_nullNode);
  9960.     }
  9961.  
  9962.     const b2TreeNode* node = m_nodes + index;
  9963.  
  9964.     int32 child1 = node->child1;
  9965.     int32 child2 = node->child2;
  9966.  
  9967.     if (node->IsLeaf()) {
  9968.         b2Assert(child1 == b2_nullNode);
  9969.         b2Assert(child2 == b2_nullNode);
  9970.         b2Assert(node->height == 0);
  9971.         return;
  9972.     }
  9973.  
  9974.     b2Assert(0 <= child1 && child1 < m_nodeCapacity);
  9975.     b2Assert(0 <= child2 && child2 < m_nodeCapacity);
  9976.  
  9977.     b2Assert(m_nodes[child1].parent == index);
  9978.     b2Assert(m_nodes[child2].parent == index);
  9979.  
  9980.     ValidateStructure(child1);
  9981.     ValidateStructure(child2);
  9982. }
  9983.  
  9984. void b2DynamicTree::ValidateMetrics(int32 index) const {
  9985.     if (index == b2_nullNode) {
  9986.         return;
  9987.     }
  9988.  
  9989.     const b2TreeNode* node = m_nodes + index;
  9990.  
  9991.     int32 child1 = node->child1;
  9992.     int32 child2 = node->child2;
  9993.  
  9994.     if (node->IsLeaf()) {
  9995.         b2Assert(child1 == b2_nullNode);
  9996.         b2Assert(child2 == b2_nullNode);
  9997.         b2Assert(node->height == 0);
  9998.         return;
  9999.     }
  10000.  
  10001.     b2Assert(0 <= child1 && child1 < m_nodeCapacity);
  10002.     b2Assert(0 <= child2 && child2 < m_nodeCapacity);
  10003.  
  10004.     int32 height1 = m_nodes[child1].height;
  10005.     int32 height2 = m_nodes[child2].height;
  10006.     int32 height;
  10007.     height = 1 + b2Max(height1, height2);
  10008.     b2Assert(node->height == height);
  10009.  
  10010.     b2AABB aabb;
  10011.     aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);
  10012.  
  10013.     b2Assert(aabb.lowerBound == node->aabb.lowerBound);
  10014.     b2Assert(aabb.upperBound == node->aabb.upperBound);
  10015.  
  10016.     ValidateMetrics(child1);
  10017.     ValidateMetrics(child2);
  10018. }
  10019.  
  10020. void b2DynamicTree::Validate() const {
  10021. #if defined(b2DEBUG)
  10022.     ValidateStructure(m_root);
  10023.     ValidateMetrics(m_root);
  10024.  
  10025.     int32 freeCount = 0;
  10026.     int32 freeIndex = m_freeList;
  10027.     while (freeIndex != b2_nullNode) {
  10028.         b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity);
  10029.         freeIndex = m_nodes[freeIndex].next;
  10030.         ++freeCount;
  10031.     }
  10032.  
  10033.     b2Assert(GetHeight() == ComputeHeight());
  10034.  
  10035.     b2Assert(m_nodeCount + freeCount == m_nodeCapacity);
  10036. #endif
  10037. }
  10038.  
  10039. int32 b2DynamicTree::GetMaxBalance() const {
  10040.     int32 maxBalance = 0;
  10041.     for (int32 i = 0; i < m_nodeCapacity; ++i) {
  10042.         const b2TreeNode* node = m_nodes + i;
  10043.         if (node->height <= 1) {
  10044.             continue;
  10045.         }
  10046.  
  10047.         b2Assert(node->IsLeaf() == false);
  10048.  
  10049.         int32 child1 = node->child1;
  10050.         int32 child2 = node->child2;
  10051.         int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height);
  10052.         maxBalance = b2Max(maxBalance, balance);
  10053.     }
  10054.  
  10055.     return maxBalance;
  10056. }
  10057.  
  10058. void b2DynamicTree::RebuildBottomUp() {
  10059.     int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32));
  10060.     int32 count = 0;
  10061.  
  10062.     // Build array of leaves. Free the rest.
  10063.     for (int32 i = 0; i < m_nodeCapacity; ++i) {
  10064.         if (m_nodes[i].height < 0) {
  10065.             // free node in pool
  10066.             continue;
  10067.         }
  10068.  
  10069.         if (m_nodes[i].IsLeaf()) {
  10070.             m_nodes[i].parent = b2_nullNode;
  10071.             nodes[count] = i;
  10072.             ++count;
  10073.         } else {
  10074.             FreeNode(i);
  10075.         }
  10076.     }
  10077.  
  10078.     while (count > 1) {
  10079.         float minCost = b2_maxFloat;
  10080.         int32 iMin = -1, jMin = -1;
  10081.         for (int32 i = 0; i < count; ++i) {
  10082.             b2AABB aabbi = m_nodes[nodes[i]].aabb;
  10083.  
  10084.             for (int32 j = i + 1; j < count; ++j) {
  10085.                 b2AABB aabbj = m_nodes[nodes[j]].aabb;
  10086.                 b2AABB b;
  10087.                 b.Combine(aabbi, aabbj);
  10088.                 float cost = b.GetPerimeter();
  10089.                 if (cost < minCost) {
  10090.                     iMin = i;
  10091.                     jMin = j;
  10092.                     minCost = cost;
  10093.                 }
  10094.             }
  10095.         }
  10096.  
  10097.         int32 index1 = nodes[iMin];
  10098.         int32 index2 = nodes[jMin];
  10099.         b2TreeNode* child1 = m_nodes + index1;
  10100.         b2TreeNode* child2 = m_nodes + index2;
  10101.  
  10102.         int32 parentIndex = AllocateNode();
  10103.         b2TreeNode* parent = m_nodes + parentIndex;
  10104.         parent->child1 = index1;
  10105.         parent->child2 = index2;
  10106.         parent->height = 1 + b2Max(child1->height, child2->height);
  10107.         parent->aabb.Combine(child1->aabb, child2->aabb);
  10108.         parent->parent = b2_nullNode;
  10109.  
  10110.         child1->parent = parentIndex;
  10111.         child2->parent = parentIndex;
  10112.  
  10113.         nodes[jMin] = nodes[count - 1];
  10114.         nodes[iMin] = parentIndex;
  10115.         --count;
  10116.     }
  10117.  
  10118.     m_root = nodes[0];
  10119.     b2Free(nodes);
  10120.  
  10121.     Validate();
  10122. }
  10123.  
  10124. void b2DynamicTree::ShiftOrigin(const b2Vec2& newOrigin) {
  10125.     // Build array of leaves. Free the rest.
  10126.     for (int32 i = 0; i < m_nodeCapacity; ++i) {
  10127.         m_nodes[i].aabb.lowerBound -= newOrigin;
  10128.         m_nodes[i].aabb.upperBound -= newOrigin;
  10129.     }
  10130. }
  10131. // MIT License
  10132.  
  10133. // Copyright (c) 2019 Erin Catto
  10134.  
  10135. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10136. // of this software and associated documentation files (the "Software"), to deal
  10137. // in the Software without restriction, including without limitation the rights
  10138. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10139. // copies of the Software, and to permit persons to whom the Software is
  10140. // furnished to do so, subject to the following conditions:
  10141.  
  10142. // The above copyright notice and this permission notice shall be included in all
  10143. // copies or substantial portions of the Software.
  10144.  
  10145. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  10146. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  10147. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  10148. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  10149. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  10150. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  10151. // SOFTWARE.
  10152.  
  10153. //#include "box2d/b2_edge_shape.h"
  10154. //#include "box2d/b2_block_allocator.h"
  10155. #include <new>
  10156.  
  10157. void b2EdgeShape::SetOneSided(const b2Vec2& v0, const b2Vec2& v1, const b2Vec2& v2, const b2Vec2& v3) {
  10158.     m_vertex0 = v0;
  10159.     m_vertex1 = v1;
  10160.     m_vertex2 = v2;
  10161.     m_vertex3 = v3;
  10162.     m_oneSided = true;
  10163. }
  10164.  
  10165. void b2EdgeShape::SetTwoSided(const b2Vec2& v1, const b2Vec2& v2) {
  10166.     m_vertex1 = v1;
  10167.     m_vertex2 = v2;
  10168.     m_oneSided = false;
  10169. }
  10170.  
  10171. b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const {
  10172.     void* mem = allocator->Allocate(sizeof(b2EdgeShape));
  10173.     b2EdgeShape* clone = new (mem) b2EdgeShape;
  10174.     *clone = *this;
  10175.     return clone;
  10176. }
  10177.  
  10178. int32 b2EdgeShape::GetChildCount() const {
  10179.     return 1;
  10180. }
  10181.  
  10182. bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const {
  10183.     B2_NOT_USED(xf);
  10184.     B2_NOT_USED(p);
  10185.     return false;
  10186. }
  10187.  
  10188. // p = p1 + t * d
  10189. // v = v1 + s * e
  10190. // p1 + t * d = v1 + s * e
  10191. // s * e - t * d = p1 - v1
  10192. bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  10193.     const b2Transform& xf, int32 childIndex) const {
  10194.     B2_NOT_USED(childIndex);
  10195.  
  10196.     // Put the ray into the edge's frame of reference.
  10197.     b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
  10198.     b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
  10199.     b2Vec2 d = p2 - p1;
  10200.  
  10201.     b2Vec2 v1 = m_vertex1;
  10202.     b2Vec2 v2 = m_vertex2;
  10203.     b2Vec2 e = v2 - v1;
  10204.  
  10205.     // Normal points to the right, looking from v1 at v2
  10206.     b2Vec2 normal(e.y, -e.x);
  10207.     normal.Normalize();
  10208.  
  10209.     // q = p1 + t * d
  10210.     // dot(normal, q - v1) = 0
  10211.     // dot(normal, p1 - v1) + t * dot(normal, d) = 0
  10212.     float numerator = b2Dot(normal, v1 - p1);
  10213.     if (m_oneSided && numerator > 0.0f) {
  10214.         return false;
  10215.     }
  10216.  
  10217.     float denominator = b2Dot(normal, d);
  10218.  
  10219.     if (denominator == 0.0f) {
  10220.         return false;
  10221.     }
  10222.  
  10223.     float t = numerator / denominator;
  10224.     if (t < 0.0f || input.maxFraction < t) {
  10225.         return false;
  10226.     }
  10227.  
  10228.     b2Vec2 q = p1 + t * d;
  10229.  
  10230.     // q = v1 + s * r
  10231.     // s = dot(q - v1, r) / dot(r, r)
  10232.     b2Vec2 r = v2 - v1;
  10233.     float rr = b2Dot(r, r);
  10234.     if (rr == 0.0f) {
  10235.         return false;
  10236.     }
  10237.  
  10238.     float s = b2Dot(q - v1, r) / rr;
  10239.     if (s < 0.0f || 1.0f < s) {
  10240.         return false;
  10241.     }
  10242.  
  10243.     output->fraction = t;
  10244.     if (numerator > 0.0f) {
  10245.         output->normal = -b2Mul(xf.q, normal);
  10246.     } else {
  10247.         output->normal = b2Mul(xf.q, normal);
  10248.     }
  10249.     return true;
  10250. }
  10251.  
  10252. void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const {
  10253.     B2_NOT_USED(childIndex);
  10254.  
  10255.     b2Vec2 v1 = b2Mul(xf, m_vertex1);
  10256.     b2Vec2 v2 = b2Mul(xf, m_vertex2);
  10257.  
  10258.     b2Vec2 lower = b2Min(v1, v2);
  10259.     b2Vec2 upper = b2Max(v1, v2);
  10260.  
  10261.     b2Vec2 r(m_radius, m_radius);
  10262.     aabb->lowerBound = lower - r;
  10263.     aabb->upperBound = upper + r;
  10264. }
  10265.  
  10266. void b2EdgeShape::ComputeMass(b2MassData* massData, float density) const {
  10267.     B2_NOT_USED(density);
  10268.  
  10269.     massData->mass = 0.0f;
  10270.     massData->center = 0.5f * (m_vertex1 + m_vertex2);
  10271.     massData->I = 0.0f;
  10272. }
  10273. // MIT License
  10274.  
  10275. // Copyright (c) 2019 Erin Catto
  10276.  
  10277. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10278. // of this software and associated documentation files (the "Software"), to deal
  10279. // in the Software without restriction, including without limitation the rights
  10280. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10281. // copies of the Software, and to permit persons to whom the Software is
  10282. // furnished to do so, subject to the following conditions:
  10283.  
  10284. // The above copyright notice and this permission notice shall be included in all
  10285. // copies or substantial portions of the Software.
  10286.  
  10287. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  10288. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  10289. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  10290. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  10291. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  10292. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  10293. // SOFTWARE.
  10294.  
  10295. //#include "box2d/b2_polygon_shape.h"
  10296. //#include "box2d/b2_block_allocator.h"
  10297.  
  10298. #include <new>
  10299.  
  10300. b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const {
  10301.     void* mem = allocator->Allocate(sizeof(b2PolygonShape));
  10302.     b2PolygonShape* clone = new (mem) b2PolygonShape;
  10303.     *clone = *this;
  10304.     return clone;
  10305. }
  10306.  
  10307. void b2PolygonShape::SetAsBox(float hx, float hy) {
  10308.     m_count = 4;
  10309.     m_vertices[0].Set(-hx, -hy);
  10310.     m_vertices[1].Set(hx, -hy);
  10311.     m_vertices[2].Set(hx, hy);
  10312.     m_vertices[3].Set(-hx, hy);
  10313.     m_normals[0].Set(0.0f, -1.0f);
  10314.     m_normals[1].Set(1.0f, 0.0f);
  10315.     m_normals[2].Set(0.0f, 1.0f);
  10316.     m_normals[3].Set(-1.0f, 0.0f);
  10317.     m_centroid.SetZero();
  10318. }
  10319.  
  10320. void b2PolygonShape::SetAsBox(float hx, float hy, const b2Vec2& center, float angle) {
  10321.     m_count = 4;
  10322.     m_vertices[0].Set(-hx, -hy);
  10323.     m_vertices[1].Set(hx, -hy);
  10324.     m_vertices[2].Set(hx, hy);
  10325.     m_vertices[3].Set(-hx, hy);
  10326.     m_normals[0].Set(0.0f, -1.0f);
  10327.     m_normals[1].Set(1.0f, 0.0f);
  10328.     m_normals[2].Set(0.0f, 1.0f);
  10329.     m_normals[3].Set(-1.0f, 0.0f);
  10330.     m_centroid = center;
  10331.  
  10332.     b2Transform xf;
  10333.     xf.p = center;
  10334.     xf.q.Set(angle);
  10335.  
  10336.     // Transform vertices and normals.
  10337.     for (int32 i = 0; i < m_count; ++i) {
  10338.         m_vertices[i] = b2Mul(xf, m_vertices[i]);
  10339.         m_normals[i] = b2Mul(xf.q, m_normals[i]);
  10340.     }
  10341. }
  10342.  
  10343. int32 b2PolygonShape::GetChildCount() const {
  10344.     return 1;
  10345. }
  10346.  
  10347. static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) {
  10348.     b2Assert(count >= 3);
  10349.  
  10350.     b2Vec2 c(0.0f, 0.0f);
  10351.     float area = 0.0f;
  10352.  
  10353.     // Get a reference point for forming triangles.
  10354.     // Use the first vertex to reduce round-off errors.
  10355.     b2Vec2 s = vs[0];
  10356.  
  10357.     const float inv3 = 1.0f / 3.0f;
  10358.  
  10359.     for (int32 i = 0; i < count; ++i) {
  10360.         // Triangle vertices.
  10361.         b2Vec2 p1 = vs[0] - s;
  10362.         b2Vec2 p2 = vs[i] - s;
  10363.         b2Vec2 p3 = i + 1 < count ? vs[i + 1] - s : vs[0] - s;
  10364.  
  10365.         b2Vec2 e1 = p2 - p1;
  10366.         b2Vec2 e2 = p3 - p1;
  10367.  
  10368.         float D = b2Cross(e1, e2);
  10369.  
  10370.         float triangleArea = 0.5f * D;
  10371.         area += triangleArea;
  10372.  
  10373.         // Area weighted centroid
  10374.         c += triangleArea * inv3 * (p1 + p2 + p3);
  10375.     }
  10376.  
  10377.     // Centroid
  10378.     b2Assert(area > b2_epsilon);
  10379.     c = (1.0f / area) * c + s;
  10380.     return c;
  10381. }
  10382.  
  10383. void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) {
  10384.     b2Assert(3 <= count && count <= b2_maxPolygonVertices);
  10385.     if (count < 3) {
  10386.         SetAsBox(1.0f, 1.0f);
  10387.         return;
  10388.     }
  10389.  
  10390.     int32 n = b2Min(count, b2_maxPolygonVertices);
  10391.  
  10392.     // Perform welding and copy vertices into local buffer.
  10393.     b2Vec2 ps[b2_maxPolygonVertices];
  10394.     int32 tempCount = 0;
  10395.     for (int32 i = 0; i < n; ++i) {
  10396.         b2Vec2 v = vertices[i];
  10397.  
  10398.         bool unique = true;
  10399.         for (int32 j = 0; j < tempCount; ++j) {
  10400.             if (b2DistanceSquared(v, ps[j]) < ((0.5f * b2_linearSlop) * (0.5f * b2_linearSlop))) {
  10401.                 unique = false;
  10402.                 break;
  10403.             }
  10404.         }
  10405.  
  10406.         if (unique) {
  10407.             ps[tempCount++] = v;
  10408.         }
  10409.     }
  10410.  
  10411.     n = tempCount;
  10412.     if (n < 3) {
  10413.         // Polygon is degenerate.
  10414.         b2Assert(false);
  10415.         SetAsBox(1.0f, 1.0f);
  10416.         return;
  10417.     }
  10418.  
  10419.     // Create the convex hull using the Gift wrapping algorithm
  10420.     // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm
  10421.  
  10422.     // Find the right most point on the hull
  10423.     int32 i0 = 0;
  10424.     float x0 = ps[0].x;
  10425.     for (int32 i = 1; i < n; ++i) {
  10426.         float x = ps[i].x;
  10427.         if (x > x0 || (x == x0 && ps[i].y < ps[i0].y)) {
  10428.             i0 = i;
  10429.             x0 = x;
  10430.         }
  10431.     }
  10432.  
  10433.     int32 hull[b2_maxPolygonVertices];
  10434.     int32 m = 0;
  10435.     int32 ih = i0;
  10436.  
  10437.     for (;;) {
  10438.         b2Assert(m < b2_maxPolygonVertices);
  10439.         hull[m] = ih;
  10440.  
  10441.         int32 ie = 0;
  10442.         for (int32 j = 1; j < n; ++j) {
  10443.             if (ie == ih) {
  10444.                 ie = j;
  10445.                 continue;
  10446.             }
  10447.  
  10448.             b2Vec2 r = ps[ie] - ps[hull[m]];
  10449.             b2Vec2 v = ps[j] - ps[hull[m]];
  10450.             float c = b2Cross(r, v);
  10451.             if (c < 0.0f) {
  10452.                 ie = j;
  10453.             }
  10454.  
  10455.             // Collinearity check
  10456.             if (c == 0.0f && v.LengthSquared() > r.LengthSquared()) {
  10457.                 ie = j;
  10458.             }
  10459.         }
  10460.  
  10461.         ++m;
  10462.         ih = ie;
  10463.  
  10464.         if (ie == i0) {
  10465.             break;
  10466.         }
  10467.     }
  10468.  
  10469.     if (m < 3) {
  10470.         // Polygon is degenerate.
  10471.         b2Assert(false);
  10472.         SetAsBox(1.0f, 1.0f);
  10473.         return;
  10474.     }
  10475.  
  10476.     m_count = m;
  10477.  
  10478.     // Copy vertices.
  10479.     for (int32 i = 0; i < m; ++i) {
  10480.         m_vertices[i] = ps[hull[i]];
  10481.     }
  10482.  
  10483.     // Compute normals. Ensure the edges have non-zero length.
  10484.     for (int32 i = 0; i < m; ++i) {
  10485.         int32 i1 = i;
  10486.         int32 i2 = i + 1 < m ? i + 1 : 0;
  10487.         b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
  10488.         b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
  10489.         m_normals[i] = b2Cross(edge, 1.0f);
  10490.         m_normals[i].Normalize();
  10491.     }
  10492.  
  10493.     // Compute the polygon centroid.
  10494.     m_centroid = ComputeCentroid(m_vertices, m);
  10495. }
  10496.  
  10497. bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const {
  10498.     b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);
  10499.  
  10500.     for (int32 i = 0; i < m_count; ++i) {
  10501.         float dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
  10502.         if (dot > 0.0f) {
  10503.             return false;
  10504.         }
  10505.     }
  10506.  
  10507.     return true;
  10508. }
  10509.  
  10510. bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  10511.     const b2Transform& xf, int32 childIndex) const {
  10512.     B2_NOT_USED(childIndex);
  10513.  
  10514.     // Put the ray into the polygon's frame of reference.
  10515.     b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
  10516.     b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
  10517.     b2Vec2 d = p2 - p1;
  10518.  
  10519.     float lower = 0.0f, upper = input.maxFraction;
  10520.  
  10521.     int32 index = -1;
  10522.  
  10523.     for (int32 i = 0; i < m_count; ++i) {
  10524.         // p = p1 + a * d
  10525.         // dot(normal, p - v) = 0
  10526.         // dot(normal, p1 - v) + a * dot(normal, d) = 0
  10527.         float numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
  10528.         float denominator = b2Dot(m_normals[i], d);
  10529.  
  10530.         if (denominator == 0.0f) {
  10531.             if (numerator < 0.0f) {
  10532.                 return false;
  10533.             }
  10534.         } else {
  10535.             // Note: we want this predicate without division:
  10536.             // lower < numerator / denominator, where denominator < 0
  10537.             // Since denominator < 0, we have to flip the inequality:
  10538.             // lower < numerator / denominator <==> denominator * lower > numerator.
  10539.             if (denominator < 0.0f && numerator < lower * denominator) {
  10540.                 // Increase lower.
  10541.                 // The segment enters this half-space.
  10542.                 lower = numerator / denominator;
  10543.                 index = i;
  10544.             } else if (denominator > 0.0f && numerator < upper * denominator) {
  10545.                 // Decrease upper.
  10546.                 // The segment exits this half-space.
  10547.                 upper = numerator / denominator;
  10548.             }
  10549.         }
  10550.  
  10551.         // The use of epsilon here causes the assert on lower to trip
  10552.         // in some cases. Apparently the use of epsilon was to make edge
  10553.         // shapes work, but now those are handled separately.
  10554.         //if (upper < lower - b2_epsilon)
  10555.         if (upper < lower) {
  10556.             return false;
  10557.         }
  10558.     }
  10559.  
  10560.     b2Assert(0.0f <= lower && lower <= input.maxFraction);
  10561.  
  10562.     if (index >= 0) {
  10563.         output->fraction = lower;
  10564.         output->normal = b2Mul(xf.q, m_normals[index]);
  10565.         return true;
  10566.     }
  10567.  
  10568.     return false;
  10569. }
  10570.  
  10571. void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const {
  10572.     B2_NOT_USED(childIndex);
  10573.  
  10574.     b2Vec2 lower = b2Mul(xf, m_vertices[0]);
  10575.     b2Vec2 upper = lower;
  10576.  
  10577.     for (int32 i = 1; i < m_count; ++i) {
  10578.         b2Vec2 v = b2Mul(xf, m_vertices[i]);
  10579.         lower = b2Min(lower, v);
  10580.         upper = b2Max(upper, v);
  10581.     }
  10582.  
  10583.     b2Vec2 r(m_radius, m_radius);
  10584.     aabb->lowerBound = lower - r;
  10585.     aabb->upperBound = upper + r;
  10586. }
  10587.  
  10588. void b2PolygonShape::ComputeMass(b2MassData* massData, float density) const {
  10589.     // Polygon mass, centroid, and inertia.
  10590.     // Let rho be the polygon density in mass per unit area.
  10591.     // Then:
  10592.     // mass = rho * int(dA)
  10593.     // centroid.x = (1/mass) * rho * int(x * dA)
  10594.     // centroid.y = (1/mass) * rho * int(y * dA)
  10595.     // I = rho * int((x*x + y*y) * dA)
  10596.     //
  10597.     // We can compute these integrals by summing all the integrals
  10598.     // for each triangle of the polygon. To evaluate the integral
  10599.     // for a single triangle, we make a change of variables to
  10600.     // the (u,v) coordinates of the triangle:
  10601.     // x = x0 + e1x * u + e2x * v
  10602.     // y = y0 + e1y * u + e2y * v
  10603.     // where 0 <= u && 0 <= v && u + v <= 1.
  10604.     //
  10605.     // We integrate u from [0,1-v] and then v from [0,1].
  10606.     // We also need to use the Jacobian of the transformation:
  10607.     // D = cross(e1, e2)
  10608.     //
  10609.     // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
  10610.     //
  10611.     // The rest of the derivation is handled by computer algebra.
  10612.  
  10613.     b2Assert(m_count >= 3);
  10614.  
  10615.     b2Vec2 center(0.0f, 0.0f);
  10616.     float area = 0.0f;
  10617.     float I = 0.0f;
  10618.  
  10619.     // Get a reference point for forming triangles.
  10620.     // Use the first vertex to reduce round-off errors.
  10621.     b2Vec2 s = m_vertices[0];
  10622.  
  10623.     const float k_inv3 = 1.0f / 3.0f;
  10624.  
  10625.     for (int32 i = 0; i < m_count; ++i) {
  10626.         // Triangle vertices.
  10627.         b2Vec2 e1 = m_vertices[i] - s;
  10628.         b2Vec2 e2 = i + 1 < m_count ? m_vertices[i + 1] - s : m_vertices[0] - s;
  10629.  
  10630.         float D = b2Cross(e1, e2);
  10631.  
  10632.         float triangleArea = 0.5f * D;
  10633.         area += triangleArea;
  10634.  
  10635.         // Area weighted centroid
  10636.         center += triangleArea * k_inv3 * (e1 + e2);
  10637.  
  10638.         float ex1 = e1.x, ey1 = e1.y;
  10639.         float ex2 = e2.x, ey2 = e2.y;
  10640.  
  10641.         float intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
  10642.         float inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
  10643.  
  10644.         I += (0.25f * k_inv3 * D) * (intx2 + inty2);
  10645.     }
  10646.  
  10647.     // Total mass
  10648.     massData->mass = density * area;
  10649.  
  10650.     // Center of mass
  10651.     b2Assert(area > b2_epsilon);
  10652.     center *= 1.0f / area;
  10653.     massData->center = center + s;
  10654.  
  10655.     // Inertia tensor relative to the local origin (point s).
  10656.     massData->I = density * I;
  10657.  
  10658.     // Shift to center of mass then to original body origin.
  10659.     massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
  10660. }
  10661.  
  10662. bool b2PolygonShape::Validate() const {
  10663.     for (int32 i = 0; i < m_count; ++i) {
  10664.         int32 i1 = i;
  10665.         int32 i2 = i < m_count - 1 ? i1 + 1 : 0;
  10666.         b2Vec2 p = m_vertices[i1];
  10667.         b2Vec2 e = m_vertices[i2] - p;
  10668.  
  10669.         for (int32 j = 0; j < m_count; ++j) {
  10670.             if (j == i1 || j == i2) {
  10671.                 continue;
  10672.             }
  10673.  
  10674.             b2Vec2 v = m_vertices[j] - p;
  10675.             float c = b2Cross(e, v);
  10676.             if (c < 0.0f) {
  10677.                 return false;
  10678.             }
  10679.         }
  10680.     }
  10681.  
  10682.     return true;
  10683. }
  10684. // MIT License
  10685.  
  10686. // Copyright (c) 2019 Erin Catto
  10687.  
  10688. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10689. // of this software and associated documentation files (the "Software"), to deal
  10690. // in the Software without restriction, including without limitation the rights
  10691. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10692. // copies of the Software, and to permit persons to whom the Software is
  10693. // furnished to do so, subject to the following conditions:
  10694.  
  10695. // The above copyright notice and this permission notice shall be included in all
  10696. // copies or substantial portions of the Software.
  10697.  
  10698. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  10699. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  10700. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  10701. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  10702. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  10703. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  10704. // SOFTWARE.
  10705.  
  10706. //#include "box2d/b2_collision.h"
  10707. //#include "box2d/b2_distance.h"
  10708. //#include "box2d/b2_circle_shape.h"
  10709. //#include "box2d/b2_polygon_shape.h"
  10710. //#include "box2d/b2_time_of_impact.h"
  10711. //#include "box2d/b2_timer.h"
  10712.  
  10713. #include <stdio.h>
  10714.  
  10715. B2_API float b2_toiTime, b2_toiMaxTime;
  10716. B2_API int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters;
  10717. B2_API int32 b2_toiRootIters, b2_toiMaxRootIters;
  10718.  
  10719. //
  10720. struct b2SeparationFunction {
  10721.     enum Type {
  10722.         e_points,
  10723.         e_faceA,
  10724.         e_faceB
  10725.     };
  10726.  
  10727.     // TODO_ERIN might not need to return the separation
  10728.  
  10729.     float Initialize(const b2SimplexCache* cache,
  10730.         const b2DistanceProxy* proxyA, const b2Sweep& sweepA,
  10731.         const b2DistanceProxy* proxyB, const b2Sweep& sweepB,
  10732.         float t1) {
  10733.         m_proxyA = proxyA;
  10734.         m_proxyB = proxyB;
  10735.         int32 count = cache->count;
  10736.         b2Assert(0 < count && count < 3);
  10737.  
  10738.         m_sweepA = sweepA;
  10739.         m_sweepB = sweepB;
  10740.  
  10741.         b2Transform xfA, xfB;
  10742.         m_sweepA.GetTransform(&xfA, t1);
  10743.         m_sweepB.GetTransform(&xfB, t1);
  10744.  
  10745.         if (count == 1) {
  10746.             m_type = e_points;
  10747.             b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]);
  10748.             b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]);
  10749.             b2Vec2 pointA = b2Mul(xfA, localPointA);
  10750.             b2Vec2 pointB = b2Mul(xfB, localPointB);
  10751.             m_axis = pointB - pointA;
  10752.             float s = m_axis.Normalize();
  10753.             return s;
  10754.         } else if (cache->indexA[0] == cache->indexA[1]) {
  10755.             // Two points on B and one on A.
  10756.             m_type = e_faceB;
  10757.             b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]);
  10758.             b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]);
  10759.  
  10760.             m_axis = b2Cross(localPointB2 - localPointB1, 1.0f);
  10761.             m_axis.Normalize();
  10762.             b2Vec2 normal = b2Mul(xfB.q, m_axis);
  10763.  
  10764.             m_localPoint = 0.5f * (localPointB1 + localPointB2);
  10765.             b2Vec2 pointB = b2Mul(xfB, m_localPoint);
  10766.  
  10767.             b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]);
  10768.             b2Vec2 pointA = b2Mul(xfA, localPointA);
  10769.  
  10770.             float s = b2Dot(pointA - pointB, normal);
  10771.             if (s < 0.0f) {
  10772.                 m_axis = -m_axis;
  10773.                 s = -s;
  10774.             }
  10775.             return s;
  10776.         } else {
  10777.             // Two points on A and one or two points on B.
  10778.             m_type = e_faceA;
  10779.             b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]);
  10780.             b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]);
  10781.  
  10782.             m_axis = b2Cross(localPointA2 - localPointA1, 1.0f);
  10783.             m_axis.Normalize();
  10784.             b2Vec2 normal = b2Mul(xfA.q, m_axis);
  10785.  
  10786.             m_localPoint = 0.5f * (localPointA1 + localPointA2);
  10787.             b2Vec2 pointA = b2Mul(xfA, m_localPoint);
  10788.  
  10789.             b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]);
  10790.             b2Vec2 pointB = b2Mul(xfB, localPointB);
  10791.  
  10792.             float s = b2Dot(pointB - pointA, normal);
  10793.             if (s < 0.0f) {
  10794.                 m_axis = -m_axis;
  10795.                 s = -s;
  10796.             }
  10797.             return s;
  10798.         }
  10799.     }
  10800.  
  10801.     //
  10802.     float FindMinSeparation(int32* indexA, int32* indexB, float t) const {
  10803.         b2Transform xfA, xfB;
  10804.         m_sweepA.GetTransform(&xfA, t);
  10805.         m_sweepB.GetTransform(&xfB, t);
  10806.  
  10807.         switch (m_type) {
  10808.         case e_points:
  10809.         {
  10810.             b2Vec2 axisA = b2MulT(xfA.q, m_axis);
  10811.             b2Vec2 axisB = b2MulT(xfB.q, -m_axis);
  10812.  
  10813.             *indexA = m_proxyA->GetSupport(axisA);
  10814.             *indexB = m_proxyB->GetSupport(axisB);
  10815.  
  10816.             b2Vec2 localPointA = m_proxyA->GetVertex(*indexA);
  10817.             b2Vec2 localPointB = m_proxyB->GetVertex(*indexB);
  10818.  
  10819.             b2Vec2 pointA = b2Mul(xfA, localPointA);
  10820.             b2Vec2 pointB = b2Mul(xfB, localPointB);
  10821.  
  10822.             float separation = b2Dot(pointB - pointA, m_axis);
  10823.             return separation;
  10824.         }
  10825.  
  10826.         case e_faceA:
  10827.         {
  10828.             b2Vec2 normal = b2Mul(xfA.q, m_axis);
  10829.             b2Vec2 pointA = b2Mul(xfA, m_localPoint);
  10830.  
  10831.             b2Vec2 axisB = b2MulT(xfB.q, -normal);
  10832.  
  10833.             *indexA = -1;
  10834.             *indexB = m_proxyB->GetSupport(axisB);
  10835.  
  10836.             b2Vec2 localPointB = m_proxyB->GetVertex(*indexB);
  10837.             b2Vec2 pointB = b2Mul(xfB, localPointB);
  10838.  
  10839.             float separation = b2Dot(pointB - pointA, normal);
  10840.             return separation;
  10841.         }
  10842.  
  10843.         case e_faceB:
  10844.         {
  10845.             b2Vec2 normal = b2Mul(xfB.q, m_axis);
  10846.             b2Vec2 pointB = b2Mul(xfB, m_localPoint);
  10847.  
  10848.             b2Vec2 axisA = b2MulT(xfA.q, -normal);
  10849.  
  10850.             *indexB = -1;
  10851.             *indexA = m_proxyA->GetSupport(axisA);
  10852.  
  10853.             b2Vec2 localPointA = m_proxyA->GetVertex(*indexA);
  10854.             b2Vec2 pointA = b2Mul(xfA, localPointA);
  10855.  
  10856.             float separation = b2Dot(pointA - pointB, normal);
  10857.             return separation;
  10858.         }
  10859.  
  10860.         default:
  10861.             b2Assert(false);
  10862.             *indexA = -1;
  10863.             *indexB = -1;
  10864.             return 0.0f;
  10865.         }
  10866.     }
  10867.  
  10868.     //
  10869.     float Evaluate(int32 indexA, int32 indexB, float t) const {
  10870.         b2Transform xfA, xfB;
  10871.         m_sweepA.GetTransform(&xfA, t);
  10872.         m_sweepB.GetTransform(&xfB, t);
  10873.  
  10874.         switch (m_type) {
  10875.         case e_points:
  10876.         {
  10877.             b2Vec2 localPointA = m_proxyA->GetVertex(indexA);
  10878.             b2Vec2 localPointB = m_proxyB->GetVertex(indexB);
  10879.  
  10880.             b2Vec2 pointA = b2Mul(xfA, localPointA);
  10881.             b2Vec2 pointB = b2Mul(xfB, localPointB);
  10882.             float separation = b2Dot(pointB - pointA, m_axis);
  10883.  
  10884.             return separation;
  10885.         }
  10886.  
  10887.         case e_faceA:
  10888.         {
  10889.             b2Vec2 normal = b2Mul(xfA.q, m_axis);
  10890.             b2Vec2 pointA = b2Mul(xfA, m_localPoint);
  10891.  
  10892.             b2Vec2 localPointB = m_proxyB->GetVertex(indexB);
  10893.             b2Vec2 pointB = b2Mul(xfB, localPointB);
  10894.  
  10895.             float separation = b2Dot(pointB - pointA, normal);
  10896.             return separation;
  10897.         }
  10898.  
  10899.         case e_faceB:
  10900.         {
  10901.             b2Vec2 normal = b2Mul(xfB.q, m_axis);
  10902.             b2Vec2 pointB = b2Mul(xfB, m_localPoint);
  10903.  
  10904.             b2Vec2 localPointA = m_proxyA->GetVertex(indexA);
  10905.             b2Vec2 pointA = b2Mul(xfA, localPointA);
  10906.  
  10907.             float separation = b2Dot(pointA - pointB, normal);
  10908.             return separation;
  10909.         }
  10910.  
  10911.         default:
  10912.             b2Assert(false);
  10913.             return 0.0f;
  10914.         }
  10915.     }
  10916.  
  10917.     const b2DistanceProxy* m_proxyA;
  10918.     const b2DistanceProxy* m_proxyB;
  10919.     b2Sweep m_sweepA, m_sweepB;
  10920.     Type m_type;
  10921.     b2Vec2 m_localPoint;
  10922.     b2Vec2 m_axis;
  10923. };
  10924.  
  10925. // CCD via the local separating axis method. This seeks progression
  10926. // by computing the largest time at which separation is maintained.
  10927. void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) {
  10928.     b2Timer timer;
  10929.  
  10930.     ++b2_toiCalls;
  10931.  
  10932.     output->state = b2TOIOutput::e_unknown;
  10933.     output->t = input->tMax;
  10934.  
  10935.     const b2DistanceProxy* proxyA = &input->proxyA;
  10936.     const b2DistanceProxy* proxyB = &input->proxyB;
  10937.  
  10938.     b2Sweep sweepA = input->sweepA;
  10939.     b2Sweep sweepB = input->sweepB;
  10940.  
  10941.     // Large rotations can make the root finder fail, so we normalize the
  10942.     // sweep angles.
  10943.     sweepA.Normalize();
  10944.     sweepB.Normalize();
  10945.  
  10946.     float tMax = input->tMax;
  10947.  
  10948.     float totalRadius = proxyA->m_radius + proxyB->m_radius;
  10949.     float target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop);
  10950.     float tolerance = 0.25f * b2_linearSlop;
  10951.     b2Assert(target > tolerance);
  10952.  
  10953.     float t1 = 0.0f;
  10954.     const int32 k_maxIterations = 20;   // TODO_ERIN b2Settings
  10955.     int32 iter = 0;
  10956.  
  10957.     // Prepare input for distance query.
  10958.     b2SimplexCache cache;
  10959.     cache.count = 0;
  10960.     b2DistanceInput distanceInput;
  10961.     distanceInput.proxyA = input->proxyA;
  10962.     distanceInput.proxyB = input->proxyB;
  10963.     distanceInput.useRadii = false;
  10964.  
  10965.     // The outer loop progressively attempts to compute new separating axes.
  10966.     // This loop terminates when an axis is repeated (no progress is made).
  10967.     for (;;) {
  10968.         b2Transform xfA, xfB;
  10969.         sweepA.GetTransform(&xfA, t1);
  10970.         sweepB.GetTransform(&xfB, t1);
  10971.  
  10972.         // Get the distance between shapes. We can also use the results
  10973.         // to get a separating axis.
  10974.         distanceInput.transformA = xfA;
  10975.         distanceInput.transformB = xfB;
  10976.         b2DistanceOutput distanceOutput;
  10977.         b2Distance(&distanceOutput, &cache, &distanceInput);
  10978.  
  10979.         // If the shapes are overlapped, we give up on continuous collision.
  10980.         if (distanceOutput.distance <= 0.0f) {
  10981.             // Failure!
  10982.             output->state = b2TOIOutput::e_overlapped;
  10983.             output->t = 0.0f;
  10984.             break;
  10985.         }
  10986.  
  10987.         if (distanceOutput.distance < target + tolerance) {
  10988.             // Victory!
  10989.             output->state = b2TOIOutput::e_touching;
  10990.             output->t = t1;
  10991.             break;
  10992.         }
  10993.  
  10994.         // Initialize the separating axis.
  10995.         b2SeparationFunction fcn;
  10996.         fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1);
  10997. #if 0
  10998.         // Dump the curve seen by the root finder
  10999.         {
  11000.             const int32 N = 100;
  11001.             float dx = 1.0f / N;
  11002.             float xs[N + 1];
  11003.             float fs[N + 1];
  11004.  
  11005.             float x = 0.0f;
  11006.  
  11007.             for (int32 i = 0; i <= N; ++i) {
  11008.                 sweepA.GetTransform(&xfA, x);
  11009.                 sweepB.GetTransform(&xfB, x);
  11010.                 float f = fcn.Evaluate(xfA, xfB) - target;
  11011.  
  11012.                 printf("%g %g\n", x, f);
  11013.  
  11014.                 xs[i] = x;
  11015.                 fs[i] = f;
  11016.  
  11017.                 x += dx;
  11018.             }
  11019.         }
  11020. #endif
  11021.  
  11022.         // Compute the TOI on the separating axis. We do this by successively
  11023.         // resolving the deepest point. This loop is bounded by the number of vertices.
  11024.         bool done = false;
  11025.         float t2 = tMax;
  11026.         int32 pushBackIter = 0;
  11027.         for (;;) {
  11028.             // Find the deepest point at t2. Store the witness point indices.
  11029.             int32 indexA, indexB;
  11030.             float s2 = fcn.FindMinSeparation(&indexA, &indexB, t2);
  11031.  
  11032.             // Is the final configuration separated?
  11033.             if (s2 > target + tolerance) {
  11034.                 // Victory!
  11035.                 output->state = b2TOIOutput::e_separated;
  11036.                 output->t = tMax;
  11037.                 done = true;
  11038.                 break;
  11039.             }
  11040.  
  11041.             // Has the separation reached tolerance?
  11042.             if (s2 > target - tolerance) {
  11043.                 // Advance the sweeps
  11044.                 t1 = t2;
  11045.                 break;
  11046.             }
  11047.  
  11048.             // Compute the initial separation of the witness points.
  11049.             float s1 = fcn.Evaluate(indexA, indexB, t1);
  11050.  
  11051.             // Check for initial overlap. This might happen if the root finder
  11052.             // runs out of iterations.
  11053.             if (s1 < target - tolerance) {
  11054.                 output->state = b2TOIOutput::e_failed;
  11055.                 output->t = t1;
  11056.                 done = true;
  11057.                 break;
  11058.             }
  11059.  
  11060.             // Check for touching
  11061.             if (s1 <= target + tolerance) {
  11062.                 // Victory! t1 should hold the TOI (could be 0.0).
  11063.                 output->state = b2TOIOutput::e_touching;
  11064.                 output->t = t1;
  11065.                 done = true;
  11066.                 break;
  11067.             }
  11068.  
  11069.             // Compute 1D root of: f(x) - target = 0
  11070.             int32 rootIterCount = 0;
  11071.             float a1 = t1, a2 = t2;
  11072.             for (;;) {
  11073.                 // Use a mix of the secant rule and bisection.
  11074.                 float t;
  11075.                 if (rootIterCount & 1) {
  11076.                     // Secant rule to improve convergence.
  11077.                     t = a1 + (target - s1) * (a2 - a1) / (s2 - s1);
  11078.                 } else {
  11079.                     // Bisection to guarantee progress.
  11080.                     t = 0.5f * (a1 + a2);
  11081.                 }
  11082.  
  11083.                 ++rootIterCount;
  11084.                 ++b2_toiRootIters;
  11085.  
  11086.                 float s = fcn.Evaluate(indexA, indexB, t);
  11087.  
  11088.                 if (b2Abs(s - target) < tolerance) {
  11089.                     // t2 holds a tentative value for t1
  11090.                     t2 = t;
  11091.                     break;
  11092.                 }
  11093.  
  11094.                 // Ensure we continue to bracket the root.
  11095.                 if (s > target) {
  11096.                     a1 = t;
  11097.                     s1 = s;
  11098.                 } else {
  11099.                     a2 = t;
  11100.                     s2 = s;
  11101.                 }
  11102.  
  11103.                 if (rootIterCount == 50) {
  11104.                     break;
  11105.                 }
  11106.             }
  11107.  
  11108.             b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount);
  11109.  
  11110.             ++pushBackIter;
  11111.  
  11112.             if (pushBackIter == b2_maxPolygonVertices) {
  11113.                 break;
  11114.             }
  11115.         }
  11116.  
  11117.         ++iter;
  11118.         ++b2_toiIters;
  11119.  
  11120.         if (done) {
  11121.             break;
  11122.         }
  11123.  
  11124.         if (iter == k_maxIterations) {
  11125.             // Root finder got stuck. Semi-victory.
  11126.             output->state = b2TOIOutput::e_failed;
  11127.             output->t = t1;
  11128.             break;
  11129.         }
  11130.     }
  11131.  
  11132.     b2_toiMaxIters = b2Max(b2_toiMaxIters, iter);
  11133.  
  11134.     float time = timer.GetMilliseconds();
  11135.     b2_toiMaxTime = b2Max(b2_toiMaxTime, time);
  11136.     b2_toiTime += time;
  11137. }
  11138. // MIT License
  11139.  
  11140. // Copyright (c) 2019 Erin Catto
  11141.  
  11142. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11143. // of this software and associated documentation files (the "Software"), to deal
  11144. // in the Software without restriction, including without limitation the rights
  11145. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11146. // copies of the Software, and to permit persons to whom the Software is
  11147. // furnished to do so, subject to the following conditions:
  11148.  
  11149. // The above copyright notice and this permission notice shall be included in all
  11150. // copies or substantial portions of the Software.
  11151.  
  11152. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11153. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11154. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11155. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11156. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11157. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  11158. // SOFTWARE.
  11159.  
  11160. //#include "box2d/b2_block_allocator.h"
  11161. #include <limits.h>
  11162. #include <string.h>
  11163. #include <stddef.h>
  11164.  
  11165. static const int32 b2_chunkSize = 16 * 1024;
  11166. static const int32 b2_maxBlockSize = 640;
  11167. static const int32 b2_chunkArrayIncrement = 128;
  11168.  
  11169. // These are the supported object sizes. Actual allocations are rounded up the next size.
  11170. static const int32 b2_blockSizes[b2_blockSizeCount] =
  11171. {
  11172.     16,     // 0
  11173.     32,     // 1
  11174.     64,     // 2
  11175.     96,     // 3
  11176.     128,    // 4
  11177.     160,    // 5
  11178.     192,    // 6
  11179.     224,    // 7
  11180.     256,    // 8
  11181.     320,    // 9
  11182.     384,    // 10
  11183.     448,    // 11
  11184.     512,    // 12
  11185.     640,    // 13
  11186. };
  11187.  
  11188. // This maps an arbitrary allocation size to a suitable slot in b2_blockSizes.
  11189. struct b2SizeMap {
  11190.     b2SizeMap() {
  11191.         int32 j = 0;
  11192.         values[0] = 0;
  11193.         for (int32 i = 1; i <= b2_maxBlockSize; ++i) {
  11194.             b2Assert(j < b2_blockSizeCount);
  11195.             if (i <= b2_blockSizes[j]) {
  11196.                 values[i] = (uint8)j;
  11197.             } else {
  11198.                 ++j;
  11199.                 values[i] = (uint8)j;
  11200.             }
  11201.         }
  11202.     }
  11203.  
  11204.     uint8 values[b2_maxBlockSize + 1];
  11205. };
  11206.  
  11207. static const b2SizeMap b2_sizeMap;
  11208.  
  11209. struct b2Chunk {
  11210.     int32 blockSize;
  11211.     b2Block* blocks;
  11212. };
  11213.  
  11214. struct b2Block {
  11215.     b2Block* next;
  11216. };
  11217.  
  11218. b2BlockAllocator::b2BlockAllocator() {
  11219.     b2Assert(b2_blockSizeCount < UCHAR_MAX);
  11220.  
  11221.     m_chunkSpace = b2_chunkArrayIncrement;
  11222.     m_chunkCount = 0;
  11223.     m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
  11224.  
  11225.     memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
  11226.     memset(m_freeLists, 0, sizeof(m_freeLists));
  11227. }
  11228.  
  11229. b2BlockAllocator::~b2BlockAllocator() {
  11230.     for (int32 i = 0; i < m_chunkCount; ++i) {
  11231.         b2Free(m_chunks[i].blocks);
  11232.     }
  11233.  
  11234.     b2Free(m_chunks);
  11235. }
  11236.  
  11237. void* b2BlockAllocator::Allocate(int32 size) {
  11238.     if (size == 0) {
  11239.         return nullptr;
  11240.     }
  11241.  
  11242.     b2Assert(0 < size);
  11243.  
  11244.     if (size > b2_maxBlockSize) {
  11245.         return b2Alloc(size);
  11246.     }
  11247.  
  11248.     int32 index = b2_sizeMap.values[size];
  11249.     b2Assert(0 <= index && index < b2_blockSizeCount);
  11250.  
  11251.     if (m_freeLists[index]) {
  11252.         b2Block* block = m_freeLists[index];
  11253.         m_freeLists[index] = block->next;
  11254.         return block;
  11255.     } else {
  11256.         if (m_chunkCount == m_chunkSpace) {
  11257.             b2Chunk* oldChunks = m_chunks;
  11258.             m_chunkSpace += b2_chunkArrayIncrement;
  11259.             m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
  11260.             memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk));
  11261.             memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk));
  11262.             b2Free(oldChunks);
  11263.         }
  11264.  
  11265.         b2Chunk* chunk = m_chunks + m_chunkCount;
  11266.         chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize);
  11267. #if defined(_DEBUG)
  11268.         memset(chunk->blocks, 0xcd, b2_chunkSize);
  11269. #endif
  11270.         int32 blockSize = b2_blockSizes[index];
  11271.         chunk->blockSize = blockSize;
  11272.         int32 blockCount = b2_chunkSize / blockSize;
  11273.         b2Assert(blockCount * blockSize <= b2_chunkSize);
  11274.         for (int32 i = 0; i < blockCount - 1; ++i) {
  11275.             b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i);
  11276.             b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1));
  11277.             block->next = next;
  11278.         }
  11279.         b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1));
  11280.         last->next = nullptr;
  11281.  
  11282.         m_freeLists[index] = chunk->blocks->next;
  11283.         ++m_chunkCount;
  11284.  
  11285.         return chunk->blocks;
  11286.     }
  11287. }
  11288.  
  11289. void b2BlockAllocator::Free(void* p, int32 size) {
  11290.     if (size == 0) {
  11291.         return;
  11292.     }
  11293.  
  11294.     b2Assert(0 < size);
  11295.  
  11296.     if (size > b2_maxBlockSize) {
  11297.         b2Free(p);
  11298.         return;
  11299.     }
  11300.  
  11301.     int32 index = b2_sizeMap.values[size];
  11302.     b2Assert(0 <= index && index < b2_blockSizeCount);
  11303.  
  11304. #if defined(_DEBUG)
  11305.     // Verify the memory address and size is valid.
  11306.     int32 blockSize = b2_blockSizes[index];
  11307.     bool found = false;
  11308.     for (int32 i = 0; i < m_chunkCount; ++i) {
  11309.         b2Chunk* chunk = m_chunks + i;
  11310.         if (chunk->blockSize != blockSize) {
  11311.             b2Assert((int8*)p + blockSize <= (int8*)chunk->blocks ||
  11312.                 (int8*)chunk->blocks + b2_chunkSize <= (int8*)p);
  11313.         } else {
  11314.             if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) {
  11315.                 found = true;
  11316.             }
  11317.         }
  11318.     }
  11319.  
  11320.     b2Assert(found);
  11321.  
  11322.     memset(p, 0xfd, blockSize);
  11323. #endif
  11324.  
  11325.     b2Block* block = (b2Block*)p;
  11326.     block->next = m_freeLists[index];
  11327.     m_freeLists[index] = block;
  11328. }
  11329.  
  11330. void b2BlockAllocator::Clear() {
  11331.     for (int32 i = 0; i < m_chunkCount; ++i) {
  11332.         b2Free(m_chunks[i].blocks);
  11333.     }
  11334.  
  11335.     m_chunkCount = 0;
  11336.     memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
  11337.     memset(m_freeLists, 0, sizeof(m_freeLists));
  11338. }
  11339. // MIT License
  11340.  
  11341. // Copyright (c) 2019 Erin Catto
  11342.  
  11343. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11344. // of this software and associated documentation files (the "Software"), to deal
  11345. // in the Software without restriction, including without limitation the rights
  11346. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11347. // copies of the Software, and to permit persons to whom the Software is
  11348. // furnished to do so, subject to the following conditions:
  11349.  
  11350. // The above copyright notice and this permission notice shall be included in all
  11351. // copies or substantial portions of the Software.
  11352.  
  11353. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11354. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11355. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11356. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11357. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11358. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  11359. // SOFTWARE.
  11360. //#include "box2d/b2_draw.h"
  11361.  
  11362. b2Draw::b2Draw() {
  11363.     m_drawFlags = 0;
  11364. }
  11365.  
  11366. void b2Draw::SetFlags(uint32 flags) {
  11367.     m_drawFlags = flags;
  11368. }
  11369.  
  11370. uint32 b2Draw::GetFlags() const {
  11371.     return m_drawFlags;
  11372. }
  11373.  
  11374. void b2Draw::AppendFlags(uint32 flags) {
  11375.     m_drawFlags |= flags;
  11376. }
  11377.  
  11378. void b2Draw::ClearFlags(uint32 flags) {
  11379.     m_drawFlags &= ~flags;
  11380. }
  11381. // MIT License
  11382.  
  11383. // Copyright (c) 2019 Erin Catto
  11384.  
  11385. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11386. // of this software and associated documentation files (the "Software"), to deal
  11387. // in the Software without restriction, including without limitation the rights
  11388. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11389. // copies of the Software, and to permit persons to whom the Software is
  11390. // furnished to do so, subject to the following conditions:
  11391.  
  11392. // The above copyright notice and this permission notice shall be included in all
  11393. // copies or substantial portions of the Software.
  11394.  
  11395. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11396. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11397. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11398. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11399. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11400. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  11401. // SOFTWARE.
  11402.  
  11403. //#include "box2d/b2_math.h"
  11404.  
  11405. const b2Vec2 b2Vec2_zero(0.0f, 0.0f);
  11406.  
  11407. /// Solve A * x = b, where b is a column vector. This is more efficient
  11408. /// than computing the inverse in one-shot cases.
  11409. b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const {
  11410.     float det = b2Dot(ex, b2Cross(ey, ez));
  11411.     if (det != 0.0f) {
  11412.         det = 1.0f / det;
  11413.     }
  11414.     b2Vec3 x;
  11415.     x.x = det * b2Dot(b, b2Cross(ey, ez));
  11416.     x.y = det * b2Dot(ex, b2Cross(b, ez));
  11417.     x.z = det * b2Dot(ex, b2Cross(ey, b));
  11418.     return x;
  11419. }
  11420.  
  11421. /// Solve A * x = b, where b is a column vector. This is more efficient
  11422. /// than computing the inverse in one-shot cases.
  11423. b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const {
  11424.     float a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y;
  11425.     float det = a11 * a22 - a12 * a21;
  11426.     if (det != 0.0f) {
  11427.         det = 1.0f / det;
  11428.     }
  11429.     b2Vec2 x;
  11430.     x.x = det * (a22 * b.x - a12 * b.y);
  11431.     x.y = det * (a11 * b.y - a21 * b.x);
  11432.     return x;
  11433. }
  11434.  
  11435. ///
  11436. void b2Mat33::GetInverse22(b2Mat33* M) const {
  11437.     float a = ex.x, b = ey.x, c = ex.y, d = ey.y;
  11438.     float det = a * d - b * c;
  11439.     if (det != 0.0f) {
  11440.         det = 1.0f / det;
  11441.     }
  11442.  
  11443.     M->ex.x = det * d;  M->ey.x = -det * b; M->ex.z = 0.0f;
  11444.     M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f;
  11445.     M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f;
  11446. }
  11447.  
  11448. /// Returns the zero matrix if singular.
  11449. void b2Mat33::GetSymInverse33(b2Mat33* M) const {
  11450.     float det = b2Dot(ex, b2Cross(ey, ez));
  11451.     if (det != 0.0f) {
  11452.         det = 1.0f / det;
  11453.     }
  11454.  
  11455.     float a11 = ex.x, a12 = ey.x, a13 = ez.x;
  11456.     float a22 = ey.y, a23 = ez.y;
  11457.     float a33 = ez.z;
  11458.  
  11459.     M->ex.x = det * (a22 * a33 - a23 * a23);
  11460.     M->ex.y = det * (a13 * a23 - a12 * a33);
  11461.     M->ex.z = det * (a12 * a23 - a13 * a22);
  11462.  
  11463.     M->ey.x = M->ex.y;
  11464.     M->ey.y = det * (a11 * a33 - a13 * a13);
  11465.     M->ey.z = det * (a13 * a12 - a11 * a23);
  11466.  
  11467.     M->ez.x = M->ex.z;
  11468.     M->ez.y = M->ey.z;
  11469.     M->ez.z = det * (a11 * a22 - a12 * a12);
  11470. }
  11471. // MIT License
  11472.  
  11473. // Copyright (c) 2019 Erin Catto
  11474.  
  11475. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11476. // of this software and associated documentation files (the "Software"), to deal
  11477. // in the Software without restriction, including without limitation the rights
  11478. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11479. // copies of the Software, and to permit persons to whom the Software is
  11480. // furnished to do so, subject to the following conditions:
  11481.  
  11482. // The above copyright notice and this permission notice shall be included in all
  11483. // copies or substantial portions of the Software.
  11484.  
  11485. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11486. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11487. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11488. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11489. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11490. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  11491. // SOFTWARE.
  11492.  
  11493. #define _CRT_SECURE_NO_WARNINGS
  11494.  
  11495. //#include "box2d/b2_settings.h"
  11496. #include <stdio.h>
  11497. #include <stdarg.h>
  11498. #include <stdlib.h>
  11499.  
  11500. b2Version b2_version = { 2, 4, 0 };
  11501.  
  11502. // Memory allocators. Modify these to use your own allocator.
  11503. void* b2Alloc_Default(int32 size) {
  11504.     return malloc(size);
  11505. }
  11506.  
  11507. void b2Free_Default(void* mem) {
  11508.     free(mem);
  11509. }
  11510.  
  11511. // You can modify this to use your logging facility.
  11512. void b2Log_Default(const char* string, va_list args) {
  11513.     vprintf(string, args);
  11514. }
  11515.  
  11516. FILE* b2_dumpFile = nullptr;
  11517.  
  11518. void b2OpenDump(const char* fileName) {
  11519.     b2Assert(b2_dumpFile == nullptr);
  11520.     b2_dumpFile = fopen(fileName, "w");
  11521. }
  11522.  
  11523. void b2Dump(const char* string, ...) {
  11524.     if (b2_dumpFile == nullptr) {
  11525.         return;
  11526.     }
  11527.  
  11528.     va_list args;
  11529.     va_start(args, string);
  11530.     vfprintf(b2_dumpFile, string, args);
  11531.     va_end(args);
  11532. }
  11533.  
  11534. void b2CloseDump() {
  11535.     fclose(b2_dumpFile);
  11536.     b2_dumpFile = nullptr;
  11537. }
  11538. // MIT License
  11539.  
  11540. // Copyright (c) 2019 Erin Catto
  11541.  
  11542. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11543. // of this software and associated documentation files (the "Software"), to deal
  11544. // in the Software without restriction, including without limitation the rights
  11545. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11546. // copies of the Software, and to permit persons to whom the Software is
  11547. // furnished to do so, subject to the following conditions:
  11548.  
  11549. // The above copyright notice and this permission notice shall be included in all
  11550. // copies or substantial portions of the Software.
  11551.  
  11552. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11553. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11554. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11555. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11556. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11557. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  11558. // SOFTWARE.
  11559.  
  11560. //#include "box2d/b2_stack_allocator.h"
  11561. //#include "box2d/b2_math.h"
  11562.  
  11563. b2StackAllocator::b2StackAllocator() {
  11564.     m_index = 0;
  11565.     m_allocation = 0;
  11566.     m_maxAllocation = 0;
  11567.     m_entryCount = 0;
  11568. }
  11569.  
  11570. b2StackAllocator::~b2StackAllocator() {
  11571.     b2Assert(m_index == 0);
  11572.     b2Assert(m_entryCount == 0);
  11573. }
  11574.  
  11575. void* b2StackAllocator::Allocate(int32 size) {
  11576.     b2Assert(m_entryCount < b2_maxStackEntries);
  11577.  
  11578.     b2StackEntry* entry = m_entries + m_entryCount;
  11579.     entry->size = size;
  11580.     if (m_index + size > b2_stackSize) {
  11581.         entry->data = (char*)b2Alloc(size);
  11582.         entry->usedMalloc = true;
  11583.     } else {
  11584.         entry->data = m_data + m_index;
  11585.         entry->usedMalloc = false;
  11586.         m_index += size;
  11587.     }
  11588.  
  11589.     m_allocation += size;
  11590.     m_maxAllocation = b2Max(m_maxAllocation, m_allocation);
  11591.     ++m_entryCount;
  11592.  
  11593.     return entry->data;
  11594. }
  11595.  
  11596. void b2StackAllocator::Free(void* p) {
  11597.     b2Assert(m_entryCount > 0);
  11598.     b2StackEntry* entry = m_entries + m_entryCount - 1;
  11599.     b2Assert(p == entry->data);
  11600.     if (entry->usedMalloc) {
  11601.         b2Free(p);
  11602.     } else {
  11603.         m_index -= entry->size;
  11604.     }
  11605.     m_allocation -= entry->size;
  11606.     --m_entryCount;
  11607.  
  11608.     p = nullptr;
  11609. }
  11610.  
  11611. int32 b2StackAllocator::GetMaxAllocation() const {
  11612.     return m_maxAllocation;
  11613. }
  11614. // MIT License
  11615.  
  11616. // Copyright (c) 2019 Erin Catto
  11617.  
  11618. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11619. // of this software and associated documentation files (the "Software"), to deal
  11620. // in the Software without restriction, including without limitation the rights
  11621. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11622. // copies of the Software, and to permit persons to whom the Software is
  11623. // furnished to do so, subject to the following conditions:
  11624.  
  11625. // The above copyright notice and this permission notice shall be included in all
  11626. // copies or substantial portions of the Software.
  11627.  
  11628. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11629. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11630. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11631. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11632. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11633. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  11634. // SOFTWARE.
  11635.  
  11636. //#include "box2d/b2_timer.h"
  11637.  
  11638. #if defined(_WIN32)
  11639.  
  11640. double b2Timer::s_invFrequency = 0.0;
  11641.  
  11642. #ifndef WIN32_LEAN_AND_MEAN
  11643. #define WIN32_LEAN_AND_MEAN
  11644. #endif
  11645.  
  11646. #include <windows.h>
  11647.  
  11648. b2Timer::b2Timer() {
  11649.     LARGE_INTEGER largeInteger;
  11650.  
  11651.     if (s_invFrequency == 0.0) {
  11652.         QueryPerformanceFrequency(&largeInteger);
  11653.         s_invFrequency = double(largeInteger.QuadPart);
  11654.         if (s_invFrequency > 0.0) {
  11655.             s_invFrequency = 1000.0 / s_invFrequency;
  11656.         }
  11657.     }
  11658.  
  11659.     QueryPerformanceCounter(&largeInteger);
  11660.     m_start = double(largeInteger.QuadPart);
  11661. }
  11662.  
  11663. void b2Timer::Reset() {
  11664.     LARGE_INTEGER largeInteger;
  11665.     QueryPerformanceCounter(&largeInteger);
  11666.     m_start = double(largeInteger.QuadPart);
  11667. }
  11668.  
  11669. float b2Timer::GetMilliseconds() const {
  11670.     LARGE_INTEGER largeInteger;
  11671.     QueryPerformanceCounter(&largeInteger);
  11672.     double count = double(largeInteger.QuadPart);
  11673.     float ms = float(s_invFrequency * (count - m_start));
  11674.     return ms;
  11675. }
  11676.  
  11677. #elif defined(__linux__) || defined (__APPLE__)
  11678.  
  11679. #include <sys/time.h>
  11680.  
  11681. b2Timer::b2Timer() {
  11682.     Reset();
  11683. }
  11684.  
  11685. void b2Timer::Reset() {
  11686.     timeval t;
  11687.     gettimeofday(&t, 0);
  11688.     m_start_sec = t.tv_sec;
  11689.     m_start_usec = t.tv_usec;
  11690. }
  11691.  
  11692. float b2Timer::GetMilliseconds() const {
  11693.     timeval t;
  11694.     gettimeofday(&t, 0);
  11695.     time_t start_sec = m_start_sec;
  11696.     suseconds_t start_usec = m_start_usec;
  11697.  
  11698.     // http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
  11699.     if (t.tv_usec < start_usec) {
  11700.         int nsec = (start_usec - t.tv_usec) / 1000000 + 1;
  11701.         start_usec -= 1000000 * nsec;
  11702.         start_sec += nsec;
  11703.     }
  11704.  
  11705.     if (t.tv_usec - start_usec > 1000000) {
  11706.         int nsec = (t.tv_usec - start_usec) / 1000000;
  11707.         start_usec += 1000000 * nsec;
  11708.         start_sec -= nsec;
  11709.     }
  11710.     return 1000.0f * (t.tv_sec - start_sec) + 0.001f * (t.tv_usec - start_usec);
  11711. }
  11712.  
  11713. #else
  11714.  
  11715. b2Timer::b2Timer() {
  11716. }
  11717.  
  11718. void b2Timer::Reset() {
  11719. }
  11720.  
  11721. float b2Timer::GetMilliseconds() const {
  11722.     return 0.0f;
  11723. }
  11724.  
  11725. #endif
  11726. // MIT License
  11727.  
  11728. // Copyright (c) 2019 Erin Catto
  11729.  
  11730. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11731. // of this software and associated documentation files (the "Software"), to deal
  11732. // in the Software without restriction, including without limitation the rights
  11733. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11734. // copies of the Software, and to permit persons to whom the Software is
  11735. // furnished to do so, subject to the following conditions:
  11736.  
  11737. // The above copyright notice and this permission notice shall be included in all
  11738. // copies or substantial portions of the Software.
  11739.  
  11740. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11741. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11742. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11743. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11744. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11745. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  11746. // SOFTWARE.
  11747.  
  11748. //#include "box2d/b2_body.h"
  11749. //#include "box2d/b2_contact.h"
  11750. //#include "box2d/b2_fixture.h"
  11751. //#include "box2d/b2_joint.h"
  11752. //#include "box2d/b2_world.h"
  11753.  
  11754. #include <new>
  11755.  
  11756. b2Body::b2Body(const b2BodyDef* bd, b2World* world) {
  11757.     b2Assert(bd->position.IsValid());
  11758.     b2Assert(bd->linearVelocity.IsValid());
  11759.     b2Assert(b2IsValid(bd->angle));
  11760.     b2Assert(b2IsValid(bd->angularVelocity));
  11761.     b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f);
  11762.     b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f);
  11763.  
  11764.     m_flags = 0;
  11765.  
  11766.     if (bd->bullet) {
  11767.         m_flags |= e_bulletFlag;
  11768.     }
  11769.     if (bd->fixedRotation) {
  11770.         m_flags |= e_fixedRotationFlag;
  11771.     }
  11772.     if (bd->allowSleep) {
  11773.         m_flags |= e_autoSleepFlag;
  11774.     }
  11775.     if (bd->awake && bd->type != b2_staticBody) {
  11776.         m_flags |= e_awakeFlag;
  11777.     }
  11778.     if (bd->enabled) {
  11779.         m_flags |= e_enabledFlag;
  11780.     }
  11781.  
  11782.     m_world = world;
  11783.  
  11784.     m_xf.p = bd->position;
  11785.     m_xf.q.Set(bd->angle);
  11786.  
  11787.     m_sweep.localCenter.SetZero();
  11788.     m_sweep.c0 = m_xf.p;
  11789.     m_sweep.c = m_xf.p;
  11790.     m_sweep.a0 = bd->angle;
  11791.     m_sweep.a = bd->angle;
  11792.     m_sweep.alpha0 = 0.0f;
  11793.  
  11794.     m_jointList = nullptr;
  11795.     m_contactList = nullptr;
  11796.     m_prev = nullptr;
  11797.     m_next = nullptr;
  11798.  
  11799.     m_linearVelocity = bd->linearVelocity;
  11800.     m_angularVelocity = bd->angularVelocity;
  11801.  
  11802.     m_linearDamping = bd->linearDamping;
  11803.     m_angularDamping = bd->angularDamping;
  11804.     m_gravityScale = bd->gravityScale;
  11805.  
  11806.     m_force.SetZero();
  11807.     m_torque = 0.0f;
  11808.  
  11809.     m_sleepTime = 0.0f;
  11810.  
  11811.     m_type = bd->type;
  11812.  
  11813.     m_mass = 0.0f;
  11814.     m_invMass = 0.0f;
  11815.  
  11816.     m_I = 0.0f;
  11817.     m_invI = 0.0f;
  11818.  
  11819.     m_userData = bd->userData;
  11820.  
  11821.     m_fixtureList = nullptr;
  11822.     m_fixtureCount = 0;
  11823. }
  11824.  
  11825. b2Body::~b2Body() {
  11826.     // shapes and joints are destroyed in b2World::Destroy
  11827. }
  11828.  
  11829. void b2Body::SetType(b2BodyType type) {
  11830.     b2Assert(m_world->IsLocked() == false);
  11831.     if (m_world->IsLocked() == true) {
  11832.         return;
  11833.     }
  11834.  
  11835.     if (m_type == type) {
  11836.         return;
  11837.     }
  11838.  
  11839.     m_type = type;
  11840.  
  11841.     ResetMassData();
  11842.  
  11843.     if (m_type == b2_staticBody) {
  11844.         m_linearVelocity.SetZero();
  11845.         m_angularVelocity = 0.0f;
  11846.         m_sweep.a0 = m_sweep.a;
  11847.         m_sweep.c0 = m_sweep.c;
  11848.         m_flags &= ~e_awakeFlag;
  11849.         SynchronizeFixtures();
  11850.     }
  11851.  
  11852.     SetAwake(true);
  11853.  
  11854.     m_force.SetZero();
  11855.     m_torque = 0.0f;
  11856.  
  11857.     // Delete the attached contacts.
  11858.     b2ContactEdge* ce = m_contactList;
  11859.     while (ce) {
  11860.         b2ContactEdge* ce0 = ce;
  11861.         ce = ce->next;
  11862.         m_world->m_contactManager.Destroy(ce0->contact);
  11863.     }
  11864.     m_contactList = nullptr;
  11865.  
  11866.     // Touch the proxies so that new contacts will be created (when appropriate)
  11867.     b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
  11868.     for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  11869.         int32 proxyCount = f->m_proxyCount;
  11870.         for (int32 i = 0; i < proxyCount; ++i) {
  11871.             broadPhase->TouchProxy(f->m_proxies[i].proxyId);
  11872.         }
  11873.     }
  11874. }
  11875.  
  11876. b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) {
  11877.     b2Assert(m_world->IsLocked() == false);
  11878.     if (m_world->IsLocked() == true) {
  11879.         return nullptr;
  11880.     }
  11881.  
  11882.     b2BlockAllocator* allocator = &m_world->m_blockAllocator;
  11883.  
  11884.     void* memory = allocator->Allocate(sizeof(b2Fixture));
  11885.     b2Fixture* fixture = new (memory) b2Fixture;
  11886.     fixture->Create(allocator, this, def);
  11887.  
  11888.     if (m_flags & e_enabledFlag) {
  11889.         b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
  11890.         fixture->CreateProxies(broadPhase, m_xf);
  11891.     }
  11892.  
  11893.     fixture->m_next = m_fixtureList;
  11894.     m_fixtureList = fixture;
  11895.     ++m_fixtureCount;
  11896.  
  11897.     fixture->m_body = this;
  11898.  
  11899.     // Adjust mass properties if needed.
  11900.     if (fixture->m_density > 0.0f) {
  11901.         ResetMassData();
  11902.     }
  11903.  
  11904.     // Let the world know we have a new fixture. This will cause new contacts
  11905.     // to be created at the beginning of the next time step.
  11906.     m_world->m_newContacts = true;
  11907.  
  11908.     return fixture;
  11909. }
  11910.  
  11911. b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float density) {
  11912.     b2FixtureDef def;
  11913.     def.shape = shape;
  11914.     def.density = density;
  11915.  
  11916.     return CreateFixture(&def);
  11917. }
  11918.  
  11919. void b2Body::DestroyFixture(b2Fixture* fixture) {
  11920.     if (fixture == NULL) {
  11921.         return;
  11922.     }
  11923.  
  11924.     b2Assert(m_world->IsLocked() == false);
  11925.     if (m_world->IsLocked() == true) {
  11926.         return;
  11927.     }
  11928.  
  11929.     b2Assert(fixture->m_body == this);
  11930.  
  11931.     // Remove the fixture from this body's singly linked list.
  11932.     b2Assert(m_fixtureCount > 0);
  11933.     b2Fixture** node = &m_fixtureList;
  11934.     bool found = false;
  11935.     while (*node != nullptr) {
  11936.         if (*node == fixture) {
  11937.             *node = fixture->m_next;
  11938.             found = true;
  11939.             break;
  11940.         }
  11941.  
  11942.         node = &(*node)->m_next;
  11943.     }
  11944.  
  11945.     // You tried to remove a shape that is not attached to this body.
  11946.     b2Assert(found);
  11947.  
  11948.     // Destroy any contacts associated with the fixture.
  11949.     b2ContactEdge* edge = m_contactList;
  11950.     while (edge) {
  11951.         b2Contact* c = edge->contact;
  11952.         edge = edge->next;
  11953.  
  11954.         b2Fixture* fixtureA = c->GetFixtureA();
  11955.         b2Fixture* fixtureB = c->GetFixtureB();
  11956.  
  11957.         if (fixture == fixtureA || fixture == fixtureB) {
  11958.             // This destroys the contact and removes it from
  11959.             // this body's contact list.
  11960.             m_world->m_contactManager.Destroy(c);
  11961.         }
  11962.     }
  11963.  
  11964.     b2BlockAllocator* allocator = &m_world->m_blockAllocator;
  11965.  
  11966.     if (m_flags & e_enabledFlag) {
  11967.         b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
  11968.         fixture->DestroyProxies(broadPhase);
  11969.     }
  11970.  
  11971.     fixture->m_body = nullptr;
  11972.     fixture->m_next = nullptr;
  11973.     fixture->Destroy(allocator);
  11974.     fixture->~b2Fixture();
  11975.     allocator->Free(fixture, sizeof(b2Fixture));
  11976.  
  11977.     --m_fixtureCount;
  11978.  
  11979.     // Reset the mass data.
  11980.     ResetMassData();
  11981. }
  11982.  
  11983. void b2Body::ResetMassData() {
  11984.     // Compute mass data from shapes. Each shape has its own density.
  11985.     m_mass = 0.0f;
  11986.     m_invMass = 0.0f;
  11987.     m_I = 0.0f;
  11988.     m_invI = 0.0f;
  11989.     m_sweep.localCenter.SetZero();
  11990.  
  11991.     // Static and kinematic bodies have zero mass.
  11992.     if (m_type == b2_staticBody || m_type == b2_kinematicBody) {
  11993.         m_sweep.c0 = m_xf.p;
  11994.         m_sweep.c = m_xf.p;
  11995.         m_sweep.a0 = m_sweep.a;
  11996.         return;
  11997.     }
  11998.  
  11999.     b2Assert(m_type == b2_dynamicBody);
  12000.  
  12001.     // Accumulate mass over all fixtures.
  12002.     b2Vec2 localCenter = b2Vec2_zero;
  12003.     for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  12004.         if (f->m_density == 0.0f) {
  12005.             continue;
  12006.         }
  12007.  
  12008.         b2MassData massData;
  12009.         f->GetMassData(&massData);
  12010.         m_mass += massData.mass;
  12011.         localCenter += massData.mass * massData.center;
  12012.         m_I += massData.I;
  12013.     }
  12014.  
  12015.     // Compute center of mass.
  12016.     if (m_mass > 0.0f) {
  12017.         m_invMass = 1.0f / m_mass;
  12018.         localCenter *= m_invMass;
  12019.     }
  12020.  
  12021.     if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) {
  12022.         // Center the inertia about the center of mass.
  12023.         m_I -= m_mass * b2Dot(localCenter, localCenter);
  12024.         b2Assert(m_I > 0.0f);
  12025.         m_invI = 1.0f / m_I;
  12026.  
  12027.     } else {
  12028.         m_I = 0.0f;
  12029.         m_invI = 0.0f;
  12030.     }
  12031.  
  12032.     // Move center of mass.
  12033.     b2Vec2 oldCenter = m_sweep.c;
  12034.     m_sweep.localCenter = localCenter;
  12035.     m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
  12036.  
  12037.     // Update center of mass velocity.
  12038.     m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter);
  12039. }
  12040.  
  12041. void b2Body::SetMassData(const b2MassData* massData) {
  12042.     b2Assert(m_world->IsLocked() == false);
  12043.     if (m_world->IsLocked() == true) {
  12044.         return;
  12045.     }
  12046.  
  12047.     if (m_type != b2_dynamicBody) {
  12048.         return;
  12049.     }
  12050.  
  12051.     m_invMass = 0.0f;
  12052.     m_I = 0.0f;
  12053.     m_invI = 0.0f;
  12054.  
  12055.     m_mass = massData->mass;
  12056.     if (m_mass <= 0.0f) {
  12057.         m_mass = 1.0f;
  12058.     }
  12059.  
  12060.     m_invMass = 1.0f / m_mass;
  12061.  
  12062.     if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) {
  12063.         m_I = massData->I - m_mass * b2Dot(massData->center, massData->center);
  12064.         b2Assert(m_I > 0.0f);
  12065.         m_invI = 1.0f / m_I;
  12066.     }
  12067.  
  12068.     // Move center of mass.
  12069.     b2Vec2 oldCenter = m_sweep.c;
  12070.     m_sweep.localCenter = massData->center;
  12071.     m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
  12072.  
  12073.     // Update center of mass velocity.
  12074.     m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter);
  12075. }
  12076.  
  12077. bool b2Body::ShouldCollide(const b2Body* other) const {
  12078.     // At least one body should be dynamic.
  12079.     if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) {
  12080.         return false;
  12081.     }
  12082.  
  12083.     // Does a joint prevent collision?
  12084.     for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) {
  12085.         if (jn->other == other) {
  12086.             if (jn->joint->m_collideConnected == false) {
  12087.                 return false;
  12088.             }
  12089.         }
  12090.     }
  12091.  
  12092.     return true;
  12093. }
  12094.  
  12095. void b2Body::SetTransform(const b2Vec2& position, float angle) {
  12096.     b2Assert(m_world->IsLocked() == false);
  12097.     if (m_world->IsLocked() == true) {
  12098.         return;
  12099.     }
  12100.  
  12101.     m_xf.q.Set(angle);
  12102.     m_xf.p = position;
  12103.  
  12104.     m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
  12105.     m_sweep.a = angle;
  12106.  
  12107.     m_sweep.c0 = m_sweep.c;
  12108.     m_sweep.a0 = angle;
  12109.  
  12110.     b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
  12111.     for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  12112.         f->Synchronize(broadPhase, m_xf, m_xf);
  12113.     }
  12114.  
  12115.     // Check for new contacts the next step
  12116.     m_world->m_newContacts = true;
  12117. }
  12118.  
  12119. void b2Body::SynchronizeFixtures() {
  12120.     b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
  12121.  
  12122.     if (m_flags & b2Body::e_awakeFlag) {
  12123.         b2Transform xf1;
  12124.         xf1.q.Set(m_sweep.a0);
  12125.         xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter);
  12126.  
  12127.         for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  12128.             f->Synchronize(broadPhase, xf1, m_xf);
  12129.         }
  12130.     } else {
  12131.         for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  12132.             f->Synchronize(broadPhase, m_xf, m_xf);
  12133.         }
  12134.     }
  12135. }
  12136.  
  12137. void b2Body::SetEnabled(bool flag) {
  12138.     b2Assert(m_world->IsLocked() == false);
  12139.  
  12140.     if (flag == IsEnabled()) {
  12141.         return;
  12142.     }
  12143.  
  12144.     if (flag) {
  12145.         m_flags |= e_enabledFlag;
  12146.  
  12147.         // Create all proxies.
  12148.         b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
  12149.         for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  12150.             f->CreateProxies(broadPhase, m_xf);
  12151.         }
  12152.  
  12153.         // Contacts are created at the beginning of the next
  12154.         m_world->m_newContacts = true;
  12155.     } else {
  12156.         m_flags &= ~e_enabledFlag;
  12157.  
  12158.         // Destroy all proxies.
  12159.         b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
  12160.         for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  12161.             f->DestroyProxies(broadPhase);
  12162.         }
  12163.  
  12164.         // Destroy the attached contacts.
  12165.         b2ContactEdge* ce = m_contactList;
  12166.         while (ce) {
  12167.             b2ContactEdge* ce0 = ce;
  12168.             ce = ce->next;
  12169.             m_world->m_contactManager.Destroy(ce0->contact);
  12170.         }
  12171.         m_contactList = nullptr;
  12172.     }
  12173. }
  12174.  
  12175. void b2Body::SetFixedRotation(bool flag) {
  12176.     bool status = (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
  12177.     if (status == flag) {
  12178.         return;
  12179.     }
  12180.  
  12181.     if (flag) {
  12182.         m_flags |= e_fixedRotationFlag;
  12183.     } else {
  12184.         m_flags &= ~e_fixedRotationFlag;
  12185.     }
  12186.  
  12187.     m_angularVelocity = 0.0f;
  12188.  
  12189.     ResetMassData();
  12190. }
  12191.  
  12192. void b2Body::Dump() {
  12193.     int32 bodyIndex = m_islandIndex;
  12194.  
  12195.     // %.9g is sufficient to save and load the same value using text
  12196.     // FLT_DECIMAL_DIG == 9
  12197.  
  12198.     b2Dump("{\n");
  12199.     b2Dump("  b2BodyDef bd;\n");
  12200.     b2Dump("  bd.type = b2BodyType(%d);\n", m_type);
  12201.     b2Dump("  bd.position.Set(%.9g, %.9g);\n", m_xf.p.x, m_xf.p.y);
  12202.     b2Dump("  bd.angle = %.9g;\n", m_sweep.a);
  12203.     b2Dump("  bd.linearVelocity.Set(%.9g, %.9g);\n", m_linearVelocity.x, m_linearVelocity.y);
  12204.     b2Dump("  bd.angularVelocity = %.9g;\n", m_angularVelocity);
  12205.     b2Dump("  bd.linearDamping = %.9g;\n", m_linearDamping);
  12206.     b2Dump("  bd.angularDamping = %.9g;\n", m_angularDamping);
  12207.     b2Dump("  bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag);
  12208.     b2Dump("  bd.awake = bool(%d);\n", m_flags & e_awakeFlag);
  12209.     b2Dump("  bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag);
  12210.     b2Dump("  bd.bullet = bool(%d);\n", m_flags & e_bulletFlag);
  12211.     b2Dump("  bd.enabled = bool(%d);\n", m_flags & e_enabledFlag);
  12212.     b2Dump("  bd.gravityScale = %.9g;\n", m_gravityScale);
  12213.     b2Dump("  bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex);
  12214.     b2Dump("\n");
  12215.     for (b2Fixture* f = m_fixtureList; f; f = f->m_next) {
  12216.         b2Dump("  {\n");
  12217.         f->Dump(bodyIndex);
  12218.         b2Dump("  }\n");
  12219.     }
  12220.     b2Dump("}\n");
  12221. }
  12222. // MIT License
  12223.  
  12224. // Copyright (c) 2019 Erin Catto
  12225.  
  12226. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12227. // of this software and associated documentation files (the "Software"), to deal
  12228. // in the Software without restriction, including without limitation the rights
  12229. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12230. // copies of the Software, and to permit persons to whom the Software is
  12231. // furnished to do so, subject to the following conditions:
  12232.  
  12233. // The above copyright notice and this permission notice shall be included in all
  12234. // copies or substantial portions of the Software.
  12235.  
  12236. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12237. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12238. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12239. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12240. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12241. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12242. // SOFTWARE.
  12243.  
  12244. //#include "b2_chain_circle_contact.h"
  12245. //#include "box2d/b2_block_allocator.h"
  12246. //#include "box2d/b2_fixture.h"
  12247. //#include "box2d/b2_chain_shape.h"
  12248. //#include "box2d/b2_edge_shape.h"
  12249.  
  12250. #include <new>
  12251.  
  12252. b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) {
  12253.     void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact));
  12254.     return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB);
  12255. }
  12256.  
  12257. void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  12258.     ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact();
  12259.     allocator->Free(contact, sizeof(b2ChainAndCircleContact));
  12260. }
  12261.  
  12262. b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB)
  12263.     : b2Contact(fixtureA, indexA, fixtureB, indexB) {
  12264.     b2Assert(m_fixtureA->GetType() == b2Shape::e_chain);
  12265.     b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
  12266. }
  12267.  
  12268. void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) {
  12269.     b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape();
  12270.     b2EdgeShape edge;
  12271.     chain->GetChildEdge(&edge, m_indexA);
  12272.     b2CollideEdgeAndCircle(manifold, &edge, xfA,
  12273.         (b2CircleShape*)m_fixtureB->GetShape(), xfB);
  12274. }
  12275. // MIT License
  12276.  
  12277. // Copyright (c) 2019 Erin Catto
  12278.  
  12279. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12280. // of this software and associated documentation files (the "Software"), to deal
  12281. // in the Software without restriction, including without limitation the rights
  12282. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12283. // copies of the Software, and to permit persons to whom the Software is
  12284. // furnished to do so, subject to the following conditions:
  12285.  
  12286. // The above copyright notice and this permission notice shall be included in all
  12287. // copies or substantial portions of the Software.
  12288.  
  12289. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12290. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12291. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12292. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12293. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12294. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12295. // SOFTWARE.
  12296.  
  12297. //#include "b2_chain_polygon_contact.h"
  12298. //#include "box2d/b2_block_allocator.h"
  12299. //#include "box2d/b2_fixture.h"
  12300. //#include "box2d/b2_chain_shape.h"
  12301. //#include "box2d/b2_edge_shape.h"
  12302.  
  12303. #include <new>
  12304.  
  12305. b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) {
  12306.     void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact));
  12307.     return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB);
  12308. }
  12309.  
  12310. void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  12311.     ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact();
  12312.     allocator->Free(contact, sizeof(b2ChainAndPolygonContact));
  12313. }
  12314.  
  12315. b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB)
  12316.     : b2Contact(fixtureA, indexA, fixtureB, indexB) {
  12317.     b2Assert(m_fixtureA->GetType() == b2Shape::e_chain);
  12318.     b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
  12319. }
  12320.  
  12321. void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) {
  12322.     b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape();
  12323.     b2EdgeShape edge;
  12324.     chain->GetChildEdge(&edge, m_indexA);
  12325.     b2CollideEdgeAndPolygon(manifold, &edge, xfA,
  12326.         (b2PolygonShape*)m_fixtureB->GetShape(), xfB);
  12327. }
  12328. // MIT License
  12329.  
  12330. // Copyright (c) 2019 Erin Catto
  12331.  
  12332. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12333. // of this software and associated documentation files (the "Software"), to deal
  12334. // in the Software without restriction, including without limitation the rights
  12335. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12336. // copies of the Software, and to permit persons to whom the Software is
  12337. // furnished to do so, subject to the following conditions:
  12338.  
  12339. // The above copyright notice and this permission notice shall be included in all
  12340. // copies or substantial portions of the Software.
  12341.  
  12342. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12343. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12344. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12345. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12346. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12347. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12348. // SOFTWARE.
  12349.  
  12350. //#include "b2_circle_contact.h"
  12351. //#include "box2d/b2_block_allocator.h"
  12352. //#include "box2d/b2_body.h"
  12353. //#include "box2d/b2_fixture.h"
  12354. //#include "box2d/b2_time_of_impact.h"
  12355. //#include "box2d/b2_world_callbacks.h"
  12356.  
  12357. #include <new>
  12358.  
  12359. b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) {
  12360.     void* mem = allocator->Allocate(sizeof(b2CircleContact));
  12361.     return new (mem) b2CircleContact(fixtureA, fixtureB);
  12362. }
  12363.  
  12364. void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  12365.     ((b2CircleContact*)contact)->~b2CircleContact();
  12366.     allocator->Free(contact, sizeof(b2CircleContact));
  12367. }
  12368.  
  12369. b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
  12370.     : b2Contact(fixtureA, 0, fixtureB, 0) {
  12371.     b2Assert(m_fixtureA->GetType() == b2Shape::e_circle);
  12372.     b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
  12373. }
  12374.  
  12375. void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) {
  12376.     b2CollideCircles(manifold,
  12377.         (b2CircleShape*)m_fixtureA->GetShape(), xfA,
  12378.         (b2CircleShape*)m_fixtureB->GetShape(), xfB);
  12379. }
  12380. // MIT License
  12381.  
  12382. // Copyright (c) 2019 Erin Catto
  12383.  
  12384. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12385. // of this software and associated documentation files (the "Software"), to deal
  12386. // in the Software without restriction, including without limitation the rights
  12387. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12388. // copies of the Software, and to permit persons to whom the Software is
  12389. // furnished to do so, subject to the following conditions:
  12390.  
  12391. // The above copyright notice and this permission notice shall be included in all
  12392. // copies or substantial portions of the Software.
  12393.  
  12394. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12395. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12396. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12397. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12398. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12399. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12400. // SOFTWARE.
  12401.  
  12402. //#include "b2_chain_circle_contact.h"
  12403. //#include "b2_chain_polygon_contact.h"
  12404. //#include "b2_circle_contact.h"
  12405. //#include "b2_contact_solver.h"
  12406. //#include "b2_edge_circle_contact.h"
  12407. //#include "b2_edge_polygon_contact.h"
  12408. //#include "b2_polygon_circle_contact.h"
  12409. //#include "b2_polygon_contact.h"
  12410.  
  12411. //#include "box2d/b2_contact.h"
  12412. //#include "box2d/b2_block_allocator.h"
  12413. //#include "box2d/b2_body.h"
  12414. //#include "box2d/b2_collision.h"
  12415. //#include "box2d/b2_fixture.h"
  12416. //#include "box2d/b2_shape.h"
  12417. //#include "box2d/b2_time_of_impact.h"
  12418. //#include "box2d/b2_world.h"
  12419.  
  12420. b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount];
  12421. bool b2Contact::s_initialized = false;
  12422.  
  12423. void b2Contact::InitializeRegisters() {
  12424.     AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle);
  12425.     AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle);
  12426.     AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon);
  12427.     AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle);
  12428.     AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon);
  12429.     AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle);
  12430.     AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon);
  12431. }
  12432.  
  12433. void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn,
  12434.     b2Shape::Type type1, b2Shape::Type type2) {
  12435.     b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount);
  12436.     b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount);
  12437.  
  12438.     s_registers[type1][type2].createFcn = createFcn;
  12439.     s_registers[type1][type2].destroyFcn = destoryFcn;
  12440.     s_registers[type1][type2].primary = true;
  12441.  
  12442.     if (type1 != type2) {
  12443.         s_registers[type2][type1].createFcn = createFcn;
  12444.         s_registers[type2][type1].destroyFcn = destoryFcn;
  12445.         s_registers[type2][type1].primary = false;
  12446.     }
  12447. }
  12448.  
  12449. b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) {
  12450.     if (s_initialized == false) {
  12451.         InitializeRegisters();
  12452.         s_initialized = true;
  12453.     }
  12454.  
  12455.     b2Shape::Type type1 = fixtureA->GetType();
  12456.     b2Shape::Type type2 = fixtureB->GetType();
  12457.  
  12458.     b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount);
  12459.     b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount);
  12460.  
  12461.     b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn;
  12462.     if (createFcn) {
  12463.         if (s_registers[type1][type2].primary) {
  12464.             return createFcn(fixtureA, indexA, fixtureB, indexB, allocator);
  12465.         } else {
  12466.             return createFcn(fixtureB, indexB, fixtureA, indexA, allocator);
  12467.         }
  12468.     } else {
  12469.         return nullptr;
  12470.     }
  12471. }
  12472.  
  12473. void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  12474.     b2Assert(s_initialized == true);
  12475.  
  12476.     b2Fixture* fixtureA = contact->m_fixtureA;
  12477.     b2Fixture* fixtureB = contact->m_fixtureB;
  12478.  
  12479.     if (contact->m_manifold.pointCount > 0 &&
  12480.         fixtureA->IsSensor() == false &&
  12481.         fixtureB->IsSensor() == false) {
  12482.         fixtureA->GetBody()->SetAwake(true);
  12483.         fixtureB->GetBody()->SetAwake(true);
  12484.     }
  12485.  
  12486.     b2Shape::Type typeA = fixtureA->GetType();
  12487.     b2Shape::Type typeB = fixtureB->GetType();
  12488.  
  12489.     b2Assert(0 <= typeA && typeA < b2Shape::e_typeCount);
  12490.     b2Assert(0 <= typeB && typeB < b2Shape::e_typeCount);
  12491.  
  12492.     b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn;
  12493.     destroyFcn(contact, allocator);
  12494. }
  12495.  
  12496. b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) {
  12497.     m_flags = e_enabledFlag;
  12498.  
  12499.     m_fixtureA = fA;
  12500.     m_fixtureB = fB;
  12501.  
  12502.     m_indexA = indexA;
  12503.     m_indexB = indexB;
  12504.  
  12505.     m_manifold.pointCount = 0;
  12506.  
  12507.     m_prev = nullptr;
  12508.     m_next = nullptr;
  12509.  
  12510.     m_nodeA.contact = nullptr;
  12511.     m_nodeA.prev = nullptr;
  12512.     m_nodeA.next = nullptr;
  12513.     m_nodeA.other = nullptr;
  12514.  
  12515.     m_nodeB.contact = nullptr;
  12516.     m_nodeB.prev = nullptr;
  12517.     m_nodeB.next = nullptr;
  12518.     m_nodeB.other = nullptr;
  12519.  
  12520.     m_toiCount = 0;
  12521.  
  12522.     m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction);
  12523.     m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution);
  12524.     m_restitutionThreshold = b2MixRestitutionThreshold(m_fixtureA->m_restitutionThreshold, m_fixtureB->m_restitutionThreshold);
  12525.  
  12526.     m_tangentSpeed = 0.0f;
  12527. }
  12528.  
  12529. // Update the contact manifold and touching status.
  12530. // Note: do not assume the fixture AABBs are overlapping or are valid.
  12531. void b2Contact::Update(b2ContactListener* listener) {
  12532.     b2Manifold oldManifold = m_manifold;
  12533.  
  12534.     // Re-enable this contact.
  12535.     m_flags |= e_enabledFlag;
  12536.  
  12537.     bool touching = false;
  12538.     bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag;
  12539.  
  12540.     bool sensorA = m_fixtureA->IsSensor();
  12541.     bool sensorB = m_fixtureB->IsSensor();
  12542.     bool sensor = sensorA || sensorB;
  12543.  
  12544.     b2Body* bodyA = m_fixtureA->GetBody();
  12545.     b2Body* bodyB = m_fixtureB->GetBody();
  12546.     const b2Transform& xfA = bodyA->GetTransform();
  12547.     const b2Transform& xfB = bodyB->GetTransform();
  12548.  
  12549.     // Is this contact a sensor?
  12550.     if (sensor) {
  12551.         const b2Shape* shapeA = m_fixtureA->GetShape();
  12552.         const b2Shape* shapeB = m_fixtureB->GetShape();
  12553.         touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB);
  12554.  
  12555.         // Sensors don't generate manifolds.
  12556.         m_manifold.pointCount = 0;
  12557.     } else {
  12558.         Evaluate(&m_manifold, xfA, xfB);
  12559.         touching = m_manifold.pointCount > 0;
  12560.  
  12561.         // Match old contact ids to new contact ids and copy the
  12562.         // stored impulses to warm start the solver.
  12563.         for (int32 i = 0; i < m_manifold.pointCount; ++i) {
  12564.             b2ManifoldPoint* mp2 = m_manifold.points + i;
  12565.             mp2->normalImpulse = 0.0f;
  12566.             mp2->tangentImpulse = 0.0f;
  12567.             b2ContactID id2 = mp2->id;
  12568.  
  12569.             for (int32 j = 0; j < oldManifold.pointCount; ++j) {
  12570.                 b2ManifoldPoint* mp1 = oldManifold.points + j;
  12571.  
  12572.                 if (mp1->id.key == id2.key) {
  12573.                     mp2->normalImpulse = mp1->normalImpulse;
  12574.                     mp2->tangentImpulse = mp1->tangentImpulse;
  12575.                     break;
  12576.                 }
  12577.             }
  12578.         }
  12579.  
  12580.         if (touching != wasTouching) {
  12581.             bodyA->SetAwake(true);
  12582.             bodyB->SetAwake(true);
  12583.         }
  12584.     }
  12585.  
  12586.     if (touching) {
  12587.         m_flags |= e_touchingFlag;
  12588.     } else {
  12589.         m_flags &= ~e_touchingFlag;
  12590.     }
  12591.  
  12592.     if (wasTouching == false && touching == true && listener) {
  12593.         listener->BeginContact(this);
  12594.     }
  12595.  
  12596.     if (wasTouching == true && touching == false && listener) {
  12597.         listener->EndContact(this);
  12598.     }
  12599.  
  12600.     if (sensor == false && touching && listener) {
  12601.         listener->PreSolve(this, &oldManifold);
  12602.     }
  12603. }
  12604. // MIT License
  12605.  
  12606. // Copyright (c) 2019 Erin Catto
  12607.  
  12608. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12609. // of this software and associated documentation files (the "Software"), to deal
  12610. // in the Software without restriction, including without limitation the rights
  12611. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12612. // copies of the Software, and to permit persons to whom the Software is
  12613. // furnished to do so, subject to the following conditions:
  12614.  
  12615. // The above copyright notice and this permission notice shall be included in all
  12616. // copies or substantial portions of the Software.
  12617.  
  12618. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12619. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12620. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12621. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12622. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12623. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12624. // SOFTWARE.
  12625.  
  12626. //#include "box2d/b2_body.h"
  12627. //#include "box2d/b2_contact.h"
  12628. //#include "box2d/b2_contact_manager.h"
  12629. //#include "box2d/b2_fixture.h"
  12630. //#include "box2d/b2_world_callbacks.h"
  12631.  
  12632. b2ContactFilter b2_defaultFilter;
  12633. b2ContactListener b2_defaultListener;
  12634.  
  12635. b2ContactManager::b2ContactManager() {
  12636.     m_contactList = nullptr;
  12637.     m_contactCount = 0;
  12638.     m_contactFilter = &b2_defaultFilter;
  12639.     m_contactListener = &b2_defaultListener;
  12640.     m_allocator = nullptr;
  12641. }
  12642.  
  12643. void b2ContactManager::Destroy(b2Contact* c) {
  12644.     b2Fixture* fixtureA = c->GetFixtureA();
  12645.     b2Fixture* fixtureB = c->GetFixtureB();
  12646.     b2Body* bodyA = fixtureA->GetBody();
  12647.     b2Body* bodyB = fixtureB->GetBody();
  12648.  
  12649.     if (m_contactListener && c->IsTouching()) {
  12650.         m_contactListener->EndContact(c);
  12651.     }
  12652.  
  12653.     // Remove from the world.
  12654.     if (c->m_prev) {
  12655.         c->m_prev->m_next = c->m_next;
  12656.     }
  12657.  
  12658.     if (c->m_next) {
  12659.         c->m_next->m_prev = c->m_prev;
  12660.     }
  12661.  
  12662.     if (c == m_contactList) {
  12663.         m_contactList = c->m_next;
  12664.     }
  12665.  
  12666.     // Remove from body 1
  12667.     if (c->m_nodeA.prev) {
  12668.         c->m_nodeA.prev->next = c->m_nodeA.next;
  12669.     }
  12670.  
  12671.     if (c->m_nodeA.next) {
  12672.         c->m_nodeA.next->prev = c->m_nodeA.prev;
  12673.     }
  12674.  
  12675.     if (&c->m_nodeA == bodyA->m_contactList) {
  12676.         bodyA->m_contactList = c->m_nodeA.next;
  12677.     }
  12678.  
  12679.     // Remove from body 2
  12680.     if (c->m_nodeB.prev) {
  12681.         c->m_nodeB.prev->next = c->m_nodeB.next;
  12682.     }
  12683.  
  12684.     if (c->m_nodeB.next) {
  12685.         c->m_nodeB.next->prev = c->m_nodeB.prev;
  12686.     }
  12687.  
  12688.     if (&c->m_nodeB == bodyB->m_contactList) {
  12689.         bodyB->m_contactList = c->m_nodeB.next;
  12690.     }
  12691.  
  12692.     // Call the factory.
  12693.     b2Contact::Destroy(c, m_allocator);
  12694.     --m_contactCount;
  12695. }
  12696.  
  12697. // This is the top level collision call for the time step. Here
  12698. // all the narrow phase collision is processed for the world
  12699. // contact list.
  12700. void b2ContactManager::Collide() {
  12701.     // Update awake contacts.
  12702.     b2Contact* c = m_contactList;
  12703.     while (c) {
  12704.         b2Fixture* fixtureA = c->GetFixtureA();
  12705.         b2Fixture* fixtureB = c->GetFixtureB();
  12706.         int32 indexA = c->GetChildIndexA();
  12707.         int32 indexB = c->GetChildIndexB();
  12708.         b2Body* bodyA = fixtureA->GetBody();
  12709.         b2Body* bodyB = fixtureB->GetBody();
  12710.  
  12711.         // Is this contact flagged for filtering?
  12712.         if (c->m_flags & b2Contact::e_filterFlag) {
  12713.             // Should these bodies collide?
  12714.             if (bodyB->ShouldCollide(bodyA) == false) {
  12715.                 b2Contact* cNuke = c;
  12716.                 c = cNuke->GetNext();
  12717.                 Destroy(cNuke);
  12718.                 continue;
  12719.             }
  12720.  
  12721.             // Check user filtering.
  12722.             if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) {
  12723.                 b2Contact* cNuke = c;
  12724.                 c = cNuke->GetNext();
  12725.                 Destroy(cNuke);
  12726.                 continue;
  12727.             }
  12728.  
  12729.             // Clear the filtering flag.
  12730.             c->m_flags &= ~b2Contact::e_filterFlag;
  12731.         }
  12732.  
  12733.         bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody;
  12734.         bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody;
  12735.  
  12736.         // At least one body must be awake and it must be dynamic or kinematic.
  12737.         if (activeA == false && activeB == false) {
  12738.             c = c->GetNext();
  12739.             continue;
  12740.         }
  12741.  
  12742.         int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId;
  12743.         int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId;
  12744.         bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB);
  12745.  
  12746.         // Here we destroy contacts that cease to overlap in the broad-phase.
  12747.         if (overlap == false) {
  12748.             b2Contact* cNuke = c;
  12749.             c = cNuke->GetNext();
  12750.             Destroy(cNuke);
  12751.             continue;
  12752.         }
  12753.  
  12754.         // The contact persists.
  12755.         c->Update(m_contactListener);
  12756.         c = c->GetNext();
  12757.     }
  12758. }
  12759.  
  12760. void b2ContactManager::FindNewContacts() {
  12761.     m_broadPhase.UpdatePairs(this);
  12762. }
  12763.  
  12764. void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) {
  12765.     b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA;
  12766.     b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB;
  12767.  
  12768.     b2Fixture* fixtureA = proxyA->fixture;
  12769.     b2Fixture* fixtureB = proxyB->fixture;
  12770.  
  12771.     int32 indexA = proxyA->childIndex;
  12772.     int32 indexB = proxyB->childIndex;
  12773.  
  12774.     b2Body* bodyA = fixtureA->GetBody();
  12775.     b2Body* bodyB = fixtureB->GetBody();
  12776.  
  12777.     // Are the fixtures on the same body?
  12778.     if (bodyA == bodyB) {
  12779.         return;
  12780.     }
  12781.  
  12782.     // TODO_ERIN use a hash table to remove a potential bottleneck when both
  12783.     // bodies have a lot of contacts.
  12784.     // Does a contact already exist?
  12785.     b2ContactEdge* edge = bodyB->GetContactList();
  12786.     while (edge) {
  12787.         if (edge->other == bodyA) {
  12788.             b2Fixture* fA = edge->contact->GetFixtureA();
  12789.             b2Fixture* fB = edge->contact->GetFixtureB();
  12790.             int32 iA = edge->contact->GetChildIndexA();
  12791.             int32 iB = edge->contact->GetChildIndexB();
  12792.  
  12793.             if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) {
  12794.                 // A contact already exists.
  12795.                 return;
  12796.             }
  12797.  
  12798.             if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) {
  12799.                 // A contact already exists.
  12800.                 return;
  12801.             }
  12802.         }
  12803.  
  12804.         edge = edge->next;
  12805.     }
  12806.  
  12807.     // Does a joint override collision? Is at least one body dynamic?
  12808.     if (bodyB->ShouldCollide(bodyA) == false) {
  12809.         return;
  12810.     }
  12811.  
  12812.     // Check user filtering.
  12813.     if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) {
  12814.         return;
  12815.     }
  12816.  
  12817.     // Call the factory.
  12818.     b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator);
  12819.     if (c == nullptr) {
  12820.         return;
  12821.     }
  12822.  
  12823.     // Contact creation may swap fixtures.
  12824.     fixtureA = c->GetFixtureA();
  12825.     fixtureB = c->GetFixtureB();
  12826.     indexA = c->GetChildIndexA();
  12827.     indexB = c->GetChildIndexB();
  12828.     bodyA = fixtureA->GetBody();
  12829.     bodyB = fixtureB->GetBody();
  12830.  
  12831.     // Insert into the world.
  12832.     c->m_prev = nullptr;
  12833.     c->m_next = m_contactList;
  12834.     if (m_contactList != nullptr) {
  12835.         m_contactList->m_prev = c;
  12836.     }
  12837.     m_contactList = c;
  12838.  
  12839.     // Connect to island graph.
  12840.  
  12841.     // Connect to body A
  12842.     c->m_nodeA.contact = c;
  12843.     c->m_nodeA.other = bodyB;
  12844.  
  12845.     c->m_nodeA.prev = nullptr;
  12846.     c->m_nodeA.next = bodyA->m_contactList;
  12847.     if (bodyA->m_contactList != nullptr) {
  12848.         bodyA->m_contactList->prev = &c->m_nodeA;
  12849.     }
  12850.     bodyA->m_contactList = &c->m_nodeA;
  12851.  
  12852.     // Connect to body B
  12853.     c->m_nodeB.contact = c;
  12854.     c->m_nodeB.other = bodyA;
  12855.  
  12856.     c->m_nodeB.prev = nullptr;
  12857.     c->m_nodeB.next = bodyB->m_contactList;
  12858.     if (bodyB->m_contactList != nullptr) {
  12859.         bodyB->m_contactList->prev = &c->m_nodeB;
  12860.     }
  12861.     bodyB->m_contactList = &c->m_nodeB;
  12862.  
  12863.     ++m_contactCount;
  12864. }
  12865. // MIT License
  12866.  
  12867. // Copyright (c) 2019 Erin Catto
  12868.  
  12869. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12870. // of this software and associated documentation files (the "Software"), to deal
  12871. // in the Software without restriction, including without limitation the rights
  12872. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12873. // copies of the Software, and to permit persons to whom the Software is
  12874. // furnished to do so, subject to the following conditions:
  12875.  
  12876. // The above copyright notice and this permission notice shall be included in all
  12877. // copies or substantial portions of the Software.
  12878.  
  12879. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12880. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12881. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12882. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12883. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12884. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12885. // SOFTWARE.
  12886.  
  12887. //#include "b2_contact_solver.h"
  12888.  
  12889. //#include "box2d/b2_body.h"
  12890. //#include "box2d/b2_contact.h"
  12891. //#include "box2d/b2_fixture.h"
  12892. //#include "box2d/b2_stack_allocator.h"
  12893. //#include "box2d/b2_world.h"
  12894.  
  12895. // Solver debugging is normally disabled because the block solver sometimes has to deal with a poorly conditioned effective mass matrix.
  12896. #define B2_DEBUG_SOLVER 0
  12897.  
  12898. B2_API bool g_blockSolve = true;
  12899.  
  12900. struct b2ContactPositionConstraint {
  12901.     b2Vec2 localPoints[b2_maxManifoldPoints];
  12902.     b2Vec2 localNormal;
  12903.     b2Vec2 localPoint;
  12904.     int32 indexA;
  12905.     int32 indexB;
  12906.     float invMassA, invMassB;
  12907.     b2Vec2 localCenterA, localCenterB;
  12908.     float invIA, invIB;
  12909.     b2Manifold::Type type;
  12910.     float radiusA, radiusB;
  12911.     int32 pointCount;
  12912. };
  12913.  
  12914. b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) {
  12915.     m_step = def->step;
  12916.     m_allocator = def->allocator;
  12917.     m_count = def->count;
  12918.     m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint));
  12919.     m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint));
  12920.     m_positions = def->positions;
  12921.     m_velocities = def->velocities;
  12922.     m_contacts = def->contacts;
  12923.  
  12924.     // Initialize position independent portions of the constraints.
  12925.     for (int32 i = 0; i < m_count; ++i) {
  12926.         b2Contact* contact = m_contacts[i];
  12927.  
  12928.         b2Fixture* fixtureA = contact->m_fixtureA;
  12929.         b2Fixture* fixtureB = contact->m_fixtureB;
  12930.         b2Shape* shapeA = fixtureA->GetShape();
  12931.         b2Shape* shapeB = fixtureB->GetShape();
  12932.         float radiusA = shapeA->m_radius;
  12933.         float radiusB = shapeB->m_radius;
  12934.         b2Body* bodyA = fixtureA->GetBody();
  12935.         b2Body* bodyB = fixtureB->GetBody();
  12936.         b2Manifold* manifold = contact->GetManifold();
  12937.  
  12938.         int32 pointCount = manifold->pointCount;
  12939.         b2Assert(pointCount > 0);
  12940.  
  12941.         b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
  12942.         vc->friction = contact->m_friction;
  12943.         vc->restitution = contact->m_restitution;
  12944.         vc->threshold = contact->m_restitutionThreshold;
  12945.         vc->tangentSpeed = contact->m_tangentSpeed;
  12946.         vc->indexA = bodyA->m_islandIndex;
  12947.         vc->indexB = bodyB->m_islandIndex;
  12948.         vc->invMassA = bodyA->m_invMass;
  12949.         vc->invMassB = bodyB->m_invMass;
  12950.         vc->invIA = bodyA->m_invI;
  12951.         vc->invIB = bodyB->m_invI;
  12952.         vc->contactIndex = i;
  12953.         vc->pointCount = pointCount;
  12954.         vc->K.SetZero();
  12955.         vc->normalMass.SetZero();
  12956.  
  12957.         b2ContactPositionConstraint* pc = m_positionConstraints + i;
  12958.         pc->indexA = bodyA->m_islandIndex;
  12959.         pc->indexB = bodyB->m_islandIndex;
  12960.         pc->invMassA = bodyA->m_invMass;
  12961.         pc->invMassB = bodyB->m_invMass;
  12962.         pc->localCenterA = bodyA->m_sweep.localCenter;
  12963.         pc->localCenterB = bodyB->m_sweep.localCenter;
  12964.         pc->invIA = bodyA->m_invI;
  12965.         pc->invIB = bodyB->m_invI;
  12966.         pc->localNormal = manifold->localNormal;
  12967.         pc->localPoint = manifold->localPoint;
  12968.         pc->pointCount = pointCount;
  12969.         pc->radiusA = radiusA;
  12970.         pc->radiusB = radiusB;
  12971.         pc->type = manifold->type;
  12972.  
  12973.         for (int32 j = 0; j < pointCount; ++j) {
  12974.             b2ManifoldPoint* cp = manifold->points + j;
  12975.             b2VelocityConstraintPoint* vcp = vc->points + j;
  12976.  
  12977.             if (m_step.warmStarting) {
  12978.                 vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse;
  12979.                 vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse;
  12980.             } else {
  12981.                 vcp->normalImpulse = 0.0f;
  12982.                 vcp->tangentImpulse = 0.0f;
  12983.             }
  12984.  
  12985.             vcp->rA.SetZero();
  12986.             vcp->rB.SetZero();
  12987.             vcp->normalMass = 0.0f;
  12988.             vcp->tangentMass = 0.0f;
  12989.             vcp->velocityBias = 0.0f;
  12990.  
  12991.             pc->localPoints[j] = cp->localPoint;
  12992.         }
  12993.     }
  12994. }
  12995.  
  12996. b2ContactSolver::~b2ContactSolver() {
  12997.     m_allocator->Free(m_velocityConstraints);
  12998.     m_allocator->Free(m_positionConstraints);
  12999. }
  13000.  
  13001. // Initialize position dependent portions of the velocity constraints.
  13002. void b2ContactSolver::InitializeVelocityConstraints() {
  13003.     for (int32 i = 0; i < m_count; ++i) {
  13004.         b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
  13005.         b2ContactPositionConstraint* pc = m_positionConstraints + i;
  13006.  
  13007.         float radiusA = pc->radiusA;
  13008.         float radiusB = pc->radiusB;
  13009.         b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold();
  13010.  
  13011.         int32 indexA = vc->indexA;
  13012.         int32 indexB = vc->indexB;
  13013.  
  13014.         float mA = vc->invMassA;
  13015.         float mB = vc->invMassB;
  13016.         float iA = vc->invIA;
  13017.         float iB = vc->invIB;
  13018.         b2Vec2 localCenterA = pc->localCenterA;
  13019.         b2Vec2 localCenterB = pc->localCenterB;
  13020.  
  13021.         b2Vec2 cA = m_positions[indexA].c;
  13022.         float aA = m_positions[indexA].a;
  13023.         b2Vec2 vA = m_velocities[indexA].v;
  13024.         float wA = m_velocities[indexA].w;
  13025.  
  13026.         b2Vec2 cB = m_positions[indexB].c;
  13027.         float aB = m_positions[indexB].a;
  13028.         b2Vec2 vB = m_velocities[indexB].v;
  13029.         float wB = m_velocities[indexB].w;
  13030.  
  13031.         b2Assert(manifold->pointCount > 0);
  13032.  
  13033.         b2Transform xfA, xfB;
  13034.         xfA.q.Set(aA);
  13035.         xfB.q.Set(aB);
  13036.         xfA.p = cA - b2Mul(xfA.q, localCenterA);
  13037.         xfB.p = cB - b2Mul(xfB.q, localCenterB);
  13038.  
  13039.         b2WorldManifold worldManifold;
  13040.         worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB);
  13041.  
  13042.         vc->normal = worldManifold.normal;
  13043.  
  13044.         int32 pointCount = vc->pointCount;
  13045.         for (int32 j = 0; j < pointCount; ++j) {
  13046.             b2VelocityConstraintPoint* vcp = vc->points + j;
  13047.  
  13048.             vcp->rA = worldManifold.points[j] - cA;
  13049.             vcp->rB = worldManifold.points[j] - cB;
  13050.  
  13051.             float rnA = b2Cross(vcp->rA, vc->normal);
  13052.             float rnB = b2Cross(vcp->rB, vc->normal);
  13053.  
  13054.             float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
  13055.  
  13056.             vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
  13057.  
  13058.             b2Vec2 tangent = b2Cross(vc->normal, 1.0f);
  13059.  
  13060.             float rtA = b2Cross(vcp->rA, tangent);
  13061.             float rtB = b2Cross(vcp->rB, tangent);
  13062.  
  13063.             float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
  13064.  
  13065.             vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
  13066.  
  13067.             // Setup a velocity bias for restitution.
  13068.             vcp->velocityBias = 0.0f;
  13069.             float vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA));
  13070.             if (vRel < -vc->threshold) {
  13071.                 vcp->velocityBias = -vc->restitution * vRel;
  13072.             }
  13073.         }
  13074.  
  13075.         // If we have two points, then prepare the block solver.
  13076.         if (vc->pointCount == 2 && g_blockSolve) {
  13077.             b2VelocityConstraintPoint* vcp1 = vc->points + 0;
  13078.             b2VelocityConstraintPoint* vcp2 = vc->points + 1;
  13079.  
  13080.             float rn1A = b2Cross(vcp1->rA, vc->normal);
  13081.             float rn1B = b2Cross(vcp1->rB, vc->normal);
  13082.             float rn2A = b2Cross(vcp2->rA, vc->normal);
  13083.             float rn2B = b2Cross(vcp2->rB, vc->normal);
  13084.  
  13085.             float k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
  13086.             float k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
  13087.             float k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
  13088.  
  13089.             // Ensure a reasonable condition number.
  13090.             const float k_maxConditionNumber = 1000.0f;
  13091.             if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) {
  13092.                 // K is safe to invert.
  13093.                 vc->K.ex.Set(k11, k12);
  13094.                 vc->K.ey.Set(k12, k22);
  13095.                 vc->normalMass = vc->K.GetInverse();
  13096.             } else {
  13097.                 // The constraints are redundant, just use one.
  13098.                 // TODO_ERIN use deepest?
  13099.                 vc->pointCount = 1;
  13100.             }
  13101.         }
  13102.     }
  13103. }
  13104.  
  13105. void b2ContactSolver::WarmStart() {
  13106.     // Warm start.
  13107.     for (int32 i = 0; i < m_count; ++i) {
  13108.         b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
  13109.  
  13110.         int32 indexA = vc->indexA;
  13111.         int32 indexB = vc->indexB;
  13112.         float mA = vc->invMassA;
  13113.         float iA = vc->invIA;
  13114.         float mB = vc->invMassB;
  13115.         float iB = vc->invIB;
  13116.         int32 pointCount = vc->pointCount;
  13117.  
  13118.         b2Vec2 vA = m_velocities[indexA].v;
  13119.         float wA = m_velocities[indexA].w;
  13120.         b2Vec2 vB = m_velocities[indexB].v;
  13121.         float wB = m_velocities[indexB].w;
  13122.  
  13123.         b2Vec2 normal = vc->normal;
  13124.         b2Vec2 tangent = b2Cross(normal, 1.0f);
  13125.  
  13126.         for (int32 j = 0; j < pointCount; ++j) {
  13127.             b2VelocityConstraintPoint* vcp = vc->points + j;
  13128.             b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent;
  13129.             wA -= iA * b2Cross(vcp->rA, P);
  13130.             vA -= mA * P;
  13131.             wB += iB * b2Cross(vcp->rB, P);
  13132.             vB += mB * P;
  13133.         }
  13134.  
  13135.         m_velocities[indexA].v = vA;
  13136.         m_velocities[indexA].w = wA;
  13137.         m_velocities[indexB].v = vB;
  13138.         m_velocities[indexB].w = wB;
  13139.     }
  13140. }
  13141.  
  13142. void b2ContactSolver::SolveVelocityConstraints() {
  13143.     for (int32 i = 0; i < m_count; ++i) {
  13144.         b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
  13145.  
  13146.         int32 indexA = vc->indexA;
  13147.         int32 indexB = vc->indexB;
  13148.         float mA = vc->invMassA;
  13149.         float iA = vc->invIA;
  13150.         float mB = vc->invMassB;
  13151.         float iB = vc->invIB;
  13152.         int32 pointCount = vc->pointCount;
  13153.  
  13154.         b2Vec2 vA = m_velocities[indexA].v;
  13155.         float wA = m_velocities[indexA].w;
  13156.         b2Vec2 vB = m_velocities[indexB].v;
  13157.         float wB = m_velocities[indexB].w;
  13158.  
  13159.         b2Vec2 normal = vc->normal;
  13160.         b2Vec2 tangent = b2Cross(normal, 1.0f);
  13161.         float friction = vc->friction;
  13162.  
  13163.         b2Assert(pointCount == 1 || pointCount == 2);
  13164.  
  13165.         // Solve tangent constraints first because non-penetration is more important
  13166.         // than friction.
  13167.         for (int32 j = 0; j < pointCount; ++j) {
  13168.             b2VelocityConstraintPoint* vcp = vc->points + j;
  13169.  
  13170.             // Relative velocity at contact
  13171.             b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA);
  13172.  
  13173.             // Compute tangent force
  13174.             float vt = b2Dot(dv, tangent) - vc->tangentSpeed;
  13175.             float lambda = vcp->tangentMass * (-vt);
  13176.  
  13177.             // b2Clamp the accumulated force
  13178.             float maxFriction = friction * vcp->normalImpulse;
  13179.             float newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction);
  13180.             lambda = newImpulse - vcp->tangentImpulse;
  13181.             vcp->tangentImpulse = newImpulse;
  13182.  
  13183.             // Apply contact impulse
  13184.             b2Vec2 P = lambda * tangent;
  13185.  
  13186.             vA -= mA * P;
  13187.             wA -= iA * b2Cross(vcp->rA, P);
  13188.  
  13189.             vB += mB * P;
  13190.             wB += iB * b2Cross(vcp->rB, P);
  13191.         }
  13192.  
  13193.         // Solve normal constraints
  13194.         if (pointCount == 1 || g_blockSolve == false) {
  13195.             for (int32 j = 0; j < pointCount; ++j) {
  13196.                 b2VelocityConstraintPoint* vcp = vc->points + j;
  13197.  
  13198.                 // Relative velocity at contact
  13199.                 b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA);
  13200.  
  13201.                 // Compute normal impulse
  13202.                 float vn = b2Dot(dv, normal);
  13203.                 float lambda = -vcp->normalMass * (vn - vcp->velocityBias);
  13204.  
  13205.                 // b2Clamp the accumulated impulse
  13206.                 float newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f);
  13207.                 lambda = newImpulse - vcp->normalImpulse;
  13208.                 vcp->normalImpulse = newImpulse;
  13209.  
  13210.                 // Apply contact impulse
  13211.                 b2Vec2 P = lambda * normal;
  13212.                 vA -= mA * P;
  13213.                 wA -= iA * b2Cross(vcp->rA, P);
  13214.  
  13215.                 vB += mB * P;
  13216.                 wB += iB * b2Cross(vcp->rB, P);
  13217.             }
  13218.         } else {
  13219.             // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
  13220.             // Build the mini LCP for this contact patch
  13221.             //
  13222.             // vn = A * x + b, vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
  13223.             //
  13224.             // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
  13225.             // b = vn0 - velocityBias
  13226.             //
  13227.             // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
  13228.             // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
  13229.             // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
  13230.             // solution that satisfies the problem is chosen.
  13231.             //
  13232.             // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
  13233.             // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
  13234.             //
  13235.             // Substitute:
  13236.             //
  13237.             // x = a + d
  13238.             //
  13239.             // a := old total impulse
  13240.             // x := new total impulse
  13241.             // d := incremental impulse
  13242.             //
  13243.             // For the current iteration we extend the formula for the incremental impulse
  13244.             // to compute the new total impulse:
  13245.             //
  13246.             // vn = A * d + b
  13247.             //    = A * (x - a) + b
  13248.             //    = A * x + b - A * a
  13249.             //    = A * x + b'
  13250.             // b' = b - A * a;
  13251.  
  13252.             b2VelocityConstraintPoint* cp1 = vc->points + 0;
  13253.             b2VelocityConstraintPoint* cp2 = vc->points + 1;
  13254.  
  13255.             b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse);
  13256.             b2Assert(a.x >= 0.0f && a.y >= 0.0f);
  13257.  
  13258.             // Relative velocity at contact
  13259.             b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA);
  13260.             b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA);
  13261.  
  13262.             // Compute normal velocity
  13263.             float vn1 = b2Dot(dv1, normal);
  13264.             float vn2 = b2Dot(dv2, normal);
  13265.  
  13266.             b2Vec2 b;
  13267.             b.x = vn1 - cp1->velocityBias;
  13268.             b.y = vn2 - cp2->velocityBias;
  13269.  
  13270.             // Compute b'
  13271.             b -= b2Mul(vc->K, a);
  13272.  
  13273.             const float k_errorTol = 1e-3f;
  13274.             B2_NOT_USED(k_errorTol);
  13275.  
  13276.             for (;;) {
  13277.                 //
  13278.                 // Case 1: vn = 0
  13279.                 //
  13280.                 // 0 = A * x + b'
  13281.                 //
  13282.                 // Solve for x:
  13283.                 //
  13284.                 // x = - inv(A) * b'
  13285.                 //
  13286.                 b2Vec2 x = -b2Mul(vc->normalMass, b);
  13287.  
  13288.                 if (x.x >= 0.0f && x.y >= 0.0f) {
  13289.                     // Get the incremental impulse
  13290.                     b2Vec2 d = x - a;
  13291.  
  13292.                     // Apply incremental impulse
  13293.                     b2Vec2 P1 = d.x * normal;
  13294.                     b2Vec2 P2 = d.y * normal;
  13295.                     vA -= mA * (P1 + P2);
  13296.                     wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
  13297.  
  13298.                     vB += mB * (P1 + P2);
  13299.                     wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
  13300.  
  13301.                     // Accumulate
  13302.                     cp1->normalImpulse = x.x;
  13303.                     cp2->normalImpulse = x.y;
  13304.  
  13305. #if B2_DEBUG_SOLVER == 1
  13306.                     // Postconditions
  13307.                     dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA);
  13308.                     dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA);
  13309.  
  13310.                     // Compute normal velocity
  13311.                     vn1 = b2Dot(dv1, normal);
  13312.                     vn2 = b2Dot(dv2, normal);
  13313.  
  13314.                     b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol);
  13315.                     b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol);
  13316. #endif
  13317.                     break;
  13318.                 }
  13319.  
  13320.                 //
  13321.                 // Case 2: vn1 = 0 and x2 = 0
  13322.                 //
  13323.                 //   0 = a11 * x1 + a12 * 0 + b1'
  13324.                 // vn2 = a21 * x1 + a22 * 0 + b2'
  13325.                 //
  13326.                 x.x = -cp1->normalMass * b.x;
  13327.                 x.y = 0.0f;
  13328.                 vn1 = 0.0f;
  13329.                 vn2 = vc->K.ex.y * x.x + b.y;
  13330.                 if (x.x >= 0.0f && vn2 >= 0.0f) {
  13331.                     // Get the incremental impulse
  13332.                     b2Vec2 d = x - a;
  13333.  
  13334.                     // Apply incremental impulse
  13335.                     b2Vec2 P1 = d.x * normal;
  13336.                     b2Vec2 P2 = d.y * normal;
  13337.                     vA -= mA * (P1 + P2);
  13338.                     wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
  13339.  
  13340.                     vB += mB * (P1 + P2);
  13341.                     wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
  13342.  
  13343.                     // Accumulate
  13344.                     cp1->normalImpulse = x.x;
  13345.                     cp2->normalImpulse = x.y;
  13346.  
  13347. #if B2_DEBUG_SOLVER == 1
  13348.                     // Postconditions
  13349.                     dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA);
  13350.  
  13351.                     // Compute normal velocity
  13352.                     vn1 = b2Dot(dv1, normal);
  13353.  
  13354.                     b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol);
  13355. #endif
  13356.                     break;
  13357.                 }
  13358.  
  13359.  
  13360.                 //
  13361.                 // Case 3: vn2 = 0 and x1 = 0
  13362.                 //
  13363.                 // vn1 = a11 * 0 + a12 * x2 + b1'
  13364.                 //   0 = a21 * 0 + a22 * x2 + b2'
  13365.                 //
  13366.                 x.x = 0.0f;
  13367.                 x.y = -cp2->normalMass * b.y;
  13368.                 vn1 = vc->K.ey.x * x.y + b.x;
  13369.                 vn2 = 0.0f;
  13370.  
  13371.                 if (x.y >= 0.0f && vn1 >= 0.0f) {
  13372.                     // Resubstitute for the incremental impulse
  13373.                     b2Vec2 d = x - a;
  13374.  
  13375.                     // Apply incremental impulse
  13376.                     b2Vec2 P1 = d.x * normal;
  13377.                     b2Vec2 P2 = d.y * normal;
  13378.                     vA -= mA * (P1 + P2);
  13379.                     wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
  13380.  
  13381.                     vB += mB * (P1 + P2);
  13382.                     wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
  13383.  
  13384.                     // Accumulate
  13385.                     cp1->normalImpulse = x.x;
  13386.                     cp2->normalImpulse = x.y;
  13387.  
  13388. #if B2_DEBUG_SOLVER == 1
  13389.                     // Postconditions
  13390.                     dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA);
  13391.  
  13392.                     // Compute normal velocity
  13393.                     vn2 = b2Dot(dv2, normal);
  13394.  
  13395.                     b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol);
  13396. #endif
  13397.                     break;
  13398.                 }
  13399.  
  13400.                 //
  13401.                 // Case 4: x1 = 0 and x2 = 0
  13402.                 //
  13403.                 // vn1 = b1
  13404.                 // vn2 = b2;
  13405.                 x.x = 0.0f;
  13406.                 x.y = 0.0f;
  13407.                 vn1 = b.x;
  13408.                 vn2 = b.y;
  13409.  
  13410.                 if (vn1 >= 0.0f && vn2 >= 0.0f) {
  13411.                     // Resubstitute for the incremental impulse
  13412.                     b2Vec2 d = x - a;
  13413.  
  13414.                     // Apply incremental impulse
  13415.                     b2Vec2 P1 = d.x * normal;
  13416.                     b2Vec2 P2 = d.y * normal;
  13417.                     vA -= mA * (P1 + P2);
  13418.                     wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
  13419.  
  13420.                     vB += mB * (P1 + P2);
  13421.                     wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
  13422.  
  13423.                     // Accumulate
  13424.                     cp1->normalImpulse = x.x;
  13425.                     cp2->normalImpulse = x.y;
  13426.  
  13427.                     break;
  13428.                 }
  13429.  
  13430.                 // No solution, give up. This is hit sometimes, but it doesn't seem to matter.
  13431.                 break;
  13432.             }
  13433.         }
  13434.  
  13435.         m_velocities[indexA].v = vA;
  13436.         m_velocities[indexA].w = wA;
  13437.         m_velocities[indexB].v = vB;
  13438.         m_velocities[indexB].w = wB;
  13439.     }
  13440. }
  13441.  
  13442. void b2ContactSolver::StoreImpulses() {
  13443.     for (int32 i = 0; i < m_count; ++i) {
  13444.         b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
  13445.         b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold();
  13446.  
  13447.         for (int32 j = 0; j < vc->pointCount; ++j) {
  13448.             manifold->points[j].normalImpulse = vc->points[j].normalImpulse;
  13449.             manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse;
  13450.         }
  13451.     }
  13452. }
  13453.  
  13454. struct b2PositionSolverManifold {
  13455.     void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) {
  13456.         b2Assert(pc->pointCount > 0);
  13457.  
  13458.         switch (pc->type) {
  13459.         case b2Manifold::e_circles:
  13460.         {
  13461.             b2Vec2 pointA = b2Mul(xfA, pc->localPoint);
  13462.             b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]);
  13463.             normal = pointB - pointA;
  13464.             normal.Normalize();
  13465.             point = 0.5f * (pointA + pointB);
  13466.             separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB;
  13467.         }
  13468.         break;
  13469.  
  13470.         case b2Manifold::e_faceA:
  13471.         {
  13472.             normal = b2Mul(xfA.q, pc->localNormal);
  13473.             b2Vec2 planePoint = b2Mul(xfA, pc->localPoint);
  13474.  
  13475.             b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]);
  13476.             separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB;
  13477.             point = clipPoint;
  13478.         }
  13479.         break;
  13480.  
  13481.         case b2Manifold::e_faceB:
  13482.         {
  13483.             normal = b2Mul(xfB.q, pc->localNormal);
  13484.             b2Vec2 planePoint = b2Mul(xfB, pc->localPoint);
  13485.  
  13486.             b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]);
  13487.             separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB;
  13488.             point = clipPoint;
  13489.  
  13490.             // Ensure normal points from A to B
  13491.             normal = -normal;
  13492.         }
  13493.         break;
  13494.         }
  13495.     }
  13496.  
  13497.     b2Vec2 normal;
  13498.     b2Vec2 point;
  13499.     float separation;
  13500. };
  13501.  
  13502. // Sequential solver.
  13503. bool b2ContactSolver::SolvePositionConstraints() {
  13504.     float minSeparation = 0.0f;
  13505.  
  13506.     for (int32 i = 0; i < m_count; ++i) {
  13507.         b2ContactPositionConstraint* pc = m_positionConstraints + i;
  13508.  
  13509.         int32 indexA = pc->indexA;
  13510.         int32 indexB = pc->indexB;
  13511.         b2Vec2 localCenterA = pc->localCenterA;
  13512.         float mA = pc->invMassA;
  13513.         float iA = pc->invIA;
  13514.         b2Vec2 localCenterB = pc->localCenterB;
  13515.         float mB = pc->invMassB;
  13516.         float iB = pc->invIB;
  13517.         int32 pointCount = pc->pointCount;
  13518.  
  13519.         b2Vec2 cA = m_positions[indexA].c;
  13520.         float aA = m_positions[indexA].a;
  13521.  
  13522.         b2Vec2 cB = m_positions[indexB].c;
  13523.         float aB = m_positions[indexB].a;
  13524.  
  13525.         // Solve normal constraints
  13526.         for (int32 j = 0; j < pointCount; ++j) {
  13527.             b2Transform xfA, xfB;
  13528.             xfA.q.Set(aA);
  13529.             xfB.q.Set(aB);
  13530.             xfA.p = cA - b2Mul(xfA.q, localCenterA);
  13531.             xfB.p = cB - b2Mul(xfB.q, localCenterB);
  13532.  
  13533.             b2PositionSolverManifold psm;
  13534.             psm.Initialize(pc, xfA, xfB, j);
  13535.             b2Vec2 normal = psm.normal;
  13536.  
  13537.             b2Vec2 point = psm.point;
  13538.             float separation = psm.separation;
  13539.  
  13540.             b2Vec2 rA = point - cA;
  13541.             b2Vec2 rB = point - cB;
  13542.  
  13543.             // Track max constraint error.
  13544.             minSeparation = b2Min(minSeparation, separation);
  13545.  
  13546.             // Prevent large corrections and allow slop.
  13547.             float C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f);
  13548.  
  13549.             // Compute the effective mass.
  13550.             float rnA = b2Cross(rA, normal);
  13551.             float rnB = b2Cross(rB, normal);
  13552.             float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
  13553.  
  13554.             // Compute normal impulse
  13555.             float impulse = K > 0.0f ? -C / K : 0.0f;
  13556.  
  13557.             b2Vec2 P = impulse * normal;
  13558.  
  13559.             cA -= mA * P;
  13560.             aA -= iA * b2Cross(rA, P);
  13561.  
  13562.             cB += mB * P;
  13563.             aB += iB * b2Cross(rB, P);
  13564.         }
  13565.  
  13566.         m_positions[indexA].c = cA;
  13567.         m_positions[indexA].a = aA;
  13568.  
  13569.         m_positions[indexB].c = cB;
  13570.         m_positions[indexB].a = aB;
  13571.     }
  13572.  
  13573.     // We can't expect minSpeparation >= -b2_linearSlop because we don't
  13574.     // push the separation above -b2_linearSlop.
  13575.     return minSeparation >= -3.0f * b2_linearSlop;
  13576. }
  13577.  
  13578. // Sequential position solver for position constraints.
  13579. bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) {
  13580.     float minSeparation = 0.0f;
  13581.  
  13582.     for (int32 i = 0; i < m_count; ++i) {
  13583.         b2ContactPositionConstraint* pc = m_positionConstraints + i;
  13584.  
  13585.         int32 indexA = pc->indexA;
  13586.         int32 indexB = pc->indexB;
  13587.         b2Vec2 localCenterA = pc->localCenterA;
  13588.         b2Vec2 localCenterB = pc->localCenterB;
  13589.         int32 pointCount = pc->pointCount;
  13590.  
  13591.         float mA = 0.0f;
  13592.         float iA = 0.0f;
  13593.         if (indexA == toiIndexA || indexA == toiIndexB) {
  13594.             mA = pc->invMassA;
  13595.             iA = pc->invIA;
  13596.         }
  13597.  
  13598.         float mB = 0.0f;
  13599.         float iB = 0.;
  13600.         if (indexB == toiIndexA || indexB == toiIndexB) {
  13601.             mB = pc->invMassB;
  13602.             iB = pc->invIB;
  13603.         }
  13604.  
  13605.         b2Vec2 cA = m_positions[indexA].c;
  13606.         float aA = m_positions[indexA].a;
  13607.  
  13608.         b2Vec2 cB = m_positions[indexB].c;
  13609.         float aB = m_positions[indexB].a;
  13610.  
  13611.         // Solve normal constraints
  13612.         for (int32 j = 0; j < pointCount; ++j) {
  13613.             b2Transform xfA, xfB;
  13614.             xfA.q.Set(aA);
  13615.             xfB.q.Set(aB);
  13616.             xfA.p = cA - b2Mul(xfA.q, localCenterA);
  13617.             xfB.p = cB - b2Mul(xfB.q, localCenterB);
  13618.  
  13619.             b2PositionSolverManifold psm;
  13620.             psm.Initialize(pc, xfA, xfB, j);
  13621.             b2Vec2 normal = psm.normal;
  13622.  
  13623.             b2Vec2 point = psm.point;
  13624.             float separation = psm.separation;
  13625.  
  13626.             b2Vec2 rA = point - cA;
  13627.             b2Vec2 rB = point - cB;
  13628.  
  13629.             // Track max constraint error.
  13630.             minSeparation = b2Min(minSeparation, separation);
  13631.  
  13632.             // Prevent large corrections and allow slop.
  13633.             float C = b2Clamp(b2_toiBaumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f);
  13634.  
  13635.             // Compute the effective mass.
  13636.             float rnA = b2Cross(rA, normal);
  13637.             float rnB = b2Cross(rB, normal);
  13638.             float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
  13639.  
  13640.             // Compute normal impulse
  13641.             float impulse = K > 0.0f ? -C / K : 0.0f;
  13642.  
  13643.             b2Vec2 P = impulse * normal;
  13644.  
  13645.             cA -= mA * P;
  13646.             aA -= iA * b2Cross(rA, P);
  13647.  
  13648.             cB += mB * P;
  13649.             aB += iB * b2Cross(rB, P);
  13650.         }
  13651.  
  13652.         m_positions[indexA].c = cA;
  13653.         m_positions[indexA].a = aA;
  13654.  
  13655.         m_positions[indexB].c = cB;
  13656.         m_positions[indexB].a = aB;
  13657.     }
  13658.  
  13659.     // We can't expect minSpeparation >= -b2_linearSlop because we don't
  13660.     // push the separation above -b2_linearSlop.
  13661.     return minSeparation >= -1.5f * b2_linearSlop;
  13662. }
  13663. // MIT License
  13664.  
  13665. // Copyright (c) 2019 Erin Catto
  13666.  
  13667. // Permission is hereby granted, free of charge, to any person obtaining a copy
  13668. // of this software and associated documentation files (the "Software"), to deal
  13669. // in the Software without restriction, including without limitation the rights
  13670. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13671. // copies of the Software, and to permit persons to whom the Software is
  13672. // furnished to do so, subject to the following conditions:
  13673.  
  13674. // The above copyright notice and this permission notice shall be included in all
  13675. // copies or substantial portions of the Software.
  13676.  
  13677. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13678. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13679. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  13680. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  13681. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  13682. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  13683. // SOFTWARE.
  13684.  
  13685. //#include "box2d/b2_body.h"
  13686. //#include "box2d/b2_draw.h"
  13687. //#include "box2d/b2_distance_joint.h"
  13688. //#include "box2d/b2_time_step.h"
  13689.  
  13690. // 1-D constrained system
  13691. // m (v2 - v1) = lambda
  13692. // v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
  13693. // x2 = x1 + h * v2
  13694.  
  13695. // 1-D mass-damper-spring system
  13696. // m (v2 - v1) + h * d * v2 + h * k *
  13697.  
  13698. // C = norm(p2 - p1) - L
  13699. // u = (p2 - p1) / norm(p2 - p1)
  13700. // Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
  13701. // J = [-u -cross(r1, u) u cross(r2, u)]
  13702. // K = J * invM * JT
  13703. //   = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
  13704.  
  13705.  
  13706. void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2,
  13707.     const b2Vec2& anchor1, const b2Vec2& anchor2) {
  13708.     bodyA = b1;
  13709.     bodyB = b2;
  13710.     localAnchorA = bodyA->GetLocalPoint(anchor1);
  13711.     localAnchorB = bodyB->GetLocalPoint(anchor2);
  13712.     b2Vec2 d = anchor2 - anchor1;
  13713.     length = b2Max(d.Length(), b2_linearSlop);
  13714.     minLength = length;
  13715.     maxLength = length;
  13716. }
  13717.  
  13718. b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def)
  13719.     : b2Joint(def) {
  13720.     m_localAnchorA = def->localAnchorA;
  13721.     m_localAnchorB = def->localAnchorB;
  13722.     m_length = b2Max(def->length, b2_linearSlop);
  13723.     m_minLength = b2Max(def->minLength, b2_linearSlop);
  13724.     m_maxLength = b2Max(def->maxLength, m_minLength);
  13725.     m_stiffness = def->stiffness;
  13726.     m_damping = def->damping;
  13727.  
  13728.     m_gamma = 0.0f;
  13729.     m_bias = 0.0f;
  13730.     m_impulse = 0.0f;
  13731.     m_lowerImpulse = 0.0f;
  13732.     m_upperImpulse = 0.0f;
  13733.     m_currentLength = 0.0f;
  13734. }
  13735.  
  13736. void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) {
  13737.     m_indexA = m_bodyA->m_islandIndex;
  13738.     m_indexB = m_bodyB->m_islandIndex;
  13739.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  13740.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  13741.     m_invMassA = m_bodyA->m_invMass;
  13742.     m_invMassB = m_bodyB->m_invMass;
  13743.     m_invIA = m_bodyA->m_invI;
  13744.     m_invIB = m_bodyB->m_invI;
  13745.  
  13746.     b2Vec2 cA = data.positions[m_indexA].c;
  13747.     float aA = data.positions[m_indexA].a;
  13748.     b2Vec2 vA = data.velocities[m_indexA].v;
  13749.     float wA = data.velocities[m_indexA].w;
  13750.  
  13751.     b2Vec2 cB = data.positions[m_indexB].c;
  13752.     float aB = data.positions[m_indexB].a;
  13753.     b2Vec2 vB = data.velocities[m_indexB].v;
  13754.     float wB = data.velocities[m_indexB].w;
  13755.  
  13756.     b2Rot qA(aA), qB(aB);
  13757.  
  13758.     m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  13759.     m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  13760.     m_u = cB + m_rB - cA - m_rA;
  13761.  
  13762.     // Handle singularity.
  13763.     m_currentLength = m_u.Length();
  13764.     if (m_currentLength > b2_linearSlop) {
  13765.         m_u *= 1.0f / m_currentLength;
  13766.     } else {
  13767.         m_u.Set(0.0f, 0.0f);
  13768.         m_mass = 0.0f;
  13769.         m_impulse = 0.0f;
  13770.         m_lowerImpulse = 0.0f;
  13771.         m_upperImpulse = 0.0f;
  13772.     }
  13773.  
  13774.     float crAu = b2Cross(m_rA, m_u);
  13775.     float crBu = b2Cross(m_rB, m_u);
  13776.     float invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu;
  13777.     m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
  13778.  
  13779.     if (m_stiffness > 0.0f && m_minLength < m_maxLength) {
  13780.         // soft
  13781.         float C = m_currentLength - m_length;
  13782.  
  13783.         float d = m_damping;
  13784.         float k = m_stiffness;
  13785.  
  13786.         // magic formulas
  13787.         float h = data.step.dt;
  13788.  
  13789.         // gamma = 1 / (h * (d + h * k))
  13790.         // the extra factor of h in the denominator is since the lambda is an impulse, not a force
  13791.         m_gamma = h * (d + h * k);
  13792.         m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f;
  13793.         m_bias = C * h * k * m_gamma;
  13794.  
  13795.         invMass += m_gamma;
  13796.         m_softMass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
  13797.     } else {
  13798.         // rigid
  13799.         m_gamma = 0.0f;
  13800.         m_bias = 0.0f;
  13801.         m_softMass = m_mass;
  13802.     }
  13803.  
  13804.     if (data.step.warmStarting) {
  13805.         // Scale the impulse to support a variable time step.
  13806.         m_impulse *= data.step.dtRatio;
  13807.         m_lowerImpulse *= data.step.dtRatio;
  13808.         m_upperImpulse *= data.step.dtRatio;
  13809.  
  13810.         b2Vec2 P = (m_impulse + m_lowerImpulse - m_upperImpulse) * m_u;
  13811.         vA -= m_invMassA * P;
  13812.         wA -= m_invIA * b2Cross(m_rA, P);
  13813.         vB += m_invMassB * P;
  13814.         wB += m_invIB * b2Cross(m_rB, P);
  13815.     } else {
  13816.         m_impulse = 0.0f;
  13817.     }
  13818.  
  13819.     data.velocities[m_indexA].v = vA;
  13820.     data.velocities[m_indexA].w = wA;
  13821.     data.velocities[m_indexB].v = vB;
  13822.     data.velocities[m_indexB].w = wB;
  13823. }
  13824.  
  13825. void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) {
  13826.     b2Vec2 vA = data.velocities[m_indexA].v;
  13827.     float wA = data.velocities[m_indexA].w;
  13828.     b2Vec2 vB = data.velocities[m_indexB].v;
  13829.     float wB = data.velocities[m_indexB].w;
  13830.  
  13831.     if (m_minLength < m_maxLength) {
  13832.         if (m_stiffness > 0.0f) {
  13833.             // Cdot = dot(u, v + cross(w, r))
  13834.             b2Vec2 vpA = vA + b2Cross(wA, m_rA);
  13835.             b2Vec2 vpB = vB + b2Cross(wB, m_rB);
  13836.             float Cdot = b2Dot(m_u, vpB - vpA);
  13837.  
  13838.             float impulse = -m_softMass * (Cdot + m_bias + m_gamma * m_impulse);
  13839.             m_impulse += impulse;
  13840.  
  13841.             b2Vec2 P = impulse * m_u;
  13842.             vA -= m_invMassA * P;
  13843.             wA -= m_invIA * b2Cross(m_rA, P);
  13844.             vB += m_invMassB * P;
  13845.             wB += m_invIB * b2Cross(m_rB, P);
  13846.         }
  13847.  
  13848.         // lower
  13849.         {
  13850.             float C = m_currentLength - m_minLength;
  13851.             float bias = b2Max(0.0f, C) * data.step.inv_dt;
  13852.  
  13853.             b2Vec2 vpA = vA + b2Cross(wA, m_rA);
  13854.             b2Vec2 vpB = vB + b2Cross(wB, m_rB);
  13855.             float Cdot = b2Dot(m_u, vpB - vpA);
  13856.  
  13857.             float impulse = -m_mass * (Cdot + bias);
  13858.             float oldImpulse = m_lowerImpulse;
  13859.             m_lowerImpulse = b2Max(0.0f, m_lowerImpulse + impulse);
  13860.             impulse = m_lowerImpulse - oldImpulse;
  13861.             b2Vec2 P = impulse * m_u;
  13862.  
  13863.             vA -= m_invMassA * P;
  13864.             wA -= m_invIA * b2Cross(m_rA, P);
  13865.             vB += m_invMassB * P;
  13866.             wB += m_invIB * b2Cross(m_rB, P);
  13867.         }
  13868.  
  13869.         // upper
  13870.         {
  13871.             float C = m_maxLength - m_currentLength;
  13872.             float bias = b2Max(0.0f, C) * data.step.inv_dt;
  13873.  
  13874.             b2Vec2 vpA = vA + b2Cross(wA, m_rA);
  13875.             b2Vec2 vpB = vB + b2Cross(wB, m_rB);
  13876.             float Cdot = b2Dot(m_u, vpA - vpB);
  13877.  
  13878.             float impulse = -m_mass * (Cdot + bias);
  13879.             float oldImpulse = m_upperImpulse;
  13880.             m_upperImpulse = b2Max(0.0f, m_upperImpulse + impulse);
  13881.             impulse = m_upperImpulse - oldImpulse;
  13882.             b2Vec2 P = -impulse * m_u;
  13883.  
  13884.             vA -= m_invMassA * P;
  13885.             wA -= m_invIA * b2Cross(m_rA, P);
  13886.             vB += m_invMassB * P;
  13887.             wB += m_invIB * b2Cross(m_rB, P);
  13888.         }
  13889.     } else {
  13890.         // Equal limits
  13891.  
  13892.         // Cdot = dot(u, v + cross(w, r))
  13893.         b2Vec2 vpA = vA + b2Cross(wA, m_rA);
  13894.         b2Vec2 vpB = vB + b2Cross(wB, m_rB);
  13895.         float Cdot = b2Dot(m_u, vpB - vpA);
  13896.  
  13897.         float impulse = -m_mass * Cdot;
  13898.         m_impulse += impulse;
  13899.  
  13900.         b2Vec2 P = impulse * m_u;
  13901.         vA -= m_invMassA * P;
  13902.         wA -= m_invIA * b2Cross(m_rA, P);
  13903.         vB += m_invMassB * P;
  13904.         wB += m_invIB * b2Cross(m_rB, P);
  13905.     }
  13906.  
  13907.     data.velocities[m_indexA].v = vA;
  13908.     data.velocities[m_indexA].w = wA;
  13909.     data.velocities[m_indexB].v = vB;
  13910.     data.velocities[m_indexB].w = wB;
  13911. }
  13912.  
  13913. bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) {
  13914.     b2Vec2 cA = data.positions[m_indexA].c;
  13915.     float aA = data.positions[m_indexA].a;
  13916.     b2Vec2 cB = data.positions[m_indexB].c;
  13917.     float aB = data.positions[m_indexB].a;
  13918.  
  13919.     b2Rot qA(aA), qB(aB);
  13920.  
  13921.     b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  13922.     b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  13923.     b2Vec2 u = cB + rB - cA - rA;
  13924.  
  13925.     float length = u.Normalize();
  13926.     float C;
  13927.     if (m_minLength == m_maxLength) {
  13928.         C = length - m_minLength;
  13929.     } else if (length < m_minLength) {
  13930.         C = length - m_minLength;
  13931.     } else if (m_maxLength < length) {
  13932.         C = length - m_maxLength;
  13933.     } else {
  13934.         return true;
  13935.     }
  13936.  
  13937.     float impulse = -m_mass * C;
  13938.     b2Vec2 P = impulse * u;
  13939.  
  13940.     cA -= m_invMassA * P;
  13941.     aA -= m_invIA * b2Cross(rA, P);
  13942.     cB += m_invMassB * P;
  13943.     aB += m_invIB * b2Cross(rB, P);
  13944.  
  13945.     data.positions[m_indexA].c = cA;
  13946.     data.positions[m_indexA].a = aA;
  13947.     data.positions[m_indexB].c = cB;
  13948.     data.positions[m_indexB].a = aB;
  13949.  
  13950.     return b2Abs(C) < b2_linearSlop;
  13951. }
  13952.  
  13953. b2Vec2 b2DistanceJoint::GetAnchorA() const {
  13954.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  13955. }
  13956.  
  13957. b2Vec2 b2DistanceJoint::GetAnchorB() const {
  13958.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  13959. }
  13960.  
  13961. b2Vec2 b2DistanceJoint::GetReactionForce(float inv_dt) const {
  13962.     b2Vec2 F = inv_dt * (m_impulse + m_lowerImpulse - m_upperImpulse) * m_u;
  13963.     return F;
  13964. }
  13965.  
  13966. float b2DistanceJoint::GetReactionTorque(float inv_dt) const {
  13967.     B2_NOT_USED(inv_dt);
  13968.     return 0.0f;
  13969. }
  13970.  
  13971. float b2DistanceJoint::SetLength(float length) {
  13972.     m_impulse = 0.0f;
  13973.     m_length = b2Max(b2_linearSlop, length);
  13974.     return m_length;
  13975. }
  13976.  
  13977. float b2DistanceJoint::SetMinLength(float minLength) {
  13978.     m_lowerImpulse = 0.0f;
  13979.     m_minLength = b2Clamp(minLength, b2_linearSlop, m_maxLength);
  13980.     return m_minLength;
  13981. }
  13982.  
  13983. float b2DistanceJoint::SetMaxLength(float maxLength) {
  13984.     m_upperImpulse = 0.0f;
  13985.     m_maxLength = b2Max(maxLength, m_minLength);
  13986.     return m_maxLength;
  13987. }
  13988.  
  13989. float b2DistanceJoint::GetCurrentLength() const {
  13990.     b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA);
  13991.     b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB);
  13992.     b2Vec2 d = pB - pA;
  13993.     float length = d.Length();
  13994.     return length;
  13995. }
  13996.  
  13997. void b2DistanceJoint::Dump() {
  13998.     int32 indexA = m_bodyA->m_islandIndex;
  13999.     int32 indexB = m_bodyB->m_islandIndex;
  14000.  
  14001.     b2Dump("  b2DistanceJointDef jd;\n");
  14002.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  14003.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  14004.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  14005.     b2Dump("  jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
  14006.     b2Dump("  jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
  14007.     b2Dump("  jd.length = %.9g;\n", m_length);
  14008.     b2Dump("  jd.minLength = %.9g;\n", m_minLength);
  14009.     b2Dump("  jd.maxLength = %.9g;\n", m_maxLength);
  14010.     b2Dump("  jd.stiffness = %.9g;\n", m_stiffness);
  14011.     b2Dump("  jd.damping = %.9g;\n", m_damping);
  14012.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  14013. }
  14014.  
  14015. void b2DistanceJoint::Draw(b2Draw* draw) const {
  14016.     const b2Transform& xfA = m_bodyA->GetTransform();
  14017.     const b2Transform& xfB = m_bodyB->GetTransform();
  14018.     b2Vec2 pA = b2Mul(xfA, m_localAnchorA);
  14019.     b2Vec2 pB = b2Mul(xfB, m_localAnchorB);
  14020.  
  14021.     b2Vec2 axis = pB - pA;
  14022.     float length = axis.Normalize();
  14023.  
  14024.     b2Color c1(0.7f, 0.7f, 0.7f);
  14025.     b2Color c2(0.3f, 0.9f, 0.3f);
  14026.     b2Color c3(0.9f, 0.3f, 0.3f);
  14027.     b2Color c4(0.4f, 0.4f, 0.4f);
  14028.  
  14029.     draw->DrawSegment(pA, pB, c4);
  14030.  
  14031.     b2Vec2 pRest = pA + m_length * axis;
  14032.     draw->DrawPoint(pRest, 8.0f, c1);
  14033.  
  14034.     if (m_minLength != m_maxLength) {
  14035.         if (m_minLength > b2_linearSlop) {
  14036.             b2Vec2 pMin = pA + m_minLength * axis;
  14037.             draw->DrawPoint(pMin, 4.0f, c2);
  14038.         }
  14039.  
  14040.         if (m_maxLength < FLT_MAX) {
  14041.             b2Vec2 pMax = pA + m_maxLength * axis;
  14042.             draw->DrawPoint(pMax, 4.0f, c3);
  14043.         }
  14044.     }
  14045. }
  14046. // MIT License
  14047.  
  14048. // Copyright (c) 2019 Erin Catto
  14049.  
  14050. // Permission is hereby granted, free of charge, to any person obtaining a copy
  14051. // of this software and associated documentation files (the "Software"), to deal
  14052. // in the Software without restriction, including without limitation the rights
  14053. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14054. // copies of the Software, and to permit persons to whom the Software is
  14055. // furnished to do so, subject to the following conditions:
  14056.  
  14057. // The above copyright notice and this permission notice shall be included in all
  14058. // copies or substantial portions of the Software.
  14059.  
  14060. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14061. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14062. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14063. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14064. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14065. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  14066. // SOFTWARE.
  14067.  
  14068. //#include "b2_edge_circle_contact.h"
  14069.  
  14070. //#include "box2d/b2_block_allocator.h"
  14071. //#include "box2d/b2_fixture.h"
  14072.  
  14073. #include <new>
  14074.  
  14075. b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) {
  14076.     void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact));
  14077.     return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB);
  14078. }
  14079.  
  14080. void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  14081.     ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact();
  14082.     allocator->Free(contact, sizeof(b2EdgeAndCircleContact));
  14083. }
  14084.  
  14085. b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
  14086.     : b2Contact(fixtureA, 0, fixtureB, 0) {
  14087.     b2Assert(m_fixtureA->GetType() == b2Shape::e_edge);
  14088.     b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
  14089. }
  14090.  
  14091. void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) {
  14092.     b2CollideEdgeAndCircle(manifold,
  14093.         (b2EdgeShape*)m_fixtureA->GetShape(), xfA,
  14094.         (b2CircleShape*)m_fixtureB->GetShape(), xfB);
  14095. }
  14096. // MIT License
  14097.  
  14098. // Copyright (c) 2019 Erin Catto
  14099.  
  14100. // Permission is hereby granted, free of charge, to any person obtaining a copy
  14101. // of this software and associated documentation files (the "Software"), to deal
  14102. // in the Software without restriction, including without limitation the rights
  14103. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14104. // copies of the Software, and to permit persons to whom the Software is
  14105. // furnished to do so, subject to the following conditions:
  14106.  
  14107. // The above copyright notice and this permission notice shall be included in all
  14108. // copies or substantial portions of the Software.
  14109.  
  14110. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14111. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14112. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14113. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14114. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14115. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  14116. // SOFTWARE.
  14117.  
  14118. //#include "b2_edge_polygon_contact.h"
  14119.  
  14120. //#include "box2d/b2_block_allocator.h"
  14121. //#include "box2d/b2_fixture.h"
  14122.  
  14123. #include <new>
  14124.  
  14125. b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) {
  14126.     void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact));
  14127.     return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB);
  14128. }
  14129.  
  14130. void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  14131.     ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact();
  14132.     allocator->Free(contact, sizeof(b2EdgeAndPolygonContact));
  14133. }
  14134.  
  14135. b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
  14136.     : b2Contact(fixtureA, 0, fixtureB, 0) {
  14137.     b2Assert(m_fixtureA->GetType() == b2Shape::e_edge);
  14138.     b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
  14139. }
  14140.  
  14141. void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) {
  14142.     b2CollideEdgeAndPolygon(manifold,
  14143.         (b2EdgeShape*)m_fixtureA->GetShape(), xfA,
  14144.         (b2PolygonShape*)m_fixtureB->GetShape(), xfB);
  14145. }
  14146. // MIT License
  14147.  
  14148. // Copyright (c) 2019 Erin Catto
  14149.  
  14150. // Permission is hereby granted, free of charge, to any person obtaining a copy
  14151. // of this software and associated documentation files (the "Software"), to deal
  14152. // in the Software without restriction, including without limitation the rights
  14153. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14154. // copies of the Software, and to permit persons to whom the Software is
  14155. // furnished to do so, subject to the following conditions:
  14156.  
  14157. // The above copyright notice and this permission notice shall be included in all
  14158. // copies or substantial portions of the Software.
  14159.  
  14160. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14161. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14162. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14163. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14164. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14165. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  14166. // SOFTWARE.
  14167.  
  14168. //#include "box2d/b2_fixture.h"
  14169. //#include "box2d/b2_block_allocator.h"
  14170. //#include "box2d/b2_broad_phase.h"
  14171. //#include "box2d/b2_chain_shape.h"
  14172. //#include "box2d/b2_circle_shape.h"
  14173. //#include "box2d/b2_collision.h"
  14174. //#include "box2d/b2_contact.h"
  14175. //#include "box2d/b2_edge_shape.h"
  14176. //#include "box2d/b2_polygon_shape.h"
  14177. //#include "box2d/b2_world.h"
  14178.  
  14179. b2Fixture::b2Fixture() {
  14180.     m_body = nullptr;
  14181.     m_next = nullptr;
  14182.     m_proxies = nullptr;
  14183.     m_proxyCount = 0;
  14184.     m_shape = nullptr;
  14185.     m_density = 0.0f;
  14186. }
  14187.  
  14188. void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) {
  14189.     m_userData = def->userData;
  14190.     m_friction = def->friction;
  14191.     m_restitution = def->restitution;
  14192.     m_restitutionThreshold = def->restitutionThreshold;
  14193.  
  14194.     m_body = body;
  14195.     m_next = nullptr;
  14196.  
  14197.     m_filter = def->filter;
  14198.  
  14199.     m_isSensor = def->isSensor;
  14200.  
  14201.     m_shape = def->shape->Clone(allocator);
  14202.  
  14203.     // Reserve proxy space
  14204.     int32 childCount = m_shape->GetChildCount();
  14205.     m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy));
  14206.     for (int32 i = 0; i < childCount; ++i) {
  14207.         m_proxies[i].fixture = nullptr;
  14208.         m_proxies[i].proxyId = b2BroadPhase::e_nullProxy;
  14209.     }
  14210.     m_proxyCount = 0;
  14211.  
  14212.     m_density = def->density;
  14213. }
  14214.  
  14215. void b2Fixture::Destroy(b2BlockAllocator* allocator) {
  14216.     // The proxies must be destroyed before calling this.
  14217.     b2Assert(m_proxyCount == 0);
  14218.  
  14219.     // Free the proxy array.
  14220.     int32 childCount = m_shape->GetChildCount();
  14221.     allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy));
  14222.     m_proxies = nullptr;
  14223.  
  14224.     // Free the child shape.
  14225.     switch (m_shape->m_type) {
  14226.     case b2Shape::e_circle:
  14227.     {
  14228.         b2CircleShape* s = (b2CircleShape*)m_shape;
  14229.         s->~b2CircleShape();
  14230.         allocator->Free(s, sizeof(b2CircleShape));
  14231.     }
  14232.     break;
  14233.  
  14234.     case b2Shape::e_edge:
  14235.     {
  14236.         b2EdgeShape* s = (b2EdgeShape*)m_shape;
  14237.         s->~b2EdgeShape();
  14238.         allocator->Free(s, sizeof(b2EdgeShape));
  14239.     }
  14240.     break;
  14241.  
  14242.     case b2Shape::e_polygon:
  14243.     {
  14244.         b2PolygonShape* s = (b2PolygonShape*)m_shape;
  14245.         s->~b2PolygonShape();
  14246.         allocator->Free(s, sizeof(b2PolygonShape));
  14247.     }
  14248.     break;
  14249.  
  14250.     case b2Shape::e_chain:
  14251.     {
  14252.         b2ChainShape* s = (b2ChainShape*)m_shape;
  14253.         s->~b2ChainShape();
  14254.         allocator->Free(s, sizeof(b2ChainShape));
  14255.     }
  14256.     break;
  14257.  
  14258.     default:
  14259.         b2Assert(false);
  14260.         break;
  14261.     }
  14262.  
  14263.     m_shape = nullptr;
  14264. }
  14265.  
  14266. void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) {
  14267.     b2Assert(m_proxyCount == 0);
  14268.  
  14269.     // Create proxies in the broad-phase.
  14270.     m_proxyCount = m_shape->GetChildCount();
  14271.  
  14272.     for (int32 i = 0; i < m_proxyCount; ++i) {
  14273.         b2FixtureProxy* proxy = m_proxies + i;
  14274.         m_shape->ComputeAABB(&proxy->aabb, xf, i);
  14275.         proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy);
  14276.         proxy->fixture = this;
  14277.         proxy->childIndex = i;
  14278.     }
  14279. }
  14280.  
  14281. void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) {
  14282.     // Destroy proxies in the broad-phase.
  14283.     for (int32 i = 0; i < m_proxyCount; ++i) {
  14284.         b2FixtureProxy* proxy = m_proxies + i;
  14285.         broadPhase->DestroyProxy(proxy->proxyId);
  14286.         proxy->proxyId = b2BroadPhase::e_nullProxy;
  14287.     }
  14288.  
  14289.     m_proxyCount = 0;
  14290. }
  14291.  
  14292. void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) {
  14293.     if (m_proxyCount == 0) {
  14294.         return;
  14295.     }
  14296.  
  14297.     for (int32 i = 0; i < m_proxyCount; ++i) {
  14298.         b2FixtureProxy* proxy = m_proxies + i;
  14299.  
  14300.         // Compute an AABB that covers the swept shape (may miss some rotation effect).
  14301.         b2AABB aabb1, aabb2;
  14302.         m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex);
  14303.         m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex);
  14304.  
  14305.         proxy->aabb.Combine(aabb1, aabb2);
  14306.  
  14307.         b2Vec2 displacement = aabb2.GetCenter() - aabb1.GetCenter();
  14308.  
  14309.         broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement);
  14310.     }
  14311. }
  14312.  
  14313. void b2Fixture::SetFilterData(const b2Filter& filter) {
  14314.     m_filter = filter;
  14315.  
  14316.     Refilter();
  14317. }
  14318.  
  14319. void b2Fixture::Refilter() {
  14320.     if (m_body == nullptr) {
  14321.         return;
  14322.     }
  14323.  
  14324.     // Flag associated contacts for filtering.
  14325.     b2ContactEdge* edge = m_body->GetContactList();
  14326.     while (edge) {
  14327.         b2Contact* contact = edge->contact;
  14328.         b2Fixture* fixtureA = contact->GetFixtureA();
  14329.         b2Fixture* fixtureB = contact->GetFixtureB();
  14330.         if (fixtureA == this || fixtureB == this) {
  14331.             contact->FlagForFiltering();
  14332.         }
  14333.  
  14334.         edge = edge->next;
  14335.     }
  14336.  
  14337.     b2World* world = m_body->GetWorld();
  14338.  
  14339.     if (world == nullptr) {
  14340.         return;
  14341.     }
  14342.  
  14343.     // Touch each proxy so that new pairs may be created
  14344.     b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase;
  14345.     for (int32 i = 0; i < m_proxyCount; ++i) {
  14346.         broadPhase->TouchProxy(m_proxies[i].proxyId);
  14347.     }
  14348. }
  14349.  
  14350. void b2Fixture::SetSensor(bool sensor) {
  14351.     if (sensor != m_isSensor) {
  14352.         m_body->SetAwake(true);
  14353.         m_isSensor = sensor;
  14354.     }
  14355. }
  14356.  
  14357. void b2Fixture::Dump(int32 bodyIndex) {
  14358.     b2Dump("    b2FixtureDef fd;\n");
  14359.     b2Dump("    fd.friction = %.9g;\n", m_friction);
  14360.     b2Dump("    fd.restitution = %.9g;\n", m_restitution);
  14361.     b2Dump("    fd.restitutionThreshold = %.9g;\n", m_restitutionThreshold);
  14362.     b2Dump("    fd.density = %.9g;\n", m_density);
  14363.     b2Dump("    fd.isSensor = bool(%d);\n", m_isSensor);
  14364.     b2Dump("    fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits);
  14365.     b2Dump("    fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits);
  14366.     b2Dump("    fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex);
  14367.  
  14368.     switch (m_shape->m_type) {
  14369.     case b2Shape::e_circle:
  14370.     {
  14371.         b2CircleShape* s = (b2CircleShape*)m_shape;
  14372.         b2Dump("    b2CircleShape shape;\n");
  14373.         b2Dump("    shape.m_radius = %.9g;\n", s->m_radius);
  14374.         b2Dump("    shape.m_p.Set(%.9g, %.9g);\n", s->m_p.x, s->m_p.y);
  14375.     }
  14376.     break;
  14377.  
  14378.     case b2Shape::e_edge:
  14379.     {
  14380.         b2EdgeShape* s = (b2EdgeShape*)m_shape;
  14381.         b2Dump("    b2EdgeShape shape;\n");
  14382.         b2Dump("    shape.m_radius = %.9g;\n", s->m_radius);
  14383.         b2Dump("    shape.m_vertex0.Set(%.9g, %.9g);\n", s->m_vertex0.x, s->m_vertex0.y);
  14384.         b2Dump("    shape.m_vertex1.Set(%.9g, %.9g);\n", s->m_vertex1.x, s->m_vertex1.y);
  14385.         b2Dump("    shape.m_vertex2.Set(%.9g, %.9g);\n", s->m_vertex2.x, s->m_vertex2.y);
  14386.         b2Dump("    shape.m_vertex3.Set(%.9g, %.9g);\n", s->m_vertex3.x, s->m_vertex3.y);
  14387.         b2Dump("    shape.m_oneSided = bool(%d);\n", s->m_oneSided);
  14388.     }
  14389.     break;
  14390.  
  14391.     case b2Shape::e_polygon:
  14392.     {
  14393.         b2PolygonShape* s = (b2PolygonShape*)m_shape;
  14394.         b2Dump("    b2PolygonShape shape;\n");
  14395.         b2Dump("    b2Vec2 vs[%d];\n", b2_maxPolygonVertices);
  14396.         for (int32 i = 0; i < s->m_count; ++i) {
  14397.             b2Dump("    vs[%d].Set(%.9g, %.9g);\n", i, s->m_vertices[i].x, s->m_vertices[i].y);
  14398.         }
  14399.         b2Dump("    shape.Set(vs, %d);\n", s->m_count);
  14400.     }
  14401.     break;
  14402.  
  14403.     case b2Shape::e_chain:
  14404.     {
  14405.         b2ChainShape* s = (b2ChainShape*)m_shape;
  14406.         b2Dump("    b2ChainShape shape;\n");
  14407.         b2Dump("    b2Vec2 vs[%d];\n", s->m_count);
  14408.         for (int32 i = 0; i < s->m_count; ++i) {
  14409.             b2Dump("    vs[%d].Set(%.9g, %.9g);\n", i, s->m_vertices[i].x, s->m_vertices[i].y);
  14410.         }
  14411.         b2Dump("    shape.CreateChain(vs, %d);\n", s->m_count);
  14412.         b2Dump("    shape.m_prevVertex.Set(%.9g, %.9g);\n", s->m_prevVertex.x, s->m_prevVertex.y);
  14413.         b2Dump("    shape.m_nextVertex.Set(%.9g, %.9g);\n", s->m_nextVertex.x, s->m_nextVertex.y);
  14414.     }
  14415.     break;
  14416.  
  14417.     default:
  14418.         return;
  14419.     }
  14420.  
  14421.     b2Dump("\n");
  14422.     b2Dump("    fd.shape = &shape;\n");
  14423.     b2Dump("\n");
  14424.     b2Dump("    bodies[%d]->CreateFixture(&fd);\n", bodyIndex);
  14425. }
  14426. // MIT License
  14427.  
  14428. // Copyright (c) 2019 Erin Catto
  14429.  
  14430. // Permission is hereby granted, free of charge, to any person obtaining a copy
  14431. // of this software and associated documentation files (the "Software"), to deal
  14432. // in the Software without restriction, including without limitation the rights
  14433. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14434. // copies of the Software, and to permit persons to whom the Software is
  14435. // furnished to do so, subject to the following conditions:
  14436.  
  14437. // The above copyright notice and this permission notice shall be included in all
  14438. // copies or substantial portions of the Software.
  14439.  
  14440. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14441. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14442. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14443. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14444. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14445. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  14446. // SOFTWARE.
  14447.  
  14448. //#include "box2d/b2_friction_joint.h"
  14449. //#include "box2d/b2_body.h"
  14450. //#include "box2d/b2_time_step.h"
  14451.  
  14452. // Point-to-point constraint
  14453. // Cdot = v2 - v1
  14454. //      = v2 + cross(w2, r2) - v1 - cross(w1, r1)
  14455. // J = [-I -r1_skew I r2_skew ]
  14456. // Identity used:
  14457. // w k % (rx i + ry j) = w * (-ry i + rx j)
  14458.  
  14459. // Angle constraint
  14460. // Cdot = w2 - w1
  14461. // J = [0 0 -1 0 0 1]
  14462. // K = invI1 + invI2
  14463.  
  14464. void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) {
  14465.     bodyA = bA;
  14466.     bodyB = bB;
  14467.     localAnchorA = bodyA->GetLocalPoint(anchor);
  14468.     localAnchorB = bodyB->GetLocalPoint(anchor);
  14469. }
  14470.  
  14471. b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def)
  14472.     : b2Joint(def) {
  14473.     m_localAnchorA = def->localAnchorA;
  14474.     m_localAnchorB = def->localAnchorB;
  14475.  
  14476.     m_linearImpulse.SetZero();
  14477.     m_angularImpulse = 0.0f;
  14478.  
  14479.     m_maxForce = def->maxForce;
  14480.     m_maxTorque = def->maxTorque;
  14481. }
  14482.  
  14483. void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) {
  14484.     m_indexA = m_bodyA->m_islandIndex;
  14485.     m_indexB = m_bodyB->m_islandIndex;
  14486.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  14487.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  14488.     m_invMassA = m_bodyA->m_invMass;
  14489.     m_invMassB = m_bodyB->m_invMass;
  14490.     m_invIA = m_bodyA->m_invI;
  14491.     m_invIB = m_bodyB->m_invI;
  14492.  
  14493.     float aA = data.positions[m_indexA].a;
  14494.     b2Vec2 vA = data.velocities[m_indexA].v;
  14495.     float wA = data.velocities[m_indexA].w;
  14496.  
  14497.     float aB = data.positions[m_indexB].a;
  14498.     b2Vec2 vB = data.velocities[m_indexB].v;
  14499.     float wB = data.velocities[m_indexB].w;
  14500.  
  14501.     b2Rot qA(aA), qB(aB);
  14502.  
  14503.     // Compute the effective mass matrix.
  14504.     m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  14505.     m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  14506.  
  14507.     // J = [-I -r1_skew I r2_skew]
  14508.     //     [ 0       -1 0       1]
  14509.     // r_skew = [-ry; rx]
  14510.  
  14511.     // Matlab
  14512.     // K = [ mA+r1y^2*iA+mB+r2y^2*iB,  -r1y*iA*r1x-r2y*iB*r2x,          -r1y*iA-r2y*iB]
  14513.     //     [  -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB,           r1x*iA+r2x*iB]
  14514.     //     [          -r1y*iA-r2y*iB,           r1x*iA+r2x*iB,                   iA+iB]
  14515.  
  14516.     float mA = m_invMassA, mB = m_invMassB;
  14517.     float iA = m_invIA, iB = m_invIB;
  14518.  
  14519.     b2Mat22 K;
  14520.     K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
  14521.     K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
  14522.     K.ey.x = K.ex.y;
  14523.     K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
  14524.  
  14525.     m_linearMass = K.GetInverse();
  14526.  
  14527.     m_angularMass = iA + iB;
  14528.     if (m_angularMass > 0.0f) {
  14529.         m_angularMass = 1.0f / m_angularMass;
  14530.     }
  14531.  
  14532.     if (data.step.warmStarting) {
  14533.         // Scale impulses to support a variable time step.
  14534.         m_linearImpulse *= data.step.dtRatio;
  14535.         m_angularImpulse *= data.step.dtRatio;
  14536.  
  14537.         b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
  14538.         vA -= mA * P;
  14539.         wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
  14540.         vB += mB * P;
  14541.         wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
  14542.     } else {
  14543.         m_linearImpulse.SetZero();
  14544.         m_angularImpulse = 0.0f;
  14545.     }
  14546.  
  14547.     data.velocities[m_indexA].v = vA;
  14548.     data.velocities[m_indexA].w = wA;
  14549.     data.velocities[m_indexB].v = vB;
  14550.     data.velocities[m_indexB].w = wB;
  14551. }
  14552.  
  14553. void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) {
  14554.     b2Vec2 vA = data.velocities[m_indexA].v;
  14555.     float wA = data.velocities[m_indexA].w;
  14556.     b2Vec2 vB = data.velocities[m_indexB].v;
  14557.     float wB = data.velocities[m_indexB].w;
  14558.  
  14559.     float mA = m_invMassA, mB = m_invMassB;
  14560.     float iA = m_invIA, iB = m_invIB;
  14561.  
  14562.     float h = data.step.dt;
  14563.  
  14564.     // Solve angular friction
  14565.     {
  14566.         float Cdot = wB - wA;
  14567.         float impulse = -m_angularMass * Cdot;
  14568.  
  14569.         float oldImpulse = m_angularImpulse;
  14570.         float maxImpulse = h * m_maxTorque;
  14571.         m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
  14572.         impulse = m_angularImpulse - oldImpulse;
  14573.  
  14574.         wA -= iA * impulse;
  14575.         wB += iB * impulse;
  14576.     }
  14577.  
  14578.     // Solve linear friction
  14579.     {
  14580.         b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
  14581.  
  14582.         b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
  14583.         b2Vec2 oldImpulse = m_linearImpulse;
  14584.         m_linearImpulse += impulse;
  14585.  
  14586.         float maxImpulse = h * m_maxForce;
  14587.  
  14588.         if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) {
  14589.             m_linearImpulse.Normalize();
  14590.             m_linearImpulse *= maxImpulse;
  14591.         }
  14592.  
  14593.         impulse = m_linearImpulse - oldImpulse;
  14594.  
  14595.         vA -= mA * impulse;
  14596.         wA -= iA * b2Cross(m_rA, impulse);
  14597.  
  14598.         vB += mB * impulse;
  14599.         wB += iB * b2Cross(m_rB, impulse);
  14600.     }
  14601.  
  14602.     data.velocities[m_indexA].v = vA;
  14603.     data.velocities[m_indexA].w = wA;
  14604.     data.velocities[m_indexB].v = vB;
  14605.     data.velocities[m_indexB].w = wB;
  14606. }
  14607.  
  14608. bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) {
  14609.     B2_NOT_USED(data);
  14610.  
  14611.     return true;
  14612. }
  14613.  
  14614. b2Vec2 b2FrictionJoint::GetAnchorA() const {
  14615.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  14616. }
  14617.  
  14618. b2Vec2 b2FrictionJoint::GetAnchorB() const {
  14619.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  14620. }
  14621.  
  14622. b2Vec2 b2FrictionJoint::GetReactionForce(float inv_dt) const {
  14623.     return inv_dt * m_linearImpulse;
  14624. }
  14625.  
  14626. float b2FrictionJoint::GetReactionTorque(float inv_dt) const {
  14627.     return inv_dt * m_angularImpulse;
  14628. }
  14629.  
  14630. void b2FrictionJoint::SetMaxForce(float force) {
  14631.     b2Assert(b2IsValid(force) && force >= 0.0f);
  14632.     m_maxForce = force;
  14633. }
  14634.  
  14635. float b2FrictionJoint::GetMaxForce() const {
  14636.     return m_maxForce;
  14637. }
  14638.  
  14639. void b2FrictionJoint::SetMaxTorque(float torque) {
  14640.     b2Assert(b2IsValid(torque) && torque >= 0.0f);
  14641.     m_maxTorque = torque;
  14642. }
  14643.  
  14644. float b2FrictionJoint::GetMaxTorque() const {
  14645.     return m_maxTorque;
  14646. }
  14647.  
  14648. void b2FrictionJoint::Dump() {
  14649.     int32 indexA = m_bodyA->m_islandIndex;
  14650.     int32 indexB = m_bodyB->m_islandIndex;
  14651.  
  14652.     b2Dump("  b2FrictionJointDef jd;\n");
  14653.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  14654.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  14655.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  14656.     b2Dump("  jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
  14657.     b2Dump("  jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
  14658.     b2Dump("  jd.maxForce = %.9g;\n", m_maxForce);
  14659.     b2Dump("  jd.maxTorque = %.9g;\n", m_maxTorque);
  14660.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  14661. }
  14662. // MIT License
  14663.  
  14664. // Copyright (c) 2019 Erin Catto
  14665.  
  14666. // Permission is hereby granted, free of charge, to any person obtaining a copy
  14667. // of this software and associated documentation files (the "Software"), to deal
  14668. // in the Software without restriction, including without limitation the rights
  14669. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14670. // copies of the Software, and to permit persons to whom the Software is
  14671. // furnished to do so, subject to the following conditions:
  14672.  
  14673. // The above copyright notice and this permission notice shall be included in all
  14674. // copies or substantial portions of the Software.
  14675.  
  14676. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14677. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14678. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14679. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14680. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14681. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  14682. // SOFTWARE.
  14683.  
  14684. //#include "box2d/b2_gear_joint.h"
  14685. //#include "box2d/b2_revolute_joint.h"
  14686. //#include "box2d/b2_prismatic_joint.h"
  14687. //#include "box2d/b2_body.h"
  14688. //#include "box2d/b2_time_step.h"
  14689.  
  14690. // Gear Joint:
  14691. // C0 = (coordinate1 + ratio * coordinate2)_initial
  14692. // C = (coordinate1 + ratio * coordinate2) - C0 = 0
  14693. // J = [J1 ratio * J2]
  14694. // K = J * invM * JT
  14695. //   = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T
  14696. //
  14697. // Revolute:
  14698. // coordinate = rotation
  14699. // Cdot = angularVelocity
  14700. // J = [0 0 1]
  14701. // K = J * invM * JT = invI
  14702. //
  14703. // Prismatic:
  14704. // coordinate = dot(p - pg, ug)
  14705. // Cdot = dot(v + cross(w, r), ug)
  14706. // J = [ug cross(r, ug)]
  14707. // K = J * invM * JT = invMass + invI * cross(r, ug)^2
  14708.  
  14709. b2GearJoint::b2GearJoint(const b2GearJointDef* def)
  14710.     : b2Joint(def) {
  14711.     m_joint1 = def->joint1;
  14712.     m_joint2 = def->joint2;
  14713.  
  14714.     m_typeA = m_joint1->GetType();
  14715.     m_typeB = m_joint2->GetType();
  14716.  
  14717.     b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint);
  14718.     b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint);
  14719.  
  14720.     float coordinateA, coordinateB;
  14721.  
  14722.     // TODO_ERIN there might be some problem with the joint edges in b2Joint.
  14723.  
  14724.     m_bodyC = m_joint1->GetBodyA();
  14725.     m_bodyA = m_joint1->GetBodyB();
  14726.  
  14727.     // Body B on joint1 must be dynamic
  14728.     b2Assert(m_bodyA->m_type == b2_dynamicBody);
  14729.  
  14730.     // Get geometry of joint1
  14731.     b2Transform xfA = m_bodyA->m_xf;
  14732.     float aA = m_bodyA->m_sweep.a;
  14733.     b2Transform xfC = m_bodyC->m_xf;
  14734.     float aC = m_bodyC->m_sweep.a;
  14735.  
  14736.     if (m_typeA == e_revoluteJoint) {
  14737.         b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1;
  14738.         m_localAnchorC = revolute->m_localAnchorA;
  14739.         m_localAnchorA = revolute->m_localAnchorB;
  14740.         m_referenceAngleA = revolute->m_referenceAngle;
  14741.         m_localAxisC.SetZero();
  14742.  
  14743.         coordinateA = aA - aC - m_referenceAngleA;
  14744.     } else {
  14745.         b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1;
  14746.         m_localAnchorC = prismatic->m_localAnchorA;
  14747.         m_localAnchorA = prismatic->m_localAnchorB;
  14748.         m_referenceAngleA = prismatic->m_referenceAngle;
  14749.         m_localAxisC = prismatic->m_localXAxisA;
  14750.  
  14751.         b2Vec2 pC = m_localAnchorC;
  14752.         b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p));
  14753.         coordinateA = b2Dot(pA - pC, m_localAxisC);
  14754.     }
  14755.  
  14756.     m_bodyD = m_joint2->GetBodyA();
  14757.     m_bodyB = m_joint2->GetBodyB();
  14758.  
  14759.     // Body B on joint2 must be dynamic
  14760.     b2Assert(m_bodyB->m_type == b2_dynamicBody);
  14761.  
  14762.     // Get geometry of joint2
  14763.     b2Transform xfB = m_bodyB->m_xf;
  14764.     float aB = m_bodyB->m_sweep.a;
  14765.     b2Transform xfD = m_bodyD->m_xf;
  14766.     float aD = m_bodyD->m_sweep.a;
  14767.  
  14768.     if (m_typeB == e_revoluteJoint) {
  14769.         b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2;
  14770.         m_localAnchorD = revolute->m_localAnchorA;
  14771.         m_localAnchorB = revolute->m_localAnchorB;
  14772.         m_referenceAngleB = revolute->m_referenceAngle;
  14773.         m_localAxisD.SetZero();
  14774.  
  14775.         coordinateB = aB - aD - m_referenceAngleB;
  14776.     } else {
  14777.         b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2;
  14778.         m_localAnchorD = prismatic->m_localAnchorA;
  14779.         m_localAnchorB = prismatic->m_localAnchorB;
  14780.         m_referenceAngleB = prismatic->m_referenceAngle;
  14781.         m_localAxisD = prismatic->m_localXAxisA;
  14782.  
  14783.         b2Vec2 pD = m_localAnchorD;
  14784.         b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p));
  14785.         coordinateB = b2Dot(pB - pD, m_localAxisD);
  14786.     }
  14787.  
  14788.     m_ratio = def->ratio;
  14789.  
  14790.     m_constant = coordinateA + m_ratio * coordinateB;
  14791.  
  14792.     m_impulse = 0.0f;
  14793. }
  14794.  
  14795. void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) {
  14796.     m_indexA = m_bodyA->m_islandIndex;
  14797.     m_indexB = m_bodyB->m_islandIndex;
  14798.     m_indexC = m_bodyC->m_islandIndex;
  14799.     m_indexD = m_bodyD->m_islandIndex;
  14800.     m_lcA = m_bodyA->m_sweep.localCenter;
  14801.     m_lcB = m_bodyB->m_sweep.localCenter;
  14802.     m_lcC = m_bodyC->m_sweep.localCenter;
  14803.     m_lcD = m_bodyD->m_sweep.localCenter;
  14804.     m_mA = m_bodyA->m_invMass;
  14805.     m_mB = m_bodyB->m_invMass;
  14806.     m_mC = m_bodyC->m_invMass;
  14807.     m_mD = m_bodyD->m_invMass;
  14808.     m_iA = m_bodyA->m_invI;
  14809.     m_iB = m_bodyB->m_invI;
  14810.     m_iC = m_bodyC->m_invI;
  14811.     m_iD = m_bodyD->m_invI;
  14812.  
  14813.     float aA = data.positions[m_indexA].a;
  14814.     b2Vec2 vA = data.velocities[m_indexA].v;
  14815.     float wA = data.velocities[m_indexA].w;
  14816.  
  14817.     float aB = data.positions[m_indexB].a;
  14818.     b2Vec2 vB = data.velocities[m_indexB].v;
  14819.     float wB = data.velocities[m_indexB].w;
  14820.  
  14821.     float aC = data.positions[m_indexC].a;
  14822.     b2Vec2 vC = data.velocities[m_indexC].v;
  14823.     float wC = data.velocities[m_indexC].w;
  14824.  
  14825.     float aD = data.positions[m_indexD].a;
  14826.     b2Vec2 vD = data.velocities[m_indexD].v;
  14827.     float wD = data.velocities[m_indexD].w;
  14828.  
  14829.     b2Rot qA(aA), qB(aB), qC(aC), qD(aD);
  14830.  
  14831.     m_mass = 0.0f;
  14832.  
  14833.     if (m_typeA == e_revoluteJoint) {
  14834.         m_JvAC.SetZero();
  14835.         m_JwA = 1.0f;
  14836.         m_JwC = 1.0f;
  14837.         m_mass += m_iA + m_iC;
  14838.     } else {
  14839.         b2Vec2 u = b2Mul(qC, m_localAxisC);
  14840.         b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC);
  14841.         b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA);
  14842.         m_JvAC = u;
  14843.         m_JwC = b2Cross(rC, u);
  14844.         m_JwA = b2Cross(rA, u);
  14845.         m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA;
  14846.     }
  14847.  
  14848.     if (m_typeB == e_revoluteJoint) {
  14849.         m_JvBD.SetZero();
  14850.         m_JwB = m_ratio;
  14851.         m_JwD = m_ratio;
  14852.         m_mass += m_ratio * m_ratio * (m_iB + m_iD);
  14853.     } else {
  14854.         b2Vec2 u = b2Mul(qD, m_localAxisD);
  14855.         b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD);
  14856.         b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB);
  14857.         m_JvBD = m_ratio * u;
  14858.         m_JwD = m_ratio * b2Cross(rD, u);
  14859.         m_JwB = m_ratio * b2Cross(rB, u);
  14860.         m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB;
  14861.     }
  14862.  
  14863.     // Compute effective mass.
  14864.     m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f;
  14865.  
  14866.     if (data.step.warmStarting) {
  14867.         vA += (m_mA * m_impulse) * m_JvAC;
  14868.         wA += m_iA * m_impulse * m_JwA;
  14869.         vB += (m_mB * m_impulse) * m_JvBD;
  14870.         wB += m_iB * m_impulse * m_JwB;
  14871.         vC -= (m_mC * m_impulse) * m_JvAC;
  14872.         wC -= m_iC * m_impulse * m_JwC;
  14873.         vD -= (m_mD * m_impulse) * m_JvBD;
  14874.         wD -= m_iD * m_impulse * m_JwD;
  14875.     } else {
  14876.         m_impulse = 0.0f;
  14877.     }
  14878.  
  14879.     data.velocities[m_indexA].v = vA;
  14880.     data.velocities[m_indexA].w = wA;
  14881.     data.velocities[m_indexB].v = vB;
  14882.     data.velocities[m_indexB].w = wB;
  14883.     data.velocities[m_indexC].v = vC;
  14884.     data.velocities[m_indexC].w = wC;
  14885.     data.velocities[m_indexD].v = vD;
  14886.     data.velocities[m_indexD].w = wD;
  14887. }
  14888.  
  14889. void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) {
  14890.     b2Vec2 vA = data.velocities[m_indexA].v;
  14891.     float wA = data.velocities[m_indexA].w;
  14892.     b2Vec2 vB = data.velocities[m_indexB].v;
  14893.     float wB = data.velocities[m_indexB].w;
  14894.     b2Vec2 vC = data.velocities[m_indexC].v;
  14895.     float wC = data.velocities[m_indexC].w;
  14896.     b2Vec2 vD = data.velocities[m_indexD].v;
  14897.     float wD = data.velocities[m_indexD].w;
  14898.  
  14899.     float Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD);
  14900.     Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD);
  14901.  
  14902.     float impulse = -m_mass * Cdot;
  14903.     m_impulse += impulse;
  14904.  
  14905.     vA += (m_mA * impulse) * m_JvAC;
  14906.     wA += m_iA * impulse * m_JwA;
  14907.     vB += (m_mB * impulse) * m_JvBD;
  14908.     wB += m_iB * impulse * m_JwB;
  14909.     vC -= (m_mC * impulse) * m_JvAC;
  14910.     wC -= m_iC * impulse * m_JwC;
  14911.     vD -= (m_mD * impulse) * m_JvBD;
  14912.     wD -= m_iD * impulse * m_JwD;
  14913.  
  14914.     data.velocities[m_indexA].v = vA;
  14915.     data.velocities[m_indexA].w = wA;
  14916.     data.velocities[m_indexB].v = vB;
  14917.     data.velocities[m_indexB].w = wB;
  14918.     data.velocities[m_indexC].v = vC;
  14919.     data.velocities[m_indexC].w = wC;
  14920.     data.velocities[m_indexD].v = vD;
  14921.     data.velocities[m_indexD].w = wD;
  14922. }
  14923.  
  14924. bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) {
  14925.     b2Vec2 cA = data.positions[m_indexA].c;
  14926.     float aA = data.positions[m_indexA].a;
  14927.     b2Vec2 cB = data.positions[m_indexB].c;
  14928.     float aB = data.positions[m_indexB].a;
  14929.     b2Vec2 cC = data.positions[m_indexC].c;
  14930.     float aC = data.positions[m_indexC].a;
  14931.     b2Vec2 cD = data.positions[m_indexD].c;
  14932.     float aD = data.positions[m_indexD].a;
  14933.  
  14934.     b2Rot qA(aA), qB(aB), qC(aC), qD(aD);
  14935.  
  14936.     float linearError = 0.0f;
  14937.  
  14938.     float coordinateA, coordinateB;
  14939.  
  14940.     b2Vec2 JvAC, JvBD;
  14941.     float JwA, JwB, JwC, JwD;
  14942.     float mass = 0.0f;
  14943.  
  14944.     if (m_typeA == e_revoluteJoint) {
  14945.         JvAC.SetZero();
  14946.         JwA = 1.0f;
  14947.         JwC = 1.0f;
  14948.         mass += m_iA + m_iC;
  14949.  
  14950.         coordinateA = aA - aC - m_referenceAngleA;
  14951.     } else {
  14952.         b2Vec2 u = b2Mul(qC, m_localAxisC);
  14953.         b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC);
  14954.         b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA);
  14955.         JvAC = u;
  14956.         JwC = b2Cross(rC, u);
  14957.         JwA = b2Cross(rA, u);
  14958.         mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA;
  14959.  
  14960.         b2Vec2 pC = m_localAnchorC - m_lcC;
  14961.         b2Vec2 pA = b2MulT(qC, rA + (cA - cC));
  14962.         coordinateA = b2Dot(pA - pC, m_localAxisC);
  14963.     }
  14964.  
  14965.     if (m_typeB == e_revoluteJoint) {
  14966.         JvBD.SetZero();
  14967.         JwB = m_ratio;
  14968.         JwD = m_ratio;
  14969.         mass += m_ratio * m_ratio * (m_iB + m_iD);
  14970.  
  14971.         coordinateB = aB - aD - m_referenceAngleB;
  14972.     } else {
  14973.         b2Vec2 u = b2Mul(qD, m_localAxisD);
  14974.         b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD);
  14975.         b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB);
  14976.         JvBD = m_ratio * u;
  14977.         JwD = m_ratio * b2Cross(rD, u);
  14978.         JwB = m_ratio * b2Cross(rB, u);
  14979.         mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB;
  14980.  
  14981.         b2Vec2 pD = m_localAnchorD - m_lcD;
  14982.         b2Vec2 pB = b2MulT(qD, rB + (cB - cD));
  14983.         coordinateB = b2Dot(pB - pD, m_localAxisD);
  14984.     }
  14985.  
  14986.     float C = (coordinateA + m_ratio * coordinateB) - m_constant;
  14987.  
  14988.     float impulse = 0.0f;
  14989.     if (mass > 0.0f) {
  14990.         impulse = -C / mass;
  14991.     }
  14992.  
  14993.     cA += m_mA * impulse * JvAC;
  14994.     aA += m_iA * impulse * JwA;
  14995.     cB += m_mB * impulse * JvBD;
  14996.     aB += m_iB * impulse * JwB;
  14997.     cC -= m_mC * impulse * JvAC;
  14998.     aC -= m_iC * impulse * JwC;
  14999.     cD -= m_mD * impulse * JvBD;
  15000.     aD -= m_iD * impulse * JwD;
  15001.  
  15002.     data.positions[m_indexA].c = cA;
  15003.     data.positions[m_indexA].a = aA;
  15004.     data.positions[m_indexB].c = cB;
  15005.     data.positions[m_indexB].a = aB;
  15006.     data.positions[m_indexC].c = cC;
  15007.     data.positions[m_indexC].a = aC;
  15008.     data.positions[m_indexD].c = cD;
  15009.     data.positions[m_indexD].a = aD;
  15010.  
  15011.     // TODO_ERIN not implemented
  15012.     return linearError < b2_linearSlop;
  15013. }
  15014.  
  15015. b2Vec2 b2GearJoint::GetAnchorA() const {
  15016.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  15017. }
  15018.  
  15019. b2Vec2 b2GearJoint::GetAnchorB() const {
  15020.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  15021. }
  15022.  
  15023. b2Vec2 b2GearJoint::GetReactionForce(float inv_dt) const {
  15024.     b2Vec2 P = m_impulse * m_JvAC;
  15025.     return inv_dt * P;
  15026. }
  15027.  
  15028. float b2GearJoint::GetReactionTorque(float inv_dt) const {
  15029.     float L = m_impulse * m_JwA;
  15030.     return inv_dt * L;
  15031. }
  15032.  
  15033. void b2GearJoint::SetRatio(float ratio) {
  15034.     b2Assert(b2IsValid(ratio));
  15035.     m_ratio = ratio;
  15036. }
  15037.  
  15038. float b2GearJoint::GetRatio() const {
  15039.     return m_ratio;
  15040. }
  15041.  
  15042. void b2GearJoint::Dump() {
  15043.     int32 indexA = m_bodyA->m_islandIndex;
  15044.     int32 indexB = m_bodyB->m_islandIndex;
  15045.  
  15046.     int32 index1 = m_joint1->m_index;
  15047.     int32 index2 = m_joint2->m_index;
  15048.  
  15049.     b2Dump("  b2GearJointDef jd;\n");
  15050.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  15051.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  15052.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  15053.     b2Dump("  jd.joint1 = joints[%d];\n", index1);
  15054.     b2Dump("  jd.joint2 = joints[%d];\n", index2);
  15055.     b2Dump("  jd.ratio = %.9g;\n", m_ratio);
  15056.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  15057. }
  15058. // MIT License
  15059.  
  15060. // Copyright (c) 2019 Erin Catto
  15061.  
  15062. // Permission is hereby granted, free of charge, to any person obtaining a copy
  15063. // of this software and associated documentation files (the "Software"), to deal
  15064. // in the Software without restriction, including without limitation the rights
  15065. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15066. // copies of the Software, and to permit persons to whom the Software is
  15067. // furnished to do so, subject to the following conditions:
  15068.  
  15069. // The above copyright notice and this permission notice shall be included in all
  15070. // copies or substantial portions of the Software.
  15071.  
  15072. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15073. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15074. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15075. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15076. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15077. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  15078. // SOFTWARE.
  15079.  
  15080. //#include "box2d/b2_body.h"
  15081. //#include "box2d/b2_contact.h"
  15082. //#include "box2d/b2_distance.h"
  15083. //#include "box2d/b2_fixture.h"
  15084. //#include "box2d/b2_joint.h"
  15085. //#include "box2d/b2_stack_allocator.h"
  15086. //#include "box2d/b2_timer.h"
  15087. //#include "box2d/b2_world.h"
  15088.  
  15089. //#include "b2_island.h"
  15090. //#include "dynamics/b2_contact_solver.h"
  15091.  
  15092. /*
  15093. Position Correction Notes
  15094. =========================
  15095. I tried the several algorithms for position correction of the 2D revolute joint.
  15096. I looked at these systems:
  15097. - simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s.
  15098. - suspension bridge with 30 1m long planks of length 1m.
  15099. - multi-link chain with 30 1m long links.
  15100.  
  15101. Here are the algorithms:
  15102.  
  15103. Baumgarte - A fraction of the position error is added to the velocity error. There is no
  15104. separate position solver.
  15105.  
  15106. Pseudo Velocities - After the velocity solver and position integration,
  15107. the position error, Jacobian, and effective mass are recomputed. Then
  15108. the velocity constraints are solved with pseudo velocities and a fraction
  15109. of the position error is added to the pseudo velocity error. The pseudo
  15110. velocities are initialized to zero and there is no warm-starting. After
  15111. the position solver, the pseudo velocities are added to the positions.
  15112. This is also called the First Order World method or the Position LCP method.
  15113.  
  15114. Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the
  15115. position error is re-computed for each constraint and the positions are updated
  15116. after the constraint is solved. The radius vectors (aka Jacobians) are
  15117. re-computed too (otherwise the algorithm has horrible instability). The pseudo
  15118. velocity states are not needed because they are effectively zero at the beginning
  15119. of each iteration. Since we have the current position error, we allow the
  15120. iterations to terminate early if the error becomes smaller than b2_linearSlop.
  15121.  
  15122. Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed
  15123. each time a constraint is solved.
  15124.  
  15125. Here are the results:
  15126. Baumgarte - this is the cheapest algorithm but it has some stability problems,
  15127. especially with the bridge. The chain links separate easily close to the root
  15128. and they jitter as they struggle to pull together. This is one of the most common
  15129. methods in the field. The big drawback is that the position correction artificially
  15130. affects the momentum, thus leading to instabilities and false bounce. I used a
  15131. bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller
  15132. factor makes joints and contacts more spongy.
  15133.  
  15134. Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is
  15135. stable. However, joints still separate with large angular velocities. Drag the
  15136. simple pendulum in a circle quickly and the joint will separate. The chain separates
  15137. easily and does not recover. I used a bias factor of 0.2. A larger value lead to
  15138. the bridge collapsing when a heavy cube drops on it.
  15139.  
  15140. Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo
  15141. Velocities, but in other ways it is worse. The bridge and chain are much more
  15142. stable, but the simple pendulum goes unstable at high angular velocities.
  15143.  
  15144. Full NGS - stable in all tests. The joints display good stiffness. The bridge
  15145. still sags, but this is better than infinite forces.
  15146.  
  15147. Recommendations
  15148. Pseudo Velocities are not really worthwhile because the bridge and chain cannot
  15149. recover from joint separation. In other cases the benefit over Baumgarte is small.
  15150.  
  15151. Modified NGS is not a robust method for the revolute joint due to the violent
  15152. instability seen in the simple pendulum. Perhaps it is viable with other constraint
  15153. types, especially scalar constraints where the effective mass is a scalar.
  15154.  
  15155. This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities
  15156. and is very fast. I don't think we can escape Baumgarte, especially in highly
  15157. demanding cases where high constraint fidelity is not needed.
  15158.  
  15159. Full NGS is robust and easy on the eyes. I recommend this as an option for
  15160. higher fidelity simulation and certainly for suspension bridges and long chains.
  15161. Full NGS might be a good choice for ragdolls, especially motorized ragdolls where
  15162. joint separation can be problematic. The number of NGS iterations can be reduced
  15163. for better performance without harming robustness much.
  15164.  
  15165. Each joint in a can be handled differently in the position solver. So I recommend
  15166. a system where the user can select the algorithm on a per joint basis. I would
  15167. probably default to the slower Full NGS and let the user select the faster
  15168. Baumgarte method in performance critical scenarios.
  15169. */
  15170.  
  15171. /*
  15172. Cache Performance
  15173.  
  15174. The Box2D solvers are dominated by cache misses. Data structures are designed
  15175. to increase the number of cache hits. Much of misses are due to random access
  15176. to body data. The constraint structures are iterated over linearly, which leads
  15177. to few cache misses.
  15178.  
  15179. The bodies are not accessed during iteration. Instead read only data, such as
  15180. the mass values are stored with the constraints. The mutable data are the constraint
  15181. impulses and the bodies velocities/positions. The impulses are held inside the
  15182. constraint structures. The body velocities/positions are held in compact, temporary
  15183. arrays to increase the number of cache hits. Linear and angular velocity are
  15184. stored in a single array since multiple arrays lead to multiple misses.
  15185. */
  15186.  
  15187. /*
  15188. 2D Rotation
  15189.  
  15190. R = [cos(theta) -sin(theta)]
  15191.     [sin(theta) cos(theta) ]
  15192.  
  15193. thetaDot = omega
  15194.  
  15195. Let q1 = cos(theta), q2 = sin(theta).
  15196. R = [q1 -q2]
  15197.     [q2  q1]
  15198.  
  15199. q1Dot = -thetaDot * q2
  15200. q2Dot = thetaDot * q1
  15201.  
  15202. q1_new = q1_old - dt * w * q2
  15203. q2_new = q2_old + dt * w * q1
  15204. then normalize.
  15205.  
  15206. This might be faster than computing sin+cos.
  15207. However, we can compute sin+cos of the same angle fast.
  15208. */
  15209.  
  15210. b2Island::b2Island(
  15211.     int32 bodyCapacity,
  15212.     int32 contactCapacity,
  15213.     int32 jointCapacity,
  15214.     b2StackAllocator* allocator,
  15215.     b2ContactListener* listener) {
  15216.     m_bodyCapacity = bodyCapacity;
  15217.     m_contactCapacity = contactCapacity;
  15218.     m_jointCapacity = jointCapacity;
  15219.     m_bodyCount = 0;
  15220.     m_contactCount = 0;
  15221.     m_jointCount = 0;
  15222.  
  15223.     m_allocator = allocator;
  15224.     m_listener = listener;
  15225.  
  15226.     m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*));
  15227.     m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*));
  15228.     m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*));
  15229.  
  15230.     m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity));
  15231.     m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position));
  15232. }
  15233.  
  15234. b2Island::~b2Island() {
  15235.     // Warning: the order should reverse the constructor order.
  15236.     m_allocator->Free(m_positions);
  15237.     m_allocator->Free(m_velocities);
  15238.     m_allocator->Free(m_joints);
  15239.     m_allocator->Free(m_contacts);
  15240.     m_allocator->Free(m_bodies);
  15241. }
  15242.  
  15243. void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) {
  15244.     b2Timer timer;
  15245.  
  15246.     float h = step.dt;
  15247.  
  15248.     // Integrate velocities and apply damping. Initialize the body state.
  15249.     for (int32 i = 0; i < m_bodyCount; ++i) {
  15250.         b2Body* b = m_bodies[i];
  15251.  
  15252.         b2Vec2 c = b->m_sweep.c;
  15253.         float a = b->m_sweep.a;
  15254.         b2Vec2 v = b->m_linearVelocity;
  15255.         float w = b->m_angularVelocity;
  15256.  
  15257.         // Store positions for continuous collision.
  15258.         b->m_sweep.c0 = b->m_sweep.c;
  15259.         b->m_sweep.a0 = b->m_sweep.a;
  15260.  
  15261.         if (b->m_type == b2_dynamicBody) {
  15262.             // Integrate velocities.
  15263.             v += h * b->m_invMass * (b->m_gravityScale * b->m_mass * gravity + b->m_force);
  15264.             w += h * b->m_invI * b->m_torque;
  15265.  
  15266.             // Apply damping.
  15267.             // ODE: dv/dt + c * v = 0
  15268.             // Solution: v(t) = v0 * exp(-c * t)
  15269.             // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
  15270.             // v2 = exp(-c * dt) * v1
  15271.             // Pade approximation:
  15272.             // v2 = v1 * 1 / (1 + c * dt)
  15273.             v *= 1.0f / (1.0f + h * b->m_linearDamping);
  15274.             w *= 1.0f / (1.0f + h * b->m_angularDamping);
  15275.         }
  15276.  
  15277.         m_positions[i].c = c;
  15278.         m_positions[i].a = a;
  15279.         m_velocities[i].v = v;
  15280.         m_velocities[i].w = w;
  15281.     }
  15282.  
  15283.     timer.Reset();
  15284.  
  15285.     // Solver data
  15286.     b2SolverData solverData;
  15287.     solverData.step = step;
  15288.     solverData.positions = m_positions;
  15289.     solverData.velocities = m_velocities;
  15290.  
  15291.     // Initialize velocity constraints.
  15292.     b2ContactSolverDef contactSolverDef;
  15293.     contactSolverDef.step = step;
  15294.     contactSolverDef.contacts = m_contacts;
  15295.     contactSolverDef.count = m_contactCount;
  15296.     contactSolverDef.positions = m_positions;
  15297.     contactSolverDef.velocities = m_velocities;
  15298.     contactSolverDef.allocator = m_allocator;
  15299.  
  15300.     b2ContactSolver contactSolver(&contactSolverDef);
  15301.     contactSolver.InitializeVelocityConstraints();
  15302.  
  15303.     if (step.warmStarting) {
  15304.         contactSolver.WarmStart();
  15305.     }
  15306.  
  15307.     for (int32 i = 0; i < m_jointCount; ++i) {
  15308.         m_joints[i]->InitVelocityConstraints(solverData);
  15309.     }
  15310.  
  15311.     profile->solveInit = timer.GetMilliseconds();
  15312.  
  15313.     // Solve velocity constraints
  15314.     timer.Reset();
  15315.     for (int32 i = 0; i < step.velocityIterations; ++i) {
  15316.         for (int32 j = 0; j < m_jointCount; ++j) {
  15317.             m_joints[j]->SolveVelocityConstraints(solverData);
  15318.         }
  15319.  
  15320.         contactSolver.SolveVelocityConstraints();
  15321.     }
  15322.  
  15323.     // Store impulses for warm starting
  15324.     contactSolver.StoreImpulses();
  15325.     profile->solveVelocity = timer.GetMilliseconds();
  15326.  
  15327.     // Integrate positions
  15328.     for (int32 i = 0; i < m_bodyCount; ++i) {
  15329.         b2Vec2 c = m_positions[i].c;
  15330.         float a = m_positions[i].a;
  15331.         b2Vec2 v = m_velocities[i].v;
  15332.         float w = m_velocities[i].w;
  15333.  
  15334.         // Check for large velocities
  15335.         b2Vec2 translation = h * v;
  15336.         if (b2Dot(translation, translation) > b2_maxTranslationSquared) {
  15337.             float ratio = b2_maxTranslation / translation.Length();
  15338.             v *= ratio;
  15339.         }
  15340.  
  15341.         float rotation = h * w;
  15342.         if (rotation * rotation > b2_maxRotationSquared) {
  15343.             float ratio = b2_maxRotation / b2Abs(rotation);
  15344.             w *= ratio;
  15345.         }
  15346.  
  15347.         // Integrate
  15348.         c += h * v;
  15349.         a += h * w;
  15350.  
  15351.         m_positions[i].c = c;
  15352.         m_positions[i].a = a;
  15353.         m_velocities[i].v = v;
  15354.         m_velocities[i].w = w;
  15355.     }
  15356.  
  15357.     // Solve position constraints
  15358.     timer.Reset();
  15359.     bool positionSolved = false;
  15360.     for (int32 i = 0; i < step.positionIterations; ++i) {
  15361.         bool contactsOkay = contactSolver.SolvePositionConstraints();
  15362.  
  15363.         bool jointsOkay = true;
  15364.         for (int32 j = 0; j < m_jointCount; ++j) {
  15365.             bool jointOkay = m_joints[j]->SolvePositionConstraints(solverData);
  15366.             jointsOkay = jointsOkay && jointOkay;
  15367.         }
  15368.  
  15369.         if (contactsOkay && jointsOkay) {
  15370.             // Exit early if the position errors are small.
  15371.             positionSolved = true;
  15372.             break;
  15373.         }
  15374.     }
  15375.  
  15376.     // Copy state buffers back to the bodies
  15377.     for (int32 i = 0; i < m_bodyCount; ++i) {
  15378.         b2Body* body = m_bodies[i];
  15379.         body->m_sweep.c = m_positions[i].c;
  15380.         body->m_sweep.a = m_positions[i].a;
  15381.         body->m_linearVelocity = m_velocities[i].v;
  15382.         body->m_angularVelocity = m_velocities[i].w;
  15383.         body->SynchronizeTransform();
  15384.     }
  15385.  
  15386.     profile->solvePosition = timer.GetMilliseconds();
  15387.  
  15388.     Report(contactSolver.m_velocityConstraints);
  15389.  
  15390.     if (allowSleep) {
  15391.         float minSleepTime = b2_maxFloat;
  15392.  
  15393.         const float linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance;
  15394.         const float angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance;
  15395.  
  15396.         for (int32 i = 0; i < m_bodyCount; ++i) {
  15397.             b2Body* b = m_bodies[i];
  15398.             if (b->GetType() == b2_staticBody) {
  15399.                 continue;
  15400.             }
  15401.  
  15402.             if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 ||
  15403.                 b->m_angularVelocity * b->m_angularVelocity > angTolSqr ||
  15404.                 b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) {
  15405.                 b->m_sleepTime = 0.0f;
  15406.                 minSleepTime = 0.0f;
  15407.             } else {
  15408.                 b->m_sleepTime += h;
  15409.                 minSleepTime = b2Min(minSleepTime, b->m_sleepTime);
  15410.             }
  15411.         }
  15412.  
  15413.         if (minSleepTime >= b2_timeToSleep && positionSolved) {
  15414.             for (int32 i = 0; i < m_bodyCount; ++i) {
  15415.                 b2Body* b = m_bodies[i];
  15416.                 b->SetAwake(false);
  15417.             }
  15418.         }
  15419.     }
  15420. }
  15421.  
  15422. void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) {
  15423.     b2Assert(toiIndexA < m_bodyCount);
  15424.     b2Assert(toiIndexB < m_bodyCount);
  15425.  
  15426.     // Initialize the body state.
  15427.     for (int32 i = 0; i < m_bodyCount; ++i) {
  15428.         b2Body* b = m_bodies[i];
  15429.         m_positions[i].c = b->m_sweep.c;
  15430.         m_positions[i].a = b->m_sweep.a;
  15431.         m_velocities[i].v = b->m_linearVelocity;
  15432.         m_velocities[i].w = b->m_angularVelocity;
  15433.     }
  15434.  
  15435.     b2ContactSolverDef contactSolverDef;
  15436.     contactSolverDef.contacts = m_contacts;
  15437.     contactSolverDef.count = m_contactCount;
  15438.     contactSolverDef.allocator = m_allocator;
  15439.     contactSolverDef.step = subStep;
  15440.     contactSolverDef.positions = m_positions;
  15441.     contactSolverDef.velocities = m_velocities;
  15442.     b2ContactSolver contactSolver(&contactSolverDef);
  15443.  
  15444.     // Solve position constraints.
  15445.     for (int32 i = 0; i < subStep.positionIterations; ++i) {
  15446.         bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB);
  15447.         if (contactsOkay) {
  15448.             break;
  15449.         }
  15450.     }
  15451.  
  15452. #if 0
  15453.     // Is the new position really safe?
  15454.     for (int32 i = 0; i < m_contactCount; ++i) {
  15455.         b2Contact* c = m_contacts[i];
  15456.         b2Fixture* fA = c->GetFixtureA();
  15457.         b2Fixture* fB = c->GetFixtureB();
  15458.  
  15459.         b2Body* bA = fA->GetBody();
  15460.         b2Body* bB = fB->GetBody();
  15461.  
  15462.         int32 indexA = c->GetChildIndexA();
  15463.         int32 indexB = c->GetChildIndexB();
  15464.  
  15465.         b2DistanceInput input;
  15466.         input.proxyA.Set(fA->GetShape(), indexA);
  15467.         input.proxyB.Set(fB->GetShape(), indexB);
  15468.         input.transformA = bA->GetTransform();
  15469.         input.transformB = bB->GetTransform();
  15470.         input.useRadii = false;
  15471.  
  15472.         b2DistanceOutput output;
  15473.         b2SimplexCache cache;
  15474.         cache.count = 0;
  15475.         b2Distance(&output, &cache, &input);
  15476.  
  15477.         if (output.distance == 0 || cache.count == 3) {
  15478.             cache.count += 0;
  15479.         }
  15480.     }
  15481. #endif
  15482.  
  15483.     // Leap of faith to new safe state.
  15484.     m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c;
  15485.     m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a;
  15486.     m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c;
  15487.     m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a;
  15488.  
  15489.     // No warm starting is needed for TOI events because warm
  15490.     // starting impulses were applied in the discrete solver.
  15491.     contactSolver.InitializeVelocityConstraints();
  15492.  
  15493.     // Solve velocity constraints.
  15494.     for (int32 i = 0; i < subStep.velocityIterations; ++i) {
  15495.         contactSolver.SolveVelocityConstraints();
  15496.     }
  15497.  
  15498.     // Don't store the TOI contact forces for warm starting
  15499.     // because they can be quite large.
  15500.  
  15501.     float h = subStep.dt;
  15502.  
  15503.     // Integrate positions
  15504.     for (int32 i = 0; i < m_bodyCount; ++i) {
  15505.         b2Vec2 c = m_positions[i].c;
  15506.         float a = m_positions[i].a;
  15507.         b2Vec2 v = m_velocities[i].v;
  15508.         float w = m_velocities[i].w;
  15509.  
  15510.         // Check for large velocities
  15511.         b2Vec2 translation = h * v;
  15512.         if (b2Dot(translation, translation) > b2_maxTranslationSquared) {
  15513.             float ratio = b2_maxTranslation / translation.Length();
  15514.             v *= ratio;
  15515.         }
  15516.  
  15517.         float rotation = h * w;
  15518.         if (rotation * rotation > b2_maxRotationSquared) {
  15519.             float ratio = b2_maxRotation / b2Abs(rotation);
  15520.             w *= ratio;
  15521.         }
  15522.  
  15523.         // Integrate
  15524.         c += h * v;
  15525.         a += h * w;
  15526.  
  15527.         m_positions[i].c = c;
  15528.         m_positions[i].a = a;
  15529.         m_velocities[i].v = v;
  15530.         m_velocities[i].w = w;
  15531.  
  15532.         // Sync bodies
  15533.         b2Body* body = m_bodies[i];
  15534.         body->m_sweep.c = c;
  15535.         body->m_sweep.a = a;
  15536.         body->m_linearVelocity = v;
  15537.         body->m_angularVelocity = w;
  15538.         body->SynchronizeTransform();
  15539.     }
  15540.  
  15541.     Report(contactSolver.m_velocityConstraints);
  15542. }
  15543.  
  15544. void b2Island::Report(const b2ContactVelocityConstraint* constraints) {
  15545.     if (m_listener == nullptr) {
  15546.         return;
  15547.     }
  15548.  
  15549.     for (int32 i = 0; i < m_contactCount; ++i) {
  15550.         b2Contact* c = m_contacts[i];
  15551.  
  15552.         const b2ContactVelocityConstraint* vc = constraints + i;
  15553.  
  15554.         b2ContactImpulse impulse;
  15555.         impulse.count = vc->pointCount;
  15556.         for (int32 j = 0; j < vc->pointCount; ++j) {
  15557.             impulse.normalImpulses[j] = vc->points[j].normalImpulse;
  15558.             impulse.tangentImpulses[j] = vc->points[j].tangentImpulse;
  15559.         }
  15560.  
  15561.         m_listener->PostSolve(c, &impulse);
  15562.     }
  15563. }
  15564. // MIT License
  15565.  
  15566. // Copyright (c) 2019 Erin Catto
  15567.  
  15568. // Permission is hereby granted, free of charge, to any person obtaining a copy
  15569. // of this software and associated documentation files (the "Software"), to deal
  15570. // in the Software without restriction, including without limitation the rights
  15571. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15572. // copies of the Software, and to permit persons to whom the Software is
  15573. // furnished to do so, subject to the following conditions:
  15574.  
  15575. // The above copyright notice and this permission notice shall be included in all
  15576. // copies or substantial portions of the Software.
  15577.  
  15578. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15579. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15580. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15581. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15582. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15583. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  15584. // SOFTWARE.
  15585.  
  15586. //#include "box2d/b2_block_allocator.h"
  15587. //#include "box2d/b2_body.h"
  15588. //#include "box2d/b2_distance_joint.h"
  15589. //#include "box2d/b2_draw.h"
  15590. //#include "box2d/b2_friction_joint.h"
  15591. //#include "box2d/b2_gear_joint.h"
  15592. //#include "box2d/b2_motor_joint.h"
  15593. //#include "box2d/b2_mouse_joint.h"
  15594. //#include "box2d/b2_prismatic_joint.h"
  15595. //#include "box2d/b2_pulley_joint.h"
  15596. //#include "box2d/b2_revolute_joint.h"
  15597. //#include "box2d/b2_weld_joint.h"
  15598. //#include "box2d/b2_wheel_joint.h"
  15599. //#include "box2d/b2_world.h"
  15600.  
  15601. #include <new>
  15602.  
  15603. void b2LinearStiffness(float& stiffness, float& damping,
  15604.     float frequencyHertz, float dampingRatio,
  15605.     const b2Body* bodyA, const b2Body* bodyB) {
  15606.     float massA = bodyA->GetMass();
  15607.     float massB = bodyB->GetMass();
  15608.     float mass;
  15609.     if (massA > 0.0f && massB > 0.0f) {
  15610.         mass = massA * massB / (massA + massB);
  15611.     } else if (massA > 0.0f) {
  15612.         mass = massA;
  15613.     } else {
  15614.         mass = massB;
  15615.     }
  15616.  
  15617.     float omega = 2.0f * b2_pi * frequencyHertz;
  15618.     stiffness = mass * omega * omega;
  15619.     damping = 2.0f * mass * dampingRatio * omega;
  15620. }
  15621.  
  15622. void b2AngularStiffness(float& stiffness, float& damping,
  15623.     float frequencyHertz, float dampingRatio,
  15624.     const b2Body* bodyA, const b2Body* bodyB) {
  15625.     float IA = bodyA->GetInertia();
  15626.     float IB = bodyB->GetInertia();
  15627.     float I;
  15628.     if (IA > 0.0f && IB > 0.0f) {
  15629.         I = IA * IB / (IA + IB);
  15630.     } else if (IA > 0.0f) {
  15631.         I = IA;
  15632.     } else {
  15633.         I = IB;
  15634.     }
  15635.  
  15636.     float omega = 2.0f * b2_pi * frequencyHertz;
  15637.     stiffness = I * omega * omega;
  15638.     damping = 2.0f * I * dampingRatio * omega;
  15639. }
  15640.  
  15641. b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) {
  15642.     b2Joint* joint = nullptr;
  15643.  
  15644.     switch (def->type) {
  15645.     case e_distanceJoint:
  15646.     {
  15647.         void* mem = allocator->Allocate(sizeof(b2DistanceJoint));
  15648.         joint = new (mem) b2DistanceJoint(static_cast<const b2DistanceJointDef*>(def));
  15649.     }
  15650.     break;
  15651.  
  15652.     case e_mouseJoint:
  15653.     {
  15654.         void* mem = allocator->Allocate(sizeof(b2MouseJoint));
  15655.         joint = new (mem) b2MouseJoint(static_cast<const b2MouseJointDef*>(def));
  15656.     }
  15657.     break;
  15658.  
  15659.     case e_prismaticJoint:
  15660.     {
  15661.         void* mem = allocator->Allocate(sizeof(b2PrismaticJoint));
  15662.         joint = new (mem) b2PrismaticJoint(static_cast<const b2PrismaticJointDef*>(def));
  15663.     }
  15664.     break;
  15665.  
  15666.     case e_revoluteJoint:
  15667.     {
  15668.         void* mem = allocator->Allocate(sizeof(b2RevoluteJoint));
  15669.         joint = new (mem) b2RevoluteJoint(static_cast<const b2RevoluteJointDef*>(def));
  15670.     }
  15671.     break;
  15672.  
  15673.     case e_pulleyJoint:
  15674.     {
  15675.         void* mem = allocator->Allocate(sizeof(b2PulleyJoint));
  15676.         joint = new (mem) b2PulleyJoint(static_cast<const b2PulleyJointDef*>(def));
  15677.     }
  15678.     break;
  15679.  
  15680.     case e_gearJoint:
  15681.     {
  15682.         void* mem = allocator->Allocate(sizeof(b2GearJoint));
  15683.         joint = new (mem) b2GearJoint(static_cast<const b2GearJointDef*>(def));
  15684.     }
  15685.     break;
  15686.  
  15687.     case e_wheelJoint:
  15688.     {
  15689.         void* mem = allocator->Allocate(sizeof(b2WheelJoint));
  15690.         joint = new (mem) b2WheelJoint(static_cast<const b2WheelJointDef*>(def));
  15691.     }
  15692.     break;
  15693.  
  15694.     case e_weldJoint:
  15695.     {
  15696.         void* mem = allocator->Allocate(sizeof(b2WeldJoint));
  15697.         joint = new (mem) b2WeldJoint(static_cast<const b2WeldJointDef*>(def));
  15698.     }
  15699.     break;
  15700.  
  15701.     case e_frictionJoint:
  15702.     {
  15703.         void* mem = allocator->Allocate(sizeof(b2FrictionJoint));
  15704.         joint = new (mem) b2FrictionJoint(static_cast<const b2FrictionJointDef*>(def));
  15705.     }
  15706.     break;
  15707.  
  15708.     case e_motorJoint:
  15709.     {
  15710.         void* mem = allocator->Allocate(sizeof(b2MotorJoint));
  15711.         joint = new (mem) b2MotorJoint(static_cast<const b2MotorJointDef*>(def));
  15712.     }
  15713.     break;
  15714.  
  15715.     default:
  15716.         b2Assert(false);
  15717.         break;
  15718.     }
  15719.  
  15720.     return joint;
  15721. }
  15722.  
  15723. void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) {
  15724.     joint->~b2Joint();
  15725.     switch (joint->m_type) {
  15726.     case e_distanceJoint:
  15727.         allocator->Free(joint, sizeof(b2DistanceJoint));
  15728.         break;
  15729.  
  15730.     case e_mouseJoint:
  15731.         allocator->Free(joint, sizeof(b2MouseJoint));
  15732.         break;
  15733.  
  15734.     case e_prismaticJoint:
  15735.         allocator->Free(joint, sizeof(b2PrismaticJoint));
  15736.         break;
  15737.  
  15738.     case e_revoluteJoint:
  15739.         allocator->Free(joint, sizeof(b2RevoluteJoint));
  15740.         break;
  15741.  
  15742.     case e_pulleyJoint:
  15743.         allocator->Free(joint, sizeof(b2PulleyJoint));
  15744.         break;
  15745.  
  15746.     case e_gearJoint:
  15747.         allocator->Free(joint, sizeof(b2GearJoint));
  15748.         break;
  15749.  
  15750.     case e_wheelJoint:
  15751.         allocator->Free(joint, sizeof(b2WheelJoint));
  15752.         break;
  15753.  
  15754.     case e_weldJoint:
  15755.         allocator->Free(joint, sizeof(b2WeldJoint));
  15756.         break;
  15757.  
  15758.     case e_frictionJoint:
  15759.         allocator->Free(joint, sizeof(b2FrictionJoint));
  15760.         break;
  15761.  
  15762.     case e_motorJoint:
  15763.         allocator->Free(joint, sizeof(b2MotorJoint));
  15764.         break;
  15765.  
  15766.     default:
  15767.         b2Assert(false);
  15768.         break;
  15769.     }
  15770. }
  15771.  
  15772. b2Joint::b2Joint(const b2JointDef* def) {
  15773.     b2Assert(def->bodyA != def->bodyB);
  15774.  
  15775.     m_type = def->type;
  15776.     m_prev = nullptr;
  15777.     m_next = nullptr;
  15778.     m_bodyA = def->bodyA;
  15779.     m_bodyB = def->bodyB;
  15780.     m_index = 0;
  15781.     m_collideConnected = def->collideConnected;
  15782.     m_islandFlag = false;
  15783.     m_userData = def->userData;
  15784.  
  15785.     m_edgeA.joint = nullptr;
  15786.     m_edgeA.other = nullptr;
  15787.     m_edgeA.prev = nullptr;
  15788.     m_edgeA.next = nullptr;
  15789.  
  15790.     m_edgeB.joint = nullptr;
  15791.     m_edgeB.other = nullptr;
  15792.     m_edgeB.prev = nullptr;
  15793.     m_edgeB.next = nullptr;
  15794. }
  15795.  
  15796. bool b2Joint::IsEnabled() const {
  15797.     return m_bodyA->IsEnabled() && m_bodyB->IsEnabled();
  15798. }
  15799.  
  15800. void b2Joint::Draw(b2Draw* draw) const {
  15801.     const b2Transform& xf1 = m_bodyA->GetTransform();
  15802.     const b2Transform& xf2 = m_bodyB->GetTransform();
  15803.     b2Vec2 x1 = xf1.p;
  15804.     b2Vec2 x2 = xf2.p;
  15805.     b2Vec2 p1 = GetAnchorA();
  15806.     b2Vec2 p2 = GetAnchorB();
  15807.  
  15808.     b2Color color(0.5f, 0.8f, 0.8f);
  15809.  
  15810.     switch (m_type) {
  15811.     case e_distanceJoint:
  15812.         draw->DrawSegment(p1, p2, color);
  15813.         break;
  15814.  
  15815.     case e_pulleyJoint:
  15816.     {
  15817.         b2PulleyJoint* pulley = (b2PulleyJoint*)this;
  15818.         b2Vec2 s1 = pulley->GetGroundAnchorA();
  15819.         b2Vec2 s2 = pulley->GetGroundAnchorB();
  15820.         draw->DrawSegment(s1, p1, color);
  15821.         draw->DrawSegment(s2, p2, color);
  15822.         draw->DrawSegment(s1, s2, color);
  15823.     }
  15824.     break;
  15825.  
  15826.     case e_mouseJoint:
  15827.     {
  15828.         b2Color c;
  15829.         c.Set(0.0f, 1.0f, 0.0f);
  15830.         draw->DrawPoint(p1, 4.0f, c);
  15831.         draw->DrawPoint(p2, 4.0f, c);
  15832.  
  15833.         c.Set(0.8f, 0.8f, 0.8f);
  15834.         draw->DrawSegment(p1, p2, c);
  15835.  
  15836.     }
  15837.     break;
  15838.  
  15839.     default:
  15840.         draw->DrawSegment(x1, p1, color);
  15841.         draw->DrawSegment(p1, p2, color);
  15842.         draw->DrawSegment(x2, p2, color);
  15843.     }
  15844. }
  15845. // MIT License
  15846.  
  15847. // Copyright (c) 2019 Erin Catto
  15848.  
  15849. // Permission is hereby granted, free of charge, to any person obtaining a copy
  15850. // of this software and associated documentation files (the "Software"), to deal
  15851. // in the Software without restriction, including without limitation the rights
  15852. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15853. // copies of the Software, and to permit persons to whom the Software is
  15854. // furnished to do so, subject to the following conditions:
  15855.  
  15856. // The above copyright notice and this permission notice shall be included in all
  15857. // copies or substantial portions of the Software.
  15858.  
  15859. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15860. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15861. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15862. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15863. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15864. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  15865. // SOFTWARE.
  15866.  
  15867. //#include "box2d/b2_body.h"
  15868. //#include "box2d/b2_motor_joint.h"
  15869. //#include "box2d/b2_time_step.h"
  15870.  
  15871. // Point-to-point constraint
  15872. // Cdot = v2 - v1
  15873. //      = v2 + cross(w2, r2) - v1 - cross(w1, r1)
  15874. // J = [-I -r1_skew I r2_skew ]
  15875. // Identity used:
  15876. // w k % (rx i + ry j) = w * (-ry i + rx j)
  15877. //
  15878. // r1 = offset - c1
  15879. // r2 = -c2
  15880.  
  15881. // Angle constraint
  15882. // Cdot = w2 - w1
  15883. // J = [0 0 -1 0 0 1]
  15884. // K = invI1 + invI2
  15885.  
  15886. void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB) {
  15887.     bodyA = bA;
  15888.     bodyB = bB;
  15889.     b2Vec2 xB = bodyB->GetPosition();
  15890.     linearOffset = bodyA->GetLocalPoint(xB);
  15891.  
  15892.     float angleA = bodyA->GetAngle();
  15893.     float angleB = bodyB->GetAngle();
  15894.     angularOffset = angleB - angleA;
  15895. }
  15896.  
  15897. b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def)
  15898.     : b2Joint(def) {
  15899.     m_linearOffset = def->linearOffset;
  15900.     m_angularOffset = def->angularOffset;
  15901.  
  15902.     m_linearImpulse.SetZero();
  15903.     m_angularImpulse = 0.0f;
  15904.  
  15905.     m_maxForce = def->maxForce;
  15906.     m_maxTorque = def->maxTorque;
  15907.     m_correctionFactor = def->correctionFactor;
  15908. }
  15909.  
  15910. void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data) {
  15911.     m_indexA = m_bodyA->m_islandIndex;
  15912.     m_indexB = m_bodyB->m_islandIndex;
  15913.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  15914.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  15915.     m_invMassA = m_bodyA->m_invMass;
  15916.     m_invMassB = m_bodyB->m_invMass;
  15917.     m_invIA = m_bodyA->m_invI;
  15918.     m_invIB = m_bodyB->m_invI;
  15919.  
  15920.     b2Vec2 cA = data.positions[m_indexA].c;
  15921.     float aA = data.positions[m_indexA].a;
  15922.     b2Vec2 vA = data.velocities[m_indexA].v;
  15923.     float wA = data.velocities[m_indexA].w;
  15924.  
  15925.     b2Vec2 cB = data.positions[m_indexB].c;
  15926.     float aB = data.positions[m_indexB].a;
  15927.     b2Vec2 vB = data.velocities[m_indexB].v;
  15928.     float wB = data.velocities[m_indexB].w;
  15929.  
  15930.     b2Rot qA(aA), qB(aB);
  15931.  
  15932.     // Compute the effective mass matrix.
  15933.     m_rA = b2Mul(qA, m_linearOffset - m_localCenterA);
  15934.     m_rB = b2Mul(qB, -m_localCenterB);
  15935.  
  15936.     // J = [-I -r1_skew I r2_skew]
  15937.     // r_skew = [-ry; rx]
  15938.  
  15939.     // Matlab
  15940.     // K = [ mA+r1y^2*iA+mB+r2y^2*iB,  -r1y*iA*r1x-r2y*iB*r2x,          -r1y*iA-r2y*iB]
  15941.     //     [  -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB,           r1x*iA+r2x*iB]
  15942.     //     [          -r1y*iA-r2y*iB,           r1x*iA+r2x*iB,                   iA+iB]
  15943.  
  15944.     float mA = m_invMassA, mB = m_invMassB;
  15945.     float iA = m_invIA, iB = m_invIB;
  15946.  
  15947.     // Upper 2 by 2 of K for point to point
  15948.     b2Mat22 K;
  15949.     K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
  15950.     K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
  15951.     K.ey.x = K.ex.y;
  15952.     K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
  15953.  
  15954.     m_linearMass = K.GetInverse();
  15955.  
  15956.     m_angularMass = iA + iB;
  15957.     if (m_angularMass > 0.0f) {
  15958.         m_angularMass = 1.0f / m_angularMass;
  15959.     }
  15960.  
  15961.     m_linearError = cB + m_rB - cA - m_rA;
  15962.     m_angularError = aB - aA - m_angularOffset;
  15963.  
  15964.     if (data.step.warmStarting) {
  15965.         // Scale impulses to support a variable time step.
  15966.         m_linearImpulse *= data.step.dtRatio;
  15967.         m_angularImpulse *= data.step.dtRatio;
  15968.  
  15969.         b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
  15970.         vA -= mA * P;
  15971.         wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
  15972.         vB += mB * P;
  15973.         wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
  15974.     } else {
  15975.         m_linearImpulse.SetZero();
  15976.         m_angularImpulse = 0.0f;
  15977.     }
  15978.  
  15979.     data.velocities[m_indexA].v = vA;
  15980.     data.velocities[m_indexA].w = wA;
  15981.     data.velocities[m_indexB].v = vB;
  15982.     data.velocities[m_indexB].w = wB;
  15983. }
  15984.  
  15985. void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data) {
  15986.     b2Vec2 vA = data.velocities[m_indexA].v;
  15987.     float wA = data.velocities[m_indexA].w;
  15988.     b2Vec2 vB = data.velocities[m_indexB].v;
  15989.     float wB = data.velocities[m_indexB].w;
  15990.  
  15991.     float mA = m_invMassA, mB = m_invMassB;
  15992.     float iA = m_invIA, iB = m_invIB;
  15993.  
  15994.     float h = data.step.dt;
  15995.     float inv_h = data.step.inv_dt;
  15996.  
  15997.     // Solve angular friction
  15998.     {
  15999.         float Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError;
  16000.         float impulse = -m_angularMass * Cdot;
  16001.  
  16002.         float oldImpulse = m_angularImpulse;
  16003.         float maxImpulse = h * m_maxTorque;
  16004.         m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
  16005.         impulse = m_angularImpulse - oldImpulse;
  16006.  
  16007.         wA -= iA * impulse;
  16008.         wB += iB * impulse;
  16009.     }
  16010.  
  16011.     // Solve linear friction
  16012.     {
  16013.         b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError;
  16014.  
  16015.         b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
  16016.         b2Vec2 oldImpulse = m_linearImpulse;
  16017.         m_linearImpulse += impulse;
  16018.  
  16019.         float maxImpulse = h * m_maxForce;
  16020.  
  16021.         if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) {
  16022.             m_linearImpulse.Normalize();
  16023.             m_linearImpulse *= maxImpulse;
  16024.         }
  16025.  
  16026.         impulse = m_linearImpulse - oldImpulse;
  16027.  
  16028.         vA -= mA * impulse;
  16029.         wA -= iA * b2Cross(m_rA, impulse);
  16030.  
  16031.         vB += mB * impulse;
  16032.         wB += iB * b2Cross(m_rB, impulse);
  16033.     }
  16034.  
  16035.     data.velocities[m_indexA].v = vA;
  16036.     data.velocities[m_indexA].w = wA;
  16037.     data.velocities[m_indexB].v = vB;
  16038.     data.velocities[m_indexB].w = wB;
  16039. }
  16040.  
  16041. bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data) {
  16042.     B2_NOT_USED(data);
  16043.  
  16044.     return true;
  16045. }
  16046.  
  16047. b2Vec2 b2MotorJoint::GetAnchorA() const {
  16048.     return m_bodyA->GetPosition();
  16049. }
  16050.  
  16051. b2Vec2 b2MotorJoint::GetAnchorB() const {
  16052.     return m_bodyB->GetPosition();
  16053. }
  16054.  
  16055. b2Vec2 b2MotorJoint::GetReactionForce(float inv_dt) const {
  16056.     return inv_dt * m_linearImpulse;
  16057. }
  16058.  
  16059. float b2MotorJoint::GetReactionTorque(float inv_dt) const {
  16060.     return inv_dt * m_angularImpulse;
  16061. }
  16062.  
  16063. void b2MotorJoint::SetMaxForce(float force) {
  16064.     b2Assert(b2IsValid(force) && force >= 0.0f);
  16065.     m_maxForce = force;
  16066. }
  16067.  
  16068. float b2MotorJoint::GetMaxForce() const {
  16069.     return m_maxForce;
  16070. }
  16071.  
  16072. void b2MotorJoint::SetMaxTorque(float torque) {
  16073.     b2Assert(b2IsValid(torque) && torque >= 0.0f);
  16074.     m_maxTorque = torque;
  16075. }
  16076.  
  16077. float b2MotorJoint::GetMaxTorque() const {
  16078.     return m_maxTorque;
  16079. }
  16080.  
  16081. void b2MotorJoint::SetCorrectionFactor(float factor) {
  16082.     b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f);
  16083.     m_correctionFactor = factor;
  16084. }
  16085.  
  16086. float b2MotorJoint::GetCorrectionFactor() const {
  16087.     return m_correctionFactor;
  16088. }
  16089.  
  16090. void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset) {
  16091.     if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y) {
  16092.         m_bodyA->SetAwake(true);
  16093.         m_bodyB->SetAwake(true);
  16094.         m_linearOffset = linearOffset;
  16095.     }
  16096. }
  16097.  
  16098. const b2Vec2& b2MotorJoint::GetLinearOffset() const {
  16099.     return m_linearOffset;
  16100. }
  16101.  
  16102. void b2MotorJoint::SetAngularOffset(float angularOffset) {
  16103.     if (angularOffset != m_angularOffset) {
  16104.         m_bodyA->SetAwake(true);
  16105.         m_bodyB->SetAwake(true);
  16106.         m_angularOffset = angularOffset;
  16107.     }
  16108. }
  16109.  
  16110. float b2MotorJoint::GetAngularOffset() const {
  16111.     return m_angularOffset;
  16112. }
  16113.  
  16114. void b2MotorJoint::Dump() {
  16115.     int32 indexA = m_bodyA->m_islandIndex;
  16116.     int32 indexB = m_bodyB->m_islandIndex;
  16117.  
  16118.     b2Dump("  b2MotorJointDef jd;\n");
  16119.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  16120.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  16121.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  16122.     b2Dump("  jd.linearOffset.Set(%.9g, %.9g);\n", m_linearOffset.x, m_linearOffset.y);
  16123.     b2Dump("  jd.angularOffset = %.9g;\n", m_angularOffset);
  16124.     b2Dump("  jd.maxForce = %.9g;\n", m_maxForce);
  16125.     b2Dump("  jd.maxTorque = %.9g;\n", m_maxTorque);
  16126.     b2Dump("  jd.correctionFactor = %.9g;\n", m_correctionFactor);
  16127.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  16128. }
  16129. // MIT License
  16130.  
  16131. // Copyright (c) 2019 Erin Catto
  16132.  
  16133. // Permission is hereby granted, free of charge, to any person obtaining a copy
  16134. // of this software and associated documentation files (the "Software"), to deal
  16135. // in the Software without restriction, including without limitation the rights
  16136. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16137. // copies of the Software, and to permit persons to whom the Software is
  16138. // furnished to do so, subject to the following conditions:
  16139.  
  16140. // The above copyright notice and this permission notice shall be included in all
  16141. // copies or substantial portions of the Software.
  16142.  
  16143. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16144. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16145. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16146. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16147. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16148. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  16149. // SOFTWARE.
  16150.  
  16151. //#include "box2d/b2_body.h"
  16152. //#include "box2d/b2_mouse_joint.h"
  16153. //#include "box2d/b2_time_step.h"
  16154.  
  16155. // p = attached point, m = mouse point
  16156. // C = p - m
  16157. // Cdot = v
  16158. //      = v + cross(w, r)
  16159. // J = [I r_skew]
  16160. // Identity used:
  16161. // w k % (rx i + ry j) = w * (-ry i + rx j)
  16162.  
  16163. b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def)
  16164.     : b2Joint(def) {
  16165.     m_targetA = def->target;
  16166.     m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA);
  16167.     m_maxForce = def->maxForce;
  16168.     m_stiffness = def->stiffness;
  16169.     m_damping = def->damping;
  16170.  
  16171.     m_impulse.SetZero();
  16172.     m_beta = 0.0f;
  16173.     m_gamma = 0.0f;
  16174. }
  16175.  
  16176. void b2MouseJoint::SetTarget(const b2Vec2& target) {
  16177.     if (target != m_targetA) {
  16178.         m_bodyB->SetAwake(true);
  16179.         m_targetA = target;
  16180.     }
  16181. }
  16182.  
  16183. const b2Vec2& b2MouseJoint::GetTarget() const {
  16184.     return m_targetA;
  16185. }
  16186.  
  16187. void b2MouseJoint::SetMaxForce(float force) {
  16188.     m_maxForce = force;
  16189. }
  16190.  
  16191. float b2MouseJoint::GetMaxForce() const {
  16192.     return m_maxForce;
  16193. }
  16194.  
  16195. void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) {
  16196.     m_indexB = m_bodyB->m_islandIndex;
  16197.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  16198.     m_invMassB = m_bodyB->m_invMass;
  16199.     m_invIB = m_bodyB->m_invI;
  16200.  
  16201.     b2Vec2 cB = data.positions[m_indexB].c;
  16202.     float aB = data.positions[m_indexB].a;
  16203.     b2Vec2 vB = data.velocities[m_indexB].v;
  16204.     float wB = data.velocities[m_indexB].w;
  16205.  
  16206.     b2Rot qB(aB);
  16207.  
  16208.     float mass = m_bodyB->GetMass();
  16209.  
  16210.     float d = m_damping;
  16211.     float k = m_stiffness;
  16212.  
  16213.     // magic formulas
  16214.     // gamma has units of inverse mass.
  16215.     // beta has units of inverse time.
  16216.     float h = data.step.dt;
  16217.     m_gamma = h * (d + h * k);
  16218.     if (m_gamma != 0.0f) {
  16219.         m_gamma = 1.0f / m_gamma;
  16220.     }
  16221.     m_beta = h * k * m_gamma;
  16222.  
  16223.     // Compute the effective mass matrix.
  16224.     m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  16225.  
  16226.     // K    = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)]
  16227.     //      = [1/m1+1/m2     0    ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y]
  16228.     //        [    0     1/m1+1/m2]           [-r1.x*r1.y r1.x*r1.x]           [-r1.x*r1.y r1.x*r1.x]
  16229.     b2Mat22 K;
  16230.     K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma;
  16231.     K.ex.y = -m_invIB * m_rB.x * m_rB.y;
  16232.     K.ey.x = K.ex.y;
  16233.     K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma;
  16234.  
  16235.     m_mass = K.GetInverse();
  16236.  
  16237.     m_C = cB + m_rB - m_targetA;
  16238.     m_C *= m_beta;
  16239.  
  16240.     // Cheat with some damping
  16241.     wB *= 0.98f;
  16242.  
  16243.     if (data.step.warmStarting) {
  16244.         m_impulse *= data.step.dtRatio;
  16245.         vB += m_invMassB * m_impulse;
  16246.         wB += m_invIB * b2Cross(m_rB, m_impulse);
  16247.     } else {
  16248.         m_impulse.SetZero();
  16249.     }
  16250.  
  16251.     data.velocities[m_indexB].v = vB;
  16252.     data.velocities[m_indexB].w = wB;
  16253. }
  16254.  
  16255. void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) {
  16256.     b2Vec2 vB = data.velocities[m_indexB].v;
  16257.     float wB = data.velocities[m_indexB].w;
  16258.  
  16259.     // Cdot = v + cross(w, r)
  16260.     b2Vec2 Cdot = vB + b2Cross(wB, m_rB);
  16261.     b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse));
  16262.  
  16263.     b2Vec2 oldImpulse = m_impulse;
  16264.     m_impulse += impulse;
  16265.     float maxImpulse = data.step.dt * m_maxForce;
  16266.     if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) {
  16267.         m_impulse *= maxImpulse / m_impulse.Length();
  16268.     }
  16269.     impulse = m_impulse - oldImpulse;
  16270.  
  16271.     vB += m_invMassB * impulse;
  16272.     wB += m_invIB * b2Cross(m_rB, impulse);
  16273.  
  16274.     data.velocities[m_indexB].v = vB;
  16275.     data.velocities[m_indexB].w = wB;
  16276. }
  16277.  
  16278. bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) {
  16279.     B2_NOT_USED(data);
  16280.     return true;
  16281. }
  16282.  
  16283. b2Vec2 b2MouseJoint::GetAnchorA() const {
  16284.     return m_targetA;
  16285. }
  16286.  
  16287. b2Vec2 b2MouseJoint::GetAnchorB() const {
  16288.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  16289. }
  16290.  
  16291. b2Vec2 b2MouseJoint::GetReactionForce(float inv_dt) const {
  16292.     return inv_dt * m_impulse;
  16293. }
  16294.  
  16295. float b2MouseJoint::GetReactionTorque(float inv_dt) const {
  16296.     return inv_dt * 0.0f;
  16297. }
  16298.  
  16299. void b2MouseJoint::ShiftOrigin(const b2Vec2& newOrigin) {
  16300.     m_targetA -= newOrigin;
  16301. }
  16302. // MIT License
  16303.  
  16304. // Copyright (c) 2019 Erin Catto
  16305.  
  16306. // Permission is hereby granted, free of charge, to any person obtaining a copy
  16307. // of this software and associated documentation files (the "Software"), to deal
  16308. // in the Software without restriction, including without limitation the rights
  16309. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16310. // copies of the Software, and to permit persons to whom the Software is
  16311. // furnished to do so, subject to the following conditions:
  16312.  
  16313. // The above copyright notice and this permission notice shall be included in all
  16314. // copies or substantial portions of the Software.
  16315.  
  16316. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16317. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16318. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16319. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16320. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16321. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  16322. // SOFTWARE.
  16323.  
  16324. //#include "b2_polygon_circle_contact.h"
  16325.  
  16326. //#include "box2d/b2_block_allocator.h"
  16327. //#include "box2d/b2_fixture.h"
  16328.  
  16329. #include <new>
  16330.  
  16331. b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) {
  16332.     void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact));
  16333.     return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB);
  16334. }
  16335.  
  16336. void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  16337.     ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact();
  16338.     allocator->Free(contact, sizeof(b2PolygonAndCircleContact));
  16339. }
  16340.  
  16341. b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
  16342.     : b2Contact(fixtureA, 0, fixtureB, 0) {
  16343.     b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon);
  16344.     b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
  16345. }
  16346.  
  16347. void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) {
  16348.     b2CollidePolygonAndCircle(manifold,
  16349.         (b2PolygonShape*)m_fixtureA->GetShape(), xfA,
  16350.         (b2CircleShape*)m_fixtureB->GetShape(), xfB);
  16351. }
  16352. // MIT License
  16353.  
  16354. // Copyright (c) 2019 Erin Catto
  16355.  
  16356. // Permission is hereby granted, free of charge, to any person obtaining a copy
  16357. // of this software and associated documentation files (the "Software"), to deal
  16358. // in the Software without restriction, including without limitation the rights
  16359. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16360. // copies of the Software, and to permit persons to whom the Software is
  16361. // furnished to do so, subject to the following conditions:
  16362.  
  16363. // The above copyright notice and this permission notice shall be included in all
  16364. // copies or substantial portions of the Software.
  16365.  
  16366. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16367. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16368. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16369. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16370. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16371. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  16372. // SOFTWARE.
  16373.  
  16374. //#include "b2_polygon_contact.h"
  16375.  
  16376. //#include "box2d/b2_block_allocator.h"
  16377. //#include "box2d/b2_body.h"
  16378. //#include "box2d/b2_fixture.h"
  16379. //#include "box2d/b2_time_of_impact.h"
  16380. //#include "box2d/b2_world_callbacks.h"
  16381.  
  16382. #include <new>
  16383.  
  16384. b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) {
  16385.     void* mem = allocator->Allocate(sizeof(b2PolygonContact));
  16386.     return new (mem) b2PolygonContact(fixtureA, fixtureB);
  16387. }
  16388.  
  16389. void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) {
  16390.     ((b2PolygonContact*)contact)->~b2PolygonContact();
  16391.     allocator->Free(contact, sizeof(b2PolygonContact));
  16392. }
  16393.  
  16394. b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
  16395.     : b2Contact(fixtureA, 0, fixtureB, 0) {
  16396.     b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon);
  16397.     b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
  16398. }
  16399.  
  16400. void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) {
  16401.     b2CollidePolygons(manifold,
  16402.         (b2PolygonShape*)m_fixtureA->GetShape(), xfA,
  16403.         (b2PolygonShape*)m_fixtureB->GetShape(), xfB);
  16404. }
  16405. // MIT License
  16406.  
  16407. // Copyright (c) 2019 Erin Catto
  16408.  
  16409. // Permission is hereby granted, free of charge, to any person obtaining a copy
  16410. // of this software and associated documentation files (the "Software"), to deal
  16411. // in the Software without restriction, including without limitation the rights
  16412. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16413. // copies of the Software, and to permit persons to whom the Software is
  16414. // furnished to do so, subject to the following conditions:
  16415.  
  16416. // The above copyright notice and this permission notice shall be included in all
  16417. // copies or substantial portions of the Software.
  16418.  
  16419. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16420. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16421. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16422. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16423. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16424. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  16425. // SOFTWARE.
  16426.  
  16427. //#include "box2d/b2_body.h"
  16428. //#include "box2d/b2_draw.h"
  16429. //#include "box2d/b2_prismatic_joint.h"
  16430. //#include "box2d/b2_time_step.h"
  16431.  
  16432. // Linear constraint (point-to-line)
  16433. // d = p2 - p1 = x2 + r2 - x1 - r1
  16434. // C = dot(perp, d)
  16435. // Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1))
  16436. //      = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2)
  16437. // J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)]
  16438. //
  16439. // Angular constraint
  16440. // C = a2 - a1 + a_initial
  16441. // Cdot = w2 - w1
  16442. // J = [0 0 -1 0 0 1]
  16443. //
  16444. // K = J * invM * JT
  16445. //
  16446. // J = [-a -s1 a s2]
  16447. //     [0  -1  0  1]
  16448. // a = perp
  16449. // s1 = cross(d + r1, a) = cross(p2 - x1, a)
  16450. // s2 = cross(r2, a) = cross(p2 - x2, a)
  16451.  
  16452. // Motor/Limit linear constraint
  16453. // C = dot(ax1, d)
  16454. // Cdot = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2)
  16455. // J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)]
  16456.  
  16457. // Predictive limit is applied even when the limit is not active.
  16458. // Prevents a constraint speed that can lead to a constraint error in one time step.
  16459. // Want C2 = C1 + h * Cdot >= 0
  16460. // Or:
  16461. // Cdot + C1/h >= 0
  16462. // I do not apply a negative constraint error because that is handled in position correction.
  16463. // So:
  16464. // Cdot + max(C1, 0)/h >= 0
  16465.  
  16466. // Block Solver
  16467. // We develop a block solver that includes the angular and linear constraints. This makes the limit stiffer.
  16468. //
  16469. // The Jacobian has 2 rows:
  16470. // J = [-uT -s1 uT s2] // linear
  16471. //     [0   -1   0  1] // angular
  16472. //
  16473. // u = perp
  16474. // s1 = cross(d + r1, u), s2 = cross(r2, u)
  16475. // a1 = cross(d + r1, v), a2 = cross(r2, v)
  16476.  
  16477. void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) {
  16478.     bodyA = bA;
  16479.     bodyB = bB;
  16480.     localAnchorA = bodyA->GetLocalPoint(anchor);
  16481.     localAnchorB = bodyB->GetLocalPoint(anchor);
  16482.     localAxisA = bodyA->GetLocalVector(axis);
  16483.     referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
  16484. }
  16485.  
  16486. b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def)
  16487.     : b2Joint(def) {
  16488.     m_localAnchorA = def->localAnchorA;
  16489.     m_localAnchorB = def->localAnchorB;
  16490.     m_localXAxisA = def->localAxisA;
  16491.     m_localXAxisA.Normalize();
  16492.     m_localYAxisA = b2Cross(1.0f, m_localXAxisA);
  16493.     m_referenceAngle = def->referenceAngle;
  16494.  
  16495.     m_impulse.SetZero();
  16496.     m_axialMass = 0.0f;
  16497.     m_motorImpulse = 0.0f;
  16498.     m_lowerImpulse = 0.0f;
  16499.     m_upperImpulse = 0.0f;
  16500.  
  16501.     m_lowerTranslation = def->lowerTranslation;
  16502.     m_upperTranslation = def->upperTranslation;
  16503.  
  16504.     b2Assert(m_lowerTranslation <= m_upperTranslation);
  16505.  
  16506.     m_maxMotorForce = def->maxMotorForce;
  16507.     m_motorSpeed = def->motorSpeed;
  16508.     m_enableLimit = def->enableLimit;
  16509.     m_enableMotor = def->enableMotor;
  16510.  
  16511.     m_translation = 0.0f;
  16512.     m_axis.SetZero();
  16513.     m_perp.SetZero();
  16514. }
  16515.  
  16516. void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) {
  16517.     m_indexA = m_bodyA->m_islandIndex;
  16518.     m_indexB = m_bodyB->m_islandIndex;
  16519.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  16520.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  16521.     m_invMassA = m_bodyA->m_invMass;
  16522.     m_invMassB = m_bodyB->m_invMass;
  16523.     m_invIA = m_bodyA->m_invI;
  16524.     m_invIB = m_bodyB->m_invI;
  16525.  
  16526.     b2Vec2 cA = data.positions[m_indexA].c;
  16527.     float aA = data.positions[m_indexA].a;
  16528.     b2Vec2 vA = data.velocities[m_indexA].v;
  16529.     float wA = data.velocities[m_indexA].w;
  16530.  
  16531.     b2Vec2 cB = data.positions[m_indexB].c;
  16532.     float aB = data.positions[m_indexB].a;
  16533.     b2Vec2 vB = data.velocities[m_indexB].v;
  16534.     float wB = data.velocities[m_indexB].w;
  16535.  
  16536.     b2Rot qA(aA), qB(aB);
  16537.  
  16538.     // Compute the effective masses.
  16539.     b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  16540.     b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  16541.     b2Vec2 d = (cB - cA) + rB - rA;
  16542.  
  16543.     float mA = m_invMassA, mB = m_invMassB;
  16544.     float iA = m_invIA, iB = m_invIB;
  16545.  
  16546.     // Compute motor Jacobian and effective mass.
  16547.     {
  16548.         m_axis = b2Mul(qA, m_localXAxisA);
  16549.         m_a1 = b2Cross(d + rA, m_axis);
  16550.         m_a2 = b2Cross(rB, m_axis);
  16551.  
  16552.         m_axialMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2;
  16553.         if (m_axialMass > 0.0f) {
  16554.             m_axialMass = 1.0f / m_axialMass;
  16555.         }
  16556.     }
  16557.  
  16558.     // Prismatic constraint.
  16559.     {
  16560.         m_perp = b2Mul(qA, m_localYAxisA);
  16561.  
  16562.         m_s1 = b2Cross(d + rA, m_perp);
  16563.         m_s2 = b2Cross(rB, m_perp);
  16564.  
  16565.         float k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2;
  16566.         float k12 = iA * m_s1 + iB * m_s2;
  16567.         float k22 = iA + iB;
  16568.         if (k22 == 0.0f) {
  16569.             // For bodies with fixed rotation.
  16570.             k22 = 1.0f;
  16571.         }
  16572.  
  16573.         m_K.ex.Set(k11, k12);
  16574.         m_K.ey.Set(k12, k22);
  16575.     }
  16576.  
  16577.     if (m_enableLimit) {
  16578.         m_translation = b2Dot(m_axis, d);
  16579.     } else {
  16580.         m_lowerImpulse = 0.0f;
  16581.         m_upperImpulse = 0.0f;
  16582.     }
  16583.  
  16584.     if (m_enableMotor == false) {
  16585.         m_motorImpulse = 0.0f;
  16586.     }
  16587.  
  16588.     if (data.step.warmStarting) {
  16589.         // Account for variable time step.
  16590.         m_impulse *= data.step.dtRatio;
  16591.         m_motorImpulse *= data.step.dtRatio;
  16592.         m_lowerImpulse *= data.step.dtRatio;
  16593.         m_upperImpulse *= data.step.dtRatio;
  16594.  
  16595.         float axialImpulse = m_motorImpulse + m_lowerImpulse - m_upperImpulse;
  16596.         b2Vec2 P = m_impulse.x * m_perp + axialImpulse * m_axis;
  16597.         float LA = m_impulse.x * m_s1 + m_impulse.y + axialImpulse * m_a1;
  16598.         float LB = m_impulse.x * m_s2 + m_impulse.y + axialImpulse * m_a2;
  16599.  
  16600.         vA -= mA * P;
  16601.         wA -= iA * LA;
  16602.  
  16603.         vB += mB * P;
  16604.         wB += iB * LB;
  16605.     } else {
  16606.         m_impulse.SetZero();
  16607.         m_motorImpulse = 0.0f;
  16608.         m_lowerImpulse = 0.0f;
  16609.         m_upperImpulse = 0.0f;
  16610.     }
  16611.  
  16612.     data.velocities[m_indexA].v = vA;
  16613.     data.velocities[m_indexA].w = wA;
  16614.     data.velocities[m_indexB].v = vB;
  16615.     data.velocities[m_indexB].w = wB;
  16616. }
  16617.  
  16618. void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) {
  16619.     b2Vec2 vA = data.velocities[m_indexA].v;
  16620.     float wA = data.velocities[m_indexA].w;
  16621.     b2Vec2 vB = data.velocities[m_indexB].v;
  16622.     float wB = data.velocities[m_indexB].w;
  16623.  
  16624.     float mA = m_invMassA, mB = m_invMassB;
  16625.     float iA = m_invIA, iB = m_invIB;
  16626.  
  16627.     // Solve linear motor constraint
  16628.     if (m_enableMotor) {
  16629.         float Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA;
  16630.         float impulse = m_axialMass * (m_motorSpeed - Cdot);
  16631.         float oldImpulse = m_motorImpulse;
  16632.         float maxImpulse = data.step.dt * m_maxMotorForce;
  16633.         m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
  16634.         impulse = m_motorImpulse - oldImpulse;
  16635.  
  16636.         b2Vec2 P = impulse * m_axis;
  16637.         float LA = impulse * m_a1;
  16638.         float LB = impulse * m_a2;
  16639.  
  16640.         vA -= mA * P;
  16641.         wA -= iA * LA;
  16642.         vB += mB * P;
  16643.         wB += iB * LB;
  16644.     }
  16645.  
  16646.     if (m_enableLimit) {
  16647.         // Lower limit
  16648.         {
  16649.             float C = m_translation - m_lowerTranslation;
  16650.             float Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA;
  16651.             float impulse = -m_axialMass * (Cdot + b2Max(C, 0.0f) * data.step.inv_dt);
  16652.             float oldImpulse = m_lowerImpulse;
  16653.             m_lowerImpulse = b2Max(m_lowerImpulse + impulse, 0.0f);
  16654.             impulse = m_lowerImpulse - oldImpulse;
  16655.  
  16656.             b2Vec2 P = impulse * m_axis;
  16657.             float LA = impulse * m_a1;
  16658.             float LB = impulse * m_a2;
  16659.  
  16660.             vA -= mA * P;
  16661.             wA -= iA * LA;
  16662.             vB += mB * P;
  16663.             wB += iB * LB;
  16664.         }
  16665.  
  16666.         // Upper limit
  16667.         // Note: signs are flipped to keep C positive when the constraint is satisfied.
  16668.         // This also keeps the impulse positive when the limit is active.
  16669.         {
  16670.             float C = m_upperTranslation - m_translation;
  16671.             float Cdot = b2Dot(m_axis, vA - vB) + m_a1 * wA - m_a2 * wB;
  16672.             float impulse = -m_axialMass * (Cdot + b2Max(C, 0.0f) * data.step.inv_dt);
  16673.             float oldImpulse = m_upperImpulse;
  16674.             m_upperImpulse = b2Max(m_upperImpulse + impulse, 0.0f);
  16675.             impulse = m_upperImpulse - oldImpulse;
  16676.  
  16677.             b2Vec2 P = impulse * m_axis;
  16678.             float LA = impulse * m_a1;
  16679.             float LB = impulse * m_a2;
  16680.  
  16681.             vA += mA * P;
  16682.             wA += iA * LA;
  16683.             vB -= mB * P;
  16684.             wB -= iB * LB;
  16685.         }
  16686.     }
  16687.  
  16688.     // Solve the prismatic constraint in block form.
  16689.     {
  16690.         b2Vec2 Cdot;
  16691.         Cdot.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA;
  16692.         Cdot.y = wB - wA;
  16693.  
  16694.         b2Vec2 df = m_K.Solve(-Cdot);
  16695.         m_impulse += df;
  16696.  
  16697.         b2Vec2 P = df.x * m_perp;
  16698.         float LA = df.x * m_s1 + df.y;
  16699.         float LB = df.x * m_s2 + df.y;
  16700.  
  16701.         vA -= mA * P;
  16702.         wA -= iA * LA;
  16703.  
  16704.         vB += mB * P;
  16705.         wB += iB * LB;
  16706.     }
  16707.  
  16708.     data.velocities[m_indexA].v = vA;
  16709.     data.velocities[m_indexA].w = wA;
  16710.     data.velocities[m_indexB].v = vB;
  16711.     data.velocities[m_indexB].w = wB;
  16712. }
  16713.  
  16714. // A velocity based solver computes reaction forces(impulses) using the velocity constraint solver.Under this context,
  16715. // the position solver is not there to resolve forces.It is only there to cope with integration error.
  16716. //
  16717. // Therefore, the pseudo impulses in the position solver do not have any physical meaning.Thus it is okay if they suck.
  16718. //
  16719. // We could take the active state from the velocity solver.However, the joint might push past the limit when the velocity
  16720. // solver indicates the limit is inactive.
  16721. bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) {
  16722.     b2Vec2 cA = data.positions[m_indexA].c;
  16723.     float aA = data.positions[m_indexA].a;
  16724.     b2Vec2 cB = data.positions[m_indexB].c;
  16725.     float aB = data.positions[m_indexB].a;
  16726.  
  16727.     b2Rot qA(aA), qB(aB);
  16728.  
  16729.     float mA = m_invMassA, mB = m_invMassB;
  16730.     float iA = m_invIA, iB = m_invIB;
  16731.  
  16732.     // Compute fresh Jacobians
  16733.     b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  16734.     b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  16735.     b2Vec2 d = cB + rB - cA - rA;
  16736.  
  16737.     b2Vec2 axis = b2Mul(qA, m_localXAxisA);
  16738.     float a1 = b2Cross(d + rA, axis);
  16739.     float a2 = b2Cross(rB, axis);
  16740.     b2Vec2 perp = b2Mul(qA, m_localYAxisA);
  16741.  
  16742.     float s1 = b2Cross(d + rA, perp);
  16743.     float s2 = b2Cross(rB, perp);
  16744.  
  16745.     b2Vec3 impulse;
  16746.     b2Vec2 C1;
  16747.     C1.x = b2Dot(perp, d);
  16748.     C1.y = aB - aA - m_referenceAngle;
  16749.  
  16750.     float linearError = b2Abs(C1.x);
  16751.     float angularError = b2Abs(C1.y);
  16752.  
  16753.     bool active = false;
  16754.     float C2 = 0.0f;
  16755.     if (m_enableLimit) {
  16756.         float translation = b2Dot(axis, d);
  16757.         if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) {
  16758.             C2 = translation;
  16759.             linearError = b2Max(linearError, b2Abs(translation));
  16760.             active = true;
  16761.         } else if (translation <= m_lowerTranslation) {
  16762.             C2 = b2Min(translation - m_lowerTranslation, 0.0f);
  16763.             linearError = b2Max(linearError, m_lowerTranslation - translation);
  16764.             active = true;
  16765.         } else if (translation >= m_upperTranslation) {
  16766.             C2 = b2Max(translation - m_upperTranslation, 0.0f);
  16767.             linearError = b2Max(linearError, translation - m_upperTranslation);
  16768.             active = true;
  16769.         }
  16770.     }
  16771.  
  16772.     if (active) {
  16773.         float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
  16774.         float k12 = iA * s1 + iB * s2;
  16775.         float k13 = iA * s1 * a1 + iB * s2 * a2;
  16776.         float k22 = iA + iB;
  16777.         if (k22 == 0.0f) {
  16778.             // For fixed rotation
  16779.             k22 = 1.0f;
  16780.         }
  16781.         float k23 = iA * a1 + iB * a2;
  16782.         float k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;
  16783.  
  16784.         b2Mat33 K;
  16785.         K.ex.Set(k11, k12, k13);
  16786.         K.ey.Set(k12, k22, k23);
  16787.         K.ez.Set(k13, k23, k33);
  16788.  
  16789.         b2Vec3 C;
  16790.         C.x = C1.x;
  16791.         C.y = C1.y;
  16792.         C.z = C2;
  16793.  
  16794.         impulse = K.Solve33(-C);
  16795.     } else {
  16796.         float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
  16797.         float k12 = iA * s1 + iB * s2;
  16798.         float k22 = iA + iB;
  16799.         if (k22 == 0.0f) {
  16800.             k22 = 1.0f;
  16801.         }
  16802.  
  16803.         b2Mat22 K;
  16804.         K.ex.Set(k11, k12);
  16805.         K.ey.Set(k12, k22);
  16806.  
  16807.         b2Vec2 impulse1 = K.Solve(-C1);
  16808.         impulse.x = impulse1.x;
  16809.         impulse.y = impulse1.y;
  16810.         impulse.z = 0.0f;
  16811.     }
  16812.  
  16813.     b2Vec2 P = impulse.x * perp + impulse.z * axis;
  16814.     float LA = impulse.x * s1 + impulse.y + impulse.z * a1;
  16815.     float LB = impulse.x * s2 + impulse.y + impulse.z * a2;
  16816.  
  16817.     cA -= mA * P;
  16818.     aA -= iA * LA;
  16819.     cB += mB * P;
  16820.     aB += iB * LB;
  16821.  
  16822.     data.positions[m_indexA].c = cA;
  16823.     data.positions[m_indexA].a = aA;
  16824.     data.positions[m_indexB].c = cB;
  16825.     data.positions[m_indexB].a = aB;
  16826.  
  16827.     return linearError <= b2_linearSlop && angularError <= b2_angularSlop;
  16828. }
  16829.  
  16830. b2Vec2 b2PrismaticJoint::GetAnchorA() const {
  16831.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  16832. }
  16833.  
  16834. b2Vec2 b2PrismaticJoint::GetAnchorB() const {
  16835.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  16836. }
  16837.  
  16838. b2Vec2 b2PrismaticJoint::GetReactionForce(float inv_dt) const {
  16839.     return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_lowerImpulse - m_upperImpulse) * m_axis);
  16840. }
  16841.  
  16842. float b2PrismaticJoint::GetReactionTorque(float inv_dt) const {
  16843.     return inv_dt * m_impulse.y;
  16844. }
  16845.  
  16846. float b2PrismaticJoint::GetJointTranslation() const {
  16847.     b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA);
  16848.     b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB);
  16849.     b2Vec2 d = pB - pA;
  16850.     b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA);
  16851.  
  16852.     float translation = b2Dot(d, axis);
  16853.     return translation;
  16854. }
  16855.  
  16856. float b2PrismaticJoint::GetJointSpeed() const {
  16857.     b2Body* bA = m_bodyA;
  16858.     b2Body* bB = m_bodyB;
  16859.  
  16860.     b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter);
  16861.     b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter);
  16862.     b2Vec2 p1 = bA->m_sweep.c + rA;
  16863.     b2Vec2 p2 = bB->m_sweep.c + rB;
  16864.     b2Vec2 d = p2 - p1;
  16865.     b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA);
  16866.  
  16867.     b2Vec2 vA = bA->m_linearVelocity;
  16868.     b2Vec2 vB = bB->m_linearVelocity;
  16869.     float wA = bA->m_angularVelocity;
  16870.     float wB = bB->m_angularVelocity;
  16871.  
  16872.     float speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA));
  16873.     return speed;
  16874. }
  16875.  
  16876. bool b2PrismaticJoint::IsLimitEnabled() const {
  16877.     return m_enableLimit;
  16878. }
  16879.  
  16880. void b2PrismaticJoint::EnableLimit(bool flag) {
  16881.     if (flag != m_enableLimit) {
  16882.         m_bodyA->SetAwake(true);
  16883.         m_bodyB->SetAwake(true);
  16884.         m_enableLimit = flag;
  16885.         m_lowerImpulse = 0.0f;
  16886.         m_upperImpulse = 0.0f;
  16887.     }
  16888. }
  16889.  
  16890. float b2PrismaticJoint::GetLowerLimit() const {
  16891.     return m_lowerTranslation;
  16892. }
  16893.  
  16894. float b2PrismaticJoint::GetUpperLimit() const {
  16895.     return m_upperTranslation;
  16896. }
  16897.  
  16898. void b2PrismaticJoint::SetLimits(float lower, float upper) {
  16899.     b2Assert(lower <= upper);
  16900.     if (lower != m_lowerTranslation || upper != m_upperTranslation) {
  16901.         m_bodyA->SetAwake(true);
  16902.         m_bodyB->SetAwake(true);
  16903.         m_lowerTranslation = lower;
  16904.         m_upperTranslation = upper;
  16905.         m_lowerImpulse = 0.0f;
  16906.         m_upperImpulse = 0.0f;
  16907.     }
  16908. }
  16909.  
  16910. bool b2PrismaticJoint::IsMotorEnabled() const {
  16911.     return m_enableMotor;
  16912. }
  16913.  
  16914. void b2PrismaticJoint::EnableMotor(bool flag) {
  16915.     if (flag != m_enableMotor) {
  16916.         m_bodyA->SetAwake(true);
  16917.         m_bodyB->SetAwake(true);
  16918.         m_enableMotor = flag;
  16919.     }
  16920. }
  16921.  
  16922. void b2PrismaticJoint::SetMotorSpeed(float speed) {
  16923.     if (speed != m_motorSpeed) {
  16924.         m_bodyA->SetAwake(true);
  16925.         m_bodyB->SetAwake(true);
  16926.         m_motorSpeed = speed;
  16927.     }
  16928. }
  16929.  
  16930. void b2PrismaticJoint::SetMaxMotorForce(float force) {
  16931.     if (force != m_maxMotorForce) {
  16932.         m_bodyA->SetAwake(true);
  16933.         m_bodyB->SetAwake(true);
  16934.         m_maxMotorForce = force;
  16935.     }
  16936. }
  16937.  
  16938. float b2PrismaticJoint::GetMotorForce(float inv_dt) const {
  16939.     return inv_dt * m_motorImpulse;
  16940. }
  16941.  
  16942. void b2PrismaticJoint::Dump() {
  16943.     // FLT_DECIMAL_DIG == 9
  16944.  
  16945.     int32 indexA = m_bodyA->m_islandIndex;
  16946.     int32 indexB = m_bodyB->m_islandIndex;
  16947.  
  16948.     b2Dump("  b2PrismaticJointDef jd;\n");
  16949.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  16950.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  16951.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  16952.     b2Dump("  jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
  16953.     b2Dump("  jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
  16954.     b2Dump("  jd.localAxisA.Set(%.9g, %.9g);\n", m_localXAxisA.x, m_localXAxisA.y);
  16955.     b2Dump("  jd.referenceAngle = %.9g;\n", m_referenceAngle);
  16956.     b2Dump("  jd.enableLimit = bool(%d);\n", m_enableLimit);
  16957.     b2Dump("  jd.lowerTranslation = %.9g;\n", m_lowerTranslation);
  16958.     b2Dump("  jd.upperTranslation = %.9g;\n", m_upperTranslation);
  16959.     b2Dump("  jd.enableMotor = bool(%d);\n", m_enableMotor);
  16960.     b2Dump("  jd.motorSpeed = %.9g;\n", m_motorSpeed);
  16961.     b2Dump("  jd.maxMotorForce = %.9g;\n", m_maxMotorForce);
  16962.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  16963. }
  16964.  
  16965. void b2PrismaticJoint::Draw(b2Draw* draw) const {
  16966.     const b2Transform& xfA = m_bodyA->GetTransform();
  16967.     const b2Transform& xfB = m_bodyB->GetTransform();
  16968.     b2Vec2 pA = b2Mul(xfA, m_localAnchorA);
  16969.     b2Vec2 pB = b2Mul(xfB, m_localAnchorB);
  16970.  
  16971.     b2Vec2 axis = b2Mul(xfA.q, m_localXAxisA);
  16972.  
  16973.     b2Color c1(0.7f, 0.7f, 0.7f);
  16974.     b2Color c2(0.3f, 0.9f, 0.3f);
  16975.     b2Color c3(0.9f, 0.3f, 0.3f);
  16976.     b2Color c4(0.3f, 0.3f, 0.9f);
  16977.     b2Color c5(0.4f, 0.4f, 0.4f);
  16978.  
  16979.     draw->DrawSegment(pA, pB, c5);
  16980.  
  16981.     if (m_enableLimit) {
  16982.         b2Vec2 lower = pA + m_lowerTranslation * axis;
  16983.         b2Vec2 upper = pA + m_upperTranslation * axis;
  16984.         b2Vec2 perp = b2Mul(xfA.q, m_localYAxisA);
  16985.         draw->DrawSegment(lower, upper, c1);
  16986.         draw->DrawSegment(lower - 0.5f * perp, lower + 0.5f * perp, c2);
  16987.         draw->DrawSegment(upper - 0.5f * perp, upper + 0.5f * perp, c3);
  16988.     } else {
  16989.         draw->DrawSegment(pA - 1.0f * axis, pA + 1.0f * axis, c1);
  16990.     }
  16991.  
  16992.     draw->DrawPoint(pA, 5.0f, c1);
  16993.     draw->DrawPoint(pB, 5.0f, c4);
  16994. }
  16995. // MIT License
  16996.  
  16997. // Copyright (c) 2019 Erin Catto
  16998.  
  16999. // Permission is hereby granted, free of charge, to any person obtaining a copy
  17000. // of this software and associated documentation files (the "Software"), to deal
  17001. // in the Software without restriction, including without limitation the rights
  17002. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17003. // copies of the Software, and to permit persons to whom the Software is
  17004. // furnished to do so, subject to the following conditions:
  17005.  
  17006. // The above copyright notice and this permission notice shall be included in all
  17007. // copies or substantial portions of the Software.
  17008.  
  17009. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17010. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17011. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17012. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17013. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17014. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17015. // SOFTWARE.
  17016.  
  17017. //#include "box2d/b2_body.h"
  17018. //#include "box2d/b2_pulley_joint.h"
  17019. //#include "box2d/b2_time_step.h"
  17020.  
  17021. // Pulley:
  17022. // length1 = norm(p1 - s1)
  17023. // length2 = norm(p2 - s2)
  17024. // C0 = (length1 + ratio * length2)_initial
  17025. // C = C0 - (length1 + ratio * length2)
  17026. // u1 = (p1 - s1) / norm(p1 - s1)
  17027. // u2 = (p2 - s2) / norm(p2 - s2)
  17028. // Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2))
  17029. // J = -[u1 cross(r1, u1) ratio * u2  ratio * cross(r2, u2)]
  17030. // K = J * invM * JT
  17031. //   = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2)
  17032.  
  17033. void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB,
  17034.     const b2Vec2& groundA, const b2Vec2& groundB,
  17035.     const b2Vec2& anchorA, const b2Vec2& anchorB,
  17036.     float r) {
  17037.     bodyA = bA;
  17038.     bodyB = bB;
  17039.     groundAnchorA = groundA;
  17040.     groundAnchorB = groundB;
  17041.     localAnchorA = bodyA->GetLocalPoint(anchorA);
  17042.     localAnchorB = bodyB->GetLocalPoint(anchorB);
  17043.     b2Vec2 dA = anchorA - groundA;
  17044.     lengthA = dA.Length();
  17045.     b2Vec2 dB = anchorB - groundB;
  17046.     lengthB = dB.Length();
  17047.     ratio = r;
  17048.     b2Assert(ratio > b2_epsilon);
  17049. }
  17050.  
  17051. b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def)
  17052.     : b2Joint(def) {
  17053.     m_groundAnchorA = def->groundAnchorA;
  17054.     m_groundAnchorB = def->groundAnchorB;
  17055.     m_localAnchorA = def->localAnchorA;
  17056.     m_localAnchorB = def->localAnchorB;
  17057.  
  17058.     m_lengthA = def->lengthA;
  17059.     m_lengthB = def->lengthB;
  17060.  
  17061.     b2Assert(def->ratio != 0.0f);
  17062.     m_ratio = def->ratio;
  17063.  
  17064.     m_constant = def->lengthA + m_ratio * def->lengthB;
  17065.  
  17066.     m_impulse = 0.0f;
  17067. }
  17068.  
  17069. void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) {
  17070.     m_indexA = m_bodyA->m_islandIndex;
  17071.     m_indexB = m_bodyB->m_islandIndex;
  17072.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  17073.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  17074.     m_invMassA = m_bodyA->m_invMass;
  17075.     m_invMassB = m_bodyB->m_invMass;
  17076.     m_invIA = m_bodyA->m_invI;
  17077.     m_invIB = m_bodyB->m_invI;
  17078.  
  17079.     b2Vec2 cA = data.positions[m_indexA].c;
  17080.     float aA = data.positions[m_indexA].a;
  17081.     b2Vec2 vA = data.velocities[m_indexA].v;
  17082.     float wA = data.velocities[m_indexA].w;
  17083.  
  17084.     b2Vec2 cB = data.positions[m_indexB].c;
  17085.     float aB = data.positions[m_indexB].a;
  17086.     b2Vec2 vB = data.velocities[m_indexB].v;
  17087.     float wB = data.velocities[m_indexB].w;
  17088.  
  17089.     b2Rot qA(aA), qB(aB);
  17090.  
  17091.     m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  17092.     m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  17093.  
  17094.     // Get the pulley axes.
  17095.     m_uA = cA + m_rA - m_groundAnchorA;
  17096.     m_uB = cB + m_rB - m_groundAnchorB;
  17097.  
  17098.     float lengthA = m_uA.Length();
  17099.     float lengthB = m_uB.Length();
  17100.  
  17101.     if (lengthA > 10.0f * b2_linearSlop) {
  17102.         m_uA *= 1.0f / lengthA;
  17103.     } else {
  17104.         m_uA.SetZero();
  17105.     }
  17106.  
  17107.     if (lengthB > 10.0f * b2_linearSlop) {
  17108.         m_uB *= 1.0f / lengthB;
  17109.     } else {
  17110.         m_uB.SetZero();
  17111.     }
  17112.  
  17113.     // Compute effective mass.
  17114.     float ruA = b2Cross(m_rA, m_uA);
  17115.     float ruB = b2Cross(m_rB, m_uB);
  17116.  
  17117.     float mA = m_invMassA + m_invIA * ruA * ruA;
  17118.     float mB = m_invMassB + m_invIB * ruB * ruB;
  17119.  
  17120.     m_mass = mA + m_ratio * m_ratio * mB;
  17121.  
  17122.     if (m_mass > 0.0f) {
  17123.         m_mass = 1.0f / m_mass;
  17124.     }
  17125.  
  17126.     if (data.step.warmStarting) {
  17127.         // Scale impulses to support variable time steps.
  17128.         m_impulse *= data.step.dtRatio;
  17129.  
  17130.         // Warm starting.
  17131.         b2Vec2 PA = -(m_impulse)*m_uA;
  17132.         b2Vec2 PB = (-m_ratio * m_impulse) * m_uB;
  17133.  
  17134.         vA += m_invMassA * PA;
  17135.         wA += m_invIA * b2Cross(m_rA, PA);
  17136.         vB += m_invMassB * PB;
  17137.         wB += m_invIB * b2Cross(m_rB, PB);
  17138.     } else {
  17139.         m_impulse = 0.0f;
  17140.     }
  17141.  
  17142.     data.velocities[m_indexA].v = vA;
  17143.     data.velocities[m_indexA].w = wA;
  17144.     data.velocities[m_indexB].v = vB;
  17145.     data.velocities[m_indexB].w = wB;
  17146. }
  17147.  
  17148. void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) {
  17149.     b2Vec2 vA = data.velocities[m_indexA].v;
  17150.     float wA = data.velocities[m_indexA].w;
  17151.     b2Vec2 vB = data.velocities[m_indexB].v;
  17152.     float wB = data.velocities[m_indexB].w;
  17153.  
  17154.     b2Vec2 vpA = vA + b2Cross(wA, m_rA);
  17155.     b2Vec2 vpB = vB + b2Cross(wB, m_rB);
  17156.  
  17157.     float Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB);
  17158.     float impulse = -m_mass * Cdot;
  17159.     m_impulse += impulse;
  17160.  
  17161.     b2Vec2 PA = -impulse * m_uA;
  17162.     b2Vec2 PB = -m_ratio * impulse * m_uB;
  17163.     vA += m_invMassA * PA;
  17164.     wA += m_invIA * b2Cross(m_rA, PA);
  17165.     vB += m_invMassB * PB;
  17166.     wB += m_invIB * b2Cross(m_rB, PB);
  17167.  
  17168.     data.velocities[m_indexA].v = vA;
  17169.     data.velocities[m_indexA].w = wA;
  17170.     data.velocities[m_indexB].v = vB;
  17171.     data.velocities[m_indexB].w = wB;
  17172. }
  17173.  
  17174. bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) {
  17175.     b2Vec2 cA = data.positions[m_indexA].c;
  17176.     float aA = data.positions[m_indexA].a;
  17177.     b2Vec2 cB = data.positions[m_indexB].c;
  17178.     float aB = data.positions[m_indexB].a;
  17179.  
  17180.     b2Rot qA(aA), qB(aB);
  17181.  
  17182.     b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  17183.     b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  17184.  
  17185.     // Get the pulley axes.
  17186.     b2Vec2 uA = cA + rA - m_groundAnchorA;
  17187.     b2Vec2 uB = cB + rB - m_groundAnchorB;
  17188.  
  17189.     float lengthA = uA.Length();
  17190.     float lengthB = uB.Length();
  17191.  
  17192.     if (lengthA > 10.0f * b2_linearSlop) {
  17193.         uA *= 1.0f / lengthA;
  17194.     } else {
  17195.         uA.SetZero();
  17196.     }
  17197.  
  17198.     if (lengthB > 10.0f * b2_linearSlop) {
  17199.         uB *= 1.0f / lengthB;
  17200.     } else {
  17201.         uB.SetZero();
  17202.     }
  17203.  
  17204.     // Compute effective mass.
  17205.     float ruA = b2Cross(rA, uA);
  17206.     float ruB = b2Cross(rB, uB);
  17207.  
  17208.     float mA = m_invMassA + m_invIA * ruA * ruA;
  17209.     float mB = m_invMassB + m_invIB * ruB * ruB;
  17210.  
  17211.     float mass = mA + m_ratio * m_ratio * mB;
  17212.  
  17213.     if (mass > 0.0f) {
  17214.         mass = 1.0f / mass;
  17215.     }
  17216.  
  17217.     float C = m_constant - lengthA - m_ratio * lengthB;
  17218.     float linearError = b2Abs(C);
  17219.  
  17220.     float impulse = -mass * C;
  17221.  
  17222.     b2Vec2 PA = -impulse * uA;
  17223.     b2Vec2 PB = -m_ratio * impulse * uB;
  17224.  
  17225.     cA += m_invMassA * PA;
  17226.     aA += m_invIA * b2Cross(rA, PA);
  17227.     cB += m_invMassB * PB;
  17228.     aB += m_invIB * b2Cross(rB, PB);
  17229.  
  17230.     data.positions[m_indexA].c = cA;
  17231.     data.positions[m_indexA].a = aA;
  17232.     data.positions[m_indexB].c = cB;
  17233.     data.positions[m_indexB].a = aB;
  17234.  
  17235.     return linearError < b2_linearSlop;
  17236. }
  17237.  
  17238. b2Vec2 b2PulleyJoint::GetAnchorA() const {
  17239.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  17240. }
  17241.  
  17242. b2Vec2 b2PulleyJoint::GetAnchorB() const {
  17243.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  17244. }
  17245.  
  17246. b2Vec2 b2PulleyJoint::GetReactionForce(float inv_dt) const {
  17247.     b2Vec2 P = m_impulse * m_uB;
  17248.     return inv_dt * P;
  17249. }
  17250.  
  17251. float b2PulleyJoint::GetReactionTorque(float inv_dt) const {
  17252.     B2_NOT_USED(inv_dt);
  17253.     return 0.0f;
  17254. }
  17255.  
  17256. b2Vec2 b2PulleyJoint::GetGroundAnchorA() const {
  17257.     return m_groundAnchorA;
  17258. }
  17259.  
  17260. b2Vec2 b2PulleyJoint::GetGroundAnchorB() const {
  17261.     return m_groundAnchorB;
  17262. }
  17263.  
  17264. float b2PulleyJoint::GetLengthA() const {
  17265.     return m_lengthA;
  17266. }
  17267.  
  17268. float b2PulleyJoint::GetLengthB() const {
  17269.     return m_lengthB;
  17270. }
  17271.  
  17272. float b2PulleyJoint::GetRatio() const {
  17273.     return m_ratio;
  17274. }
  17275.  
  17276. float b2PulleyJoint::GetCurrentLengthA() const {
  17277.     b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA);
  17278.     b2Vec2 s = m_groundAnchorA;
  17279.     b2Vec2 d = p - s;
  17280.     return d.Length();
  17281. }
  17282.  
  17283. float b2PulleyJoint::GetCurrentLengthB() const {
  17284.     b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB);
  17285.     b2Vec2 s = m_groundAnchorB;
  17286.     b2Vec2 d = p - s;
  17287.     return d.Length();
  17288. }
  17289.  
  17290. void b2PulleyJoint::Dump() {
  17291.     int32 indexA = m_bodyA->m_islandIndex;
  17292.     int32 indexB = m_bodyB->m_islandIndex;
  17293.  
  17294.     b2Dump("  b2PulleyJointDef jd;\n");
  17295.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  17296.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  17297.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  17298.     b2Dump("  jd.groundAnchorA.Set(%.9g, %.9g);\n", m_groundAnchorA.x, m_groundAnchorA.y);
  17299.     b2Dump("  jd.groundAnchorB.Set(%.9g, %.9g);\n", m_groundAnchorB.x, m_groundAnchorB.y);
  17300.     b2Dump("  jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
  17301.     b2Dump("  jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
  17302.     b2Dump("  jd.lengthA = %.9g;\n", m_lengthA);
  17303.     b2Dump("  jd.lengthB = %.9g;\n", m_lengthB);
  17304.     b2Dump("  jd.ratio = %.9g;\n", m_ratio);
  17305.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  17306. }
  17307.  
  17308. void b2PulleyJoint::ShiftOrigin(const b2Vec2& newOrigin) {
  17309.     m_groundAnchorA -= newOrigin;
  17310.     m_groundAnchorB -= newOrigin;
  17311. }
  17312. // MIT License
  17313.  
  17314. // Copyright (c) 2019 Erin Catto
  17315.  
  17316. // Permission is hereby granted, free of charge, to any person obtaining a copy
  17317. // of this software and associated documentation files (the "Software"), to deal
  17318. // in the Software without restriction, including without limitation the rights
  17319. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17320. // copies of the Software, and to permit persons to whom the Software is
  17321. // furnished to do so, subject to the following conditions:
  17322.  
  17323. // The above copyright notice and this permission notice shall be included in all
  17324. // copies or substantial portions of the Software.
  17325.  
  17326. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17327. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17328. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17329. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17330. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17331. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17332. // SOFTWARE.
  17333.  
  17334. //#include "box2d/b2_body.h"
  17335. //#include "box2d/b2_draw.h"
  17336. //#include "box2d/b2_revolute_joint.h"
  17337. //#include "box2d/b2_time_step.h"
  17338.  
  17339. // Point-to-point constraint
  17340. // C = p2 - p1
  17341. // Cdot = v2 - v1
  17342. //      = v2 + cross(w2, r2) - v1 - cross(w1, r1)
  17343. // J = [-I -r1_skew I r2_skew ]
  17344. // Identity used:
  17345. // w k % (rx i + ry j) = w * (-ry i + rx j)
  17346.  
  17347. // Motor constraint
  17348. // Cdot = w2 - w1
  17349. // J = [0 0 -1 0 0 1]
  17350. // K = invI1 + invI2
  17351.  
  17352. void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) {
  17353.     bodyA = bA;
  17354.     bodyB = bB;
  17355.     localAnchorA = bodyA->GetLocalPoint(anchor);
  17356.     localAnchorB = bodyB->GetLocalPoint(anchor);
  17357.     referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
  17358. }
  17359.  
  17360. b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def)
  17361.     : b2Joint(def) {
  17362.     m_localAnchorA = def->localAnchorA;
  17363.     m_localAnchorB = def->localAnchorB;
  17364.     m_referenceAngle = def->referenceAngle;
  17365.  
  17366.     m_impulse.SetZero();
  17367.     m_axialMass = 0.0f;
  17368.     m_motorImpulse = 0.0f;
  17369.     m_lowerImpulse = 0.0f;
  17370.     m_upperImpulse = 0.0f;
  17371.  
  17372.     m_lowerAngle = def->lowerAngle;
  17373.     m_upperAngle = def->upperAngle;
  17374.     m_maxMotorTorque = def->maxMotorTorque;
  17375.     m_motorSpeed = def->motorSpeed;
  17376.     m_enableLimit = def->enableLimit;
  17377.     m_enableMotor = def->enableMotor;
  17378.  
  17379.     m_angle = 0.0f;
  17380. }
  17381.  
  17382. void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) {
  17383.     m_indexA = m_bodyA->m_islandIndex;
  17384.     m_indexB = m_bodyB->m_islandIndex;
  17385.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  17386.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  17387.     m_invMassA = m_bodyA->m_invMass;
  17388.     m_invMassB = m_bodyB->m_invMass;
  17389.     m_invIA = m_bodyA->m_invI;
  17390.     m_invIB = m_bodyB->m_invI;
  17391.  
  17392.     float aA = data.positions[m_indexA].a;
  17393.     b2Vec2 vA = data.velocities[m_indexA].v;
  17394.     float wA = data.velocities[m_indexA].w;
  17395.  
  17396.     float aB = data.positions[m_indexB].a;
  17397.     b2Vec2 vB = data.velocities[m_indexB].v;
  17398.     float wB = data.velocities[m_indexB].w;
  17399.  
  17400.     b2Rot qA(aA), qB(aB);
  17401.  
  17402.     m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  17403.     m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  17404.  
  17405.     // J = [-I -r1_skew I r2_skew]
  17406.     // r_skew = [-ry; rx]
  17407.  
  17408.     // Matlab
  17409.     // K = [ mA+r1y^2*iA+mB+r2y^2*iB,  -r1y*iA*r1x-r2y*iB*r2x]
  17410.     //     [  -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB]
  17411.  
  17412.     float mA = m_invMassA, mB = m_invMassB;
  17413.     float iA = m_invIA, iB = m_invIB;
  17414.  
  17415.     m_K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB;
  17416.     m_K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB;
  17417.     m_K.ex.y = m_K.ey.x;
  17418.     m_K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB;
  17419.  
  17420.     m_axialMass = iA + iB;
  17421.     bool fixedRotation;
  17422.     if (m_axialMass > 0.0f) {
  17423.         m_axialMass = 1.0f / m_axialMass;
  17424.         fixedRotation = false;
  17425.     } else {
  17426.         fixedRotation = true;
  17427.     }
  17428.  
  17429.     m_angle = aB - aA - m_referenceAngle;
  17430.     if (m_enableLimit == false || fixedRotation) {
  17431.         m_lowerImpulse = 0.0f;
  17432.         m_upperImpulse = 0.0f;
  17433.     }
  17434.  
  17435.     if (m_enableMotor == false || fixedRotation) {
  17436.         m_motorImpulse = 0.0f;
  17437.     }
  17438.  
  17439.     if (data.step.warmStarting) {
  17440.         // Scale impulses to support a variable time step.
  17441.         m_impulse *= data.step.dtRatio;
  17442.         m_motorImpulse *= data.step.dtRatio;
  17443.         m_lowerImpulse *= data.step.dtRatio;
  17444.         m_upperImpulse *= data.step.dtRatio;
  17445.  
  17446.         float axialImpulse = m_motorImpulse + m_lowerImpulse - m_upperImpulse;
  17447.         b2Vec2 P(m_impulse.x, m_impulse.y);
  17448.  
  17449.         vA -= mA * P;
  17450.         wA -= iA * (b2Cross(m_rA, P) + axialImpulse);
  17451.  
  17452.         vB += mB * P;
  17453.         wB += iB * (b2Cross(m_rB, P) + axialImpulse);
  17454.     } else {
  17455.         m_impulse.SetZero();
  17456.         m_motorImpulse = 0.0f;
  17457.         m_lowerImpulse = 0.0f;
  17458.         m_upperImpulse = 0.0f;
  17459.     }
  17460.  
  17461.     data.velocities[m_indexA].v = vA;
  17462.     data.velocities[m_indexA].w = wA;
  17463.     data.velocities[m_indexB].v = vB;
  17464.     data.velocities[m_indexB].w = wB;
  17465. }
  17466.  
  17467. void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) {
  17468.     b2Vec2 vA = data.velocities[m_indexA].v;
  17469.     float wA = data.velocities[m_indexA].w;
  17470.     b2Vec2 vB = data.velocities[m_indexB].v;
  17471.     float wB = data.velocities[m_indexB].w;
  17472.  
  17473.     float mA = m_invMassA, mB = m_invMassB;
  17474.     float iA = m_invIA, iB = m_invIB;
  17475.  
  17476.     bool fixedRotation = (iA + iB == 0.0f);
  17477.  
  17478.     // Solve motor constraint.
  17479.     if (m_enableMotor && fixedRotation == false) {
  17480.         float Cdot = wB - wA - m_motorSpeed;
  17481.         float impulse = -m_axialMass * Cdot;
  17482.         float oldImpulse = m_motorImpulse;
  17483.         float maxImpulse = data.step.dt * m_maxMotorTorque;
  17484.         m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
  17485.         impulse = m_motorImpulse - oldImpulse;
  17486.  
  17487.         wA -= iA * impulse;
  17488.         wB += iB * impulse;
  17489.     }
  17490.  
  17491.     if (m_enableLimit && fixedRotation == false) {
  17492.         // Lower limit
  17493.         {
  17494.             float C = m_angle - m_lowerAngle;
  17495.             float Cdot = wB - wA;
  17496.             float impulse = -m_axialMass * (Cdot + b2Max(C, 0.0f) * data.step.inv_dt);
  17497.             float oldImpulse = m_lowerImpulse;
  17498.             m_lowerImpulse = b2Max(m_lowerImpulse + impulse, 0.0f);
  17499.             impulse = m_lowerImpulse - oldImpulse;
  17500.  
  17501.             wA -= iA * impulse;
  17502.             wB += iB * impulse;
  17503.         }
  17504.  
  17505.         // Upper limit
  17506.         // Note: signs are flipped to keep C positive when the constraint is satisfied.
  17507.         // This also keeps the impulse positive when the limit is active.
  17508.         {
  17509.             float C = m_upperAngle - m_angle;
  17510.             float Cdot = wA - wB;
  17511.             float impulse = -m_axialMass * (Cdot + b2Max(C, 0.0f) * data.step.inv_dt);
  17512.             float oldImpulse = m_upperImpulse;
  17513.             m_upperImpulse = b2Max(m_upperImpulse + impulse, 0.0f);
  17514.             impulse = m_upperImpulse - oldImpulse;
  17515.  
  17516.             wA += iA * impulse;
  17517.             wB -= iB * impulse;
  17518.         }
  17519.     }
  17520.  
  17521.     // Solve point-to-point constraint
  17522.     {
  17523.         b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
  17524.         b2Vec2 impulse = m_K.Solve(-Cdot);
  17525.  
  17526.         m_impulse.x += impulse.x;
  17527.         m_impulse.y += impulse.y;
  17528.  
  17529.         vA -= mA * impulse;
  17530.         wA -= iA * b2Cross(m_rA, impulse);
  17531.  
  17532.         vB += mB * impulse;
  17533.         wB += iB * b2Cross(m_rB, impulse);
  17534.     }
  17535.  
  17536.     data.velocities[m_indexA].v = vA;
  17537.     data.velocities[m_indexA].w = wA;
  17538.     data.velocities[m_indexB].v = vB;
  17539.     data.velocities[m_indexB].w = wB;
  17540. }
  17541.  
  17542. bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) {
  17543.     b2Vec2 cA = data.positions[m_indexA].c;
  17544.     float aA = data.positions[m_indexA].a;
  17545.     b2Vec2 cB = data.positions[m_indexB].c;
  17546.     float aB = data.positions[m_indexB].a;
  17547.  
  17548.     b2Rot qA(aA), qB(aB);
  17549.  
  17550.     float angularError = 0.0f;
  17551.     float positionError = 0.0f;
  17552.  
  17553.     bool fixedRotation = (m_invIA + m_invIB == 0.0f);
  17554.  
  17555.     // Solve angular limit constraint
  17556.     if (m_enableLimit && fixedRotation == false) {
  17557.         float angle = aB - aA - m_referenceAngle;
  17558.         float C = 0.0f;
  17559.  
  17560.         if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) {
  17561.             // Prevent large angular corrections
  17562.             C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection);
  17563.         } else if (angle <= m_lowerAngle) {
  17564.             // Prevent large angular corrections and allow some slop.
  17565.             C = b2Clamp(angle - m_lowerAngle + b2_angularSlop, -b2_maxAngularCorrection, 0.0f);
  17566.         } else if (angle >= m_upperAngle) {
  17567.             // Prevent large angular corrections and allow some slop.
  17568.             C = b2Clamp(angle - m_upperAngle - b2_angularSlop, 0.0f, b2_maxAngularCorrection);
  17569.         }
  17570.  
  17571.         float limitImpulse = -m_axialMass * C;
  17572.         aA -= m_invIA * limitImpulse;
  17573.         aB += m_invIB * limitImpulse;
  17574.         angularError = b2Abs(C);
  17575.     }
  17576.  
  17577.     // Solve point-to-point constraint.
  17578.     {
  17579.         qA.Set(aA);
  17580.         qB.Set(aB);
  17581.         b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  17582.         b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  17583.  
  17584.         b2Vec2 C = cB + rB - cA - rA;
  17585.         positionError = C.Length();
  17586.  
  17587.         float mA = m_invMassA, mB = m_invMassB;
  17588.         float iA = m_invIA, iB = m_invIB;
  17589.  
  17590.         b2Mat22 K;
  17591.         K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y;
  17592.         K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y;
  17593.         K.ey.x = K.ex.y;
  17594.         K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x;
  17595.  
  17596.         b2Vec2 impulse = -K.Solve(C);
  17597.  
  17598.         cA -= mA * impulse;
  17599.         aA -= iA * b2Cross(rA, impulse);
  17600.  
  17601.         cB += mB * impulse;
  17602.         aB += iB * b2Cross(rB, impulse);
  17603.     }
  17604.  
  17605.     data.positions[m_indexA].c = cA;
  17606.     data.positions[m_indexA].a = aA;
  17607.     data.positions[m_indexB].c = cB;
  17608.     data.positions[m_indexB].a = aB;
  17609.  
  17610.     return positionError <= b2_linearSlop && angularError <= b2_angularSlop;
  17611. }
  17612.  
  17613. b2Vec2 b2RevoluteJoint::GetAnchorA() const {
  17614.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  17615. }
  17616.  
  17617. b2Vec2 b2RevoluteJoint::GetAnchorB() const {
  17618.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  17619. }
  17620.  
  17621. b2Vec2 b2RevoluteJoint::GetReactionForce(float inv_dt) const {
  17622.     b2Vec2 P(m_impulse.x, m_impulse.y);
  17623.     return inv_dt * P;
  17624. }
  17625.  
  17626. float b2RevoluteJoint::GetReactionTorque(float inv_dt) const {
  17627.     return inv_dt * (m_motorImpulse + m_lowerImpulse - m_upperImpulse);
  17628. }
  17629.  
  17630. float b2RevoluteJoint::GetJointAngle() const {
  17631.     b2Body* bA = m_bodyA;
  17632.     b2Body* bB = m_bodyB;
  17633.     return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle;
  17634. }
  17635.  
  17636. float b2RevoluteJoint::GetJointSpeed() const {
  17637.     b2Body* bA = m_bodyA;
  17638.     b2Body* bB = m_bodyB;
  17639.     return bB->m_angularVelocity - bA->m_angularVelocity;
  17640. }
  17641.  
  17642. bool b2RevoluteJoint::IsMotorEnabled() const {
  17643.     return m_enableMotor;
  17644. }
  17645.  
  17646. void b2RevoluteJoint::EnableMotor(bool flag) {
  17647.     if (flag != m_enableMotor) {
  17648.         m_bodyA->SetAwake(true);
  17649.         m_bodyB->SetAwake(true);
  17650.         m_enableMotor = flag;
  17651.     }
  17652. }
  17653.  
  17654. float b2RevoluteJoint::GetMotorTorque(float inv_dt) const {
  17655.     return inv_dt * m_motorImpulse;
  17656. }
  17657.  
  17658. void b2RevoluteJoint::SetMotorSpeed(float speed) {
  17659.     if (speed != m_motorSpeed) {
  17660.         m_bodyA->SetAwake(true);
  17661.         m_bodyB->SetAwake(true);
  17662.         m_motorSpeed = speed;
  17663.     }
  17664. }
  17665.  
  17666. void b2RevoluteJoint::SetMaxMotorTorque(float torque) {
  17667.     if (torque != m_maxMotorTorque) {
  17668.         m_bodyA->SetAwake(true);
  17669.         m_bodyB->SetAwake(true);
  17670.         m_maxMotorTorque = torque;
  17671.     }
  17672. }
  17673.  
  17674. bool b2RevoluteJoint::IsLimitEnabled() const {
  17675.     return m_enableLimit;
  17676. }
  17677.  
  17678. void b2RevoluteJoint::EnableLimit(bool flag) {
  17679.     if (flag != m_enableLimit) {
  17680.         m_bodyA->SetAwake(true);
  17681.         m_bodyB->SetAwake(true);
  17682.         m_enableLimit = flag;
  17683.         m_lowerImpulse = 0.0f;
  17684.         m_upperImpulse = 0.0f;
  17685.     }
  17686. }
  17687.  
  17688. float b2RevoluteJoint::GetLowerLimit() const {
  17689.     return m_lowerAngle;
  17690. }
  17691.  
  17692. float b2RevoluteJoint::GetUpperLimit() const {
  17693.     return m_upperAngle;
  17694. }
  17695.  
  17696. void b2RevoluteJoint::SetLimits(float lower, float upper) {
  17697.     b2Assert(lower <= upper);
  17698.  
  17699.     if (lower != m_lowerAngle || upper != m_upperAngle) {
  17700.         m_bodyA->SetAwake(true);
  17701.         m_bodyB->SetAwake(true);
  17702.         m_lowerImpulse = 0.0f;
  17703.         m_upperImpulse = 0.0f;
  17704.         m_lowerAngle = lower;
  17705.         m_upperAngle = upper;
  17706.     }
  17707. }
  17708.  
  17709. void b2RevoluteJoint::Dump() {
  17710.     int32 indexA = m_bodyA->m_islandIndex;
  17711.     int32 indexB = m_bodyB->m_islandIndex;
  17712.  
  17713.     b2Dump("  b2RevoluteJointDef jd;\n");
  17714.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  17715.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  17716.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  17717.     b2Dump("  jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
  17718.     b2Dump("  jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
  17719.     b2Dump("  jd.referenceAngle = %.9g;\n", m_referenceAngle);
  17720.     b2Dump("  jd.enableLimit = bool(%d);\n", m_enableLimit);
  17721.     b2Dump("  jd.lowerAngle = %.9g;\n", m_lowerAngle);
  17722.     b2Dump("  jd.upperAngle = %.9g;\n", m_upperAngle);
  17723.     b2Dump("  jd.enableMotor = bool(%d);\n", m_enableMotor);
  17724.     b2Dump("  jd.motorSpeed = %.9g;\n", m_motorSpeed);
  17725.     b2Dump("  jd.maxMotorTorque = %.9g;\n", m_maxMotorTorque);
  17726.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  17727. }
  17728.  
  17729. ///
  17730. void b2RevoluteJoint::Draw(b2Draw* draw) const {
  17731.     const b2Transform& xfA = m_bodyA->GetTransform();
  17732.     const b2Transform& xfB = m_bodyB->GetTransform();
  17733.     b2Vec2 pA = b2Mul(xfA, m_localAnchorA);
  17734.     b2Vec2 pB = b2Mul(xfB, m_localAnchorB);
  17735.  
  17736.     b2Color c1(0.7f, 0.7f, 0.7f);
  17737.     b2Color c2(0.3f, 0.9f, 0.3f);
  17738.     b2Color c3(0.9f, 0.3f, 0.3f);
  17739.     b2Color c4(0.3f, 0.3f, 0.9f);
  17740.     b2Color c5(0.4f, 0.4f, 0.4f);
  17741.  
  17742.     draw->DrawPoint(pA, 5.0f, c4);
  17743.     draw->DrawPoint(pB, 5.0f, c5);
  17744.  
  17745.     float aA = m_bodyA->GetAngle();
  17746.     float aB = m_bodyB->GetAngle();
  17747.     float angle = aB - aA - m_referenceAngle;
  17748.  
  17749.     const float L = 0.5f;
  17750.  
  17751.     b2Vec2 r = L * b2Vec2(cosf(angle), sinf(angle));
  17752.     draw->DrawSegment(pB, pB + r, c1);
  17753.     draw->DrawCircle(pB, L, c1);
  17754.  
  17755.     if (m_enableLimit) {
  17756.         b2Vec2 rlo = L * b2Vec2(cosf(m_lowerAngle), sinf(m_lowerAngle));
  17757.         b2Vec2 rhi = L * b2Vec2(cosf(m_upperAngle), sinf(m_upperAngle));
  17758.  
  17759.         draw->DrawSegment(pB, pB + rlo, c2);
  17760.         draw->DrawSegment(pB, pB + rhi, c3);
  17761.     }
  17762.  
  17763.     b2Color color(0.5f, 0.8f, 0.8f);
  17764.     draw->DrawSegment(xfA.p, pA, color);
  17765.     draw->DrawSegment(pA, pB, color);
  17766.     draw->DrawSegment(xfB.p, pB, color);
  17767. }
  17768. // MIT License
  17769.  
  17770. // Copyright (c) 2019 Erin Catto
  17771.  
  17772. // Permission is hereby granted, free of charge, to any person obtaining a copy
  17773. // of this software and associated documentation files (the "Software"), to deal
  17774. // in the Software without restriction, including without limitation the rights
  17775. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17776. // copies of the Software, and to permit persons to whom the Software is
  17777. // furnished to do so, subject to the following conditions:
  17778.  
  17779. // The above copyright notice and this permission notice shall be included in all
  17780. // copies or substantial portions of the Software.
  17781.  
  17782. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17783. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17784. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17785. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17786. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17787. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17788. // SOFTWARE.
  17789.  
  17790. //#include "box2d/b2_body.h"
  17791. //#include "box2d/b2_time_step.h"
  17792. //#include "box2d/b2_weld_joint.h"
  17793.  
  17794. // Point-to-point constraint
  17795. // C = p2 - p1
  17796. // Cdot = v2 - v1
  17797. //      = v2 + cross(w2, r2) - v1 - cross(w1, r1)
  17798. // J = [-I -r1_skew I r2_skew ]
  17799. // Identity used:
  17800. // w k % (rx i + ry j) = w * (-ry i + rx j)
  17801.  
  17802. // Angle constraint
  17803. // C = angle2 - angle1 - referenceAngle
  17804. // Cdot = w2 - w1
  17805. // J = [0 0 -1 0 0 1]
  17806. // K = invI1 + invI2
  17807.  
  17808. void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) {
  17809.     bodyA = bA;
  17810.     bodyB = bB;
  17811.     localAnchorA = bodyA->GetLocalPoint(anchor);
  17812.     localAnchorB = bodyB->GetLocalPoint(anchor);
  17813.     referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
  17814. }
  17815.  
  17816. b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def)
  17817.     : b2Joint(def) {
  17818.     m_localAnchorA = def->localAnchorA;
  17819.     m_localAnchorB = def->localAnchorB;
  17820.     m_referenceAngle = def->referenceAngle;
  17821.     m_stiffness = def->stiffness;
  17822.     m_damping = def->damping;
  17823.  
  17824.     m_impulse.SetZero();
  17825. }
  17826.  
  17827. void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) {
  17828.     m_indexA = m_bodyA->m_islandIndex;
  17829.     m_indexB = m_bodyB->m_islandIndex;
  17830.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  17831.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  17832.     m_invMassA = m_bodyA->m_invMass;
  17833.     m_invMassB = m_bodyB->m_invMass;
  17834.     m_invIA = m_bodyA->m_invI;
  17835.     m_invIB = m_bodyB->m_invI;
  17836.  
  17837.     float aA = data.positions[m_indexA].a;
  17838.     b2Vec2 vA = data.velocities[m_indexA].v;
  17839.     float wA = data.velocities[m_indexA].w;
  17840.  
  17841.     float aB = data.positions[m_indexB].a;
  17842.     b2Vec2 vB = data.velocities[m_indexB].v;
  17843.     float wB = data.velocities[m_indexB].w;
  17844.  
  17845.     b2Rot qA(aA), qB(aB);
  17846.  
  17847.     m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  17848.     m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  17849.  
  17850.     // J = [-I -r1_skew I r2_skew]
  17851.     //     [ 0       -1 0       1]
  17852.     // r_skew = [-ry; rx]
  17853.  
  17854.     // Matlab
  17855.     // K = [ mA+r1y^2*iA+mB+r2y^2*iB,  -r1y*iA*r1x-r2y*iB*r2x,          -r1y*iA-r2y*iB]
  17856.     //     [  -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB,           r1x*iA+r2x*iB]
  17857.     //     [          -r1y*iA-r2y*iB,           r1x*iA+r2x*iB,                   iA+iB]
  17858.  
  17859.     float mA = m_invMassA, mB = m_invMassB;
  17860.     float iA = m_invIA, iB = m_invIB;
  17861.  
  17862.     b2Mat33 K;
  17863.     K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB;
  17864.     K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB;
  17865.     K.ez.x = -m_rA.y * iA - m_rB.y * iB;
  17866.     K.ex.y = K.ey.x;
  17867.     K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB;
  17868.     K.ez.y = m_rA.x * iA + m_rB.x * iB;
  17869.     K.ex.z = K.ez.x;
  17870.     K.ey.z = K.ez.y;
  17871.     K.ez.z = iA + iB;
  17872.  
  17873.     if (m_stiffness > 0.0f) {
  17874.         K.GetInverse22(&m_mass);
  17875.  
  17876.         float invM = iA + iB;
  17877.  
  17878.         float C = aB - aA - m_referenceAngle;
  17879.  
  17880.         // Damping coefficient
  17881.         float d = m_damping;
  17882.  
  17883.         // Spring stiffness
  17884.         float k = m_stiffness;
  17885.  
  17886.         // magic formulas
  17887.         float h = data.step.dt;
  17888.         m_gamma = h * (d + h * k);
  17889.         m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f;
  17890.         m_bias = C * h * k * m_gamma;
  17891.  
  17892.         invM += m_gamma;
  17893.         m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f;
  17894.     } else if (K.ez.z == 0.0f) {
  17895.         K.GetInverse22(&m_mass);
  17896.         m_gamma = 0.0f;
  17897.         m_bias = 0.0f;
  17898.     } else {
  17899.         K.GetSymInverse33(&m_mass);
  17900.         m_gamma = 0.0f;
  17901.         m_bias = 0.0f;
  17902.     }
  17903.  
  17904.     if (data.step.warmStarting) {
  17905.         // Scale impulses to support a variable time step.
  17906.         m_impulse *= data.step.dtRatio;
  17907.  
  17908.         b2Vec2 P(m_impulse.x, m_impulse.y);
  17909.  
  17910.         vA -= mA * P;
  17911.         wA -= iA * (b2Cross(m_rA, P) + m_impulse.z);
  17912.  
  17913.         vB += mB * P;
  17914.         wB += iB * (b2Cross(m_rB, P) + m_impulse.z);
  17915.     } else {
  17916.         m_impulse.SetZero();
  17917.     }
  17918.  
  17919.     data.velocities[m_indexA].v = vA;
  17920.     data.velocities[m_indexA].w = wA;
  17921.     data.velocities[m_indexB].v = vB;
  17922.     data.velocities[m_indexB].w = wB;
  17923. }
  17924.  
  17925. void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) {
  17926.     b2Vec2 vA = data.velocities[m_indexA].v;
  17927.     float wA = data.velocities[m_indexA].w;
  17928.     b2Vec2 vB = data.velocities[m_indexB].v;
  17929.     float wB = data.velocities[m_indexB].w;
  17930.  
  17931.     float mA = m_invMassA, mB = m_invMassB;
  17932.     float iA = m_invIA, iB = m_invIB;
  17933.  
  17934.     if (m_stiffness > 0.0f) {
  17935.         float Cdot2 = wB - wA;
  17936.  
  17937.         float impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z);
  17938.         m_impulse.z += impulse2;
  17939.  
  17940.         wA -= iA * impulse2;
  17941.         wB += iB * impulse2;
  17942.  
  17943.         b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
  17944.  
  17945.         b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1);
  17946.         m_impulse.x += impulse1.x;
  17947.         m_impulse.y += impulse1.y;
  17948.  
  17949.         b2Vec2 P = impulse1;
  17950.  
  17951.         vA -= mA * P;
  17952.         wA -= iA * b2Cross(m_rA, P);
  17953.  
  17954.         vB += mB * P;
  17955.         wB += iB * b2Cross(m_rB, P);
  17956.     } else {
  17957.         b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
  17958.         float Cdot2 = wB - wA;
  17959.         b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2);
  17960.  
  17961.         b2Vec3 impulse = -b2Mul(m_mass, Cdot);
  17962.         m_impulse += impulse;
  17963.  
  17964.         b2Vec2 P(impulse.x, impulse.y);
  17965.  
  17966.         vA -= mA * P;
  17967.         wA -= iA * (b2Cross(m_rA, P) + impulse.z);
  17968.  
  17969.         vB += mB * P;
  17970.         wB += iB * (b2Cross(m_rB, P) + impulse.z);
  17971.     }
  17972.  
  17973.     data.velocities[m_indexA].v = vA;
  17974.     data.velocities[m_indexA].w = wA;
  17975.     data.velocities[m_indexB].v = vB;
  17976.     data.velocities[m_indexB].w = wB;
  17977. }
  17978.  
  17979. bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) {
  17980.     b2Vec2 cA = data.positions[m_indexA].c;
  17981.     float aA = data.positions[m_indexA].a;
  17982.     b2Vec2 cB = data.positions[m_indexB].c;
  17983.     float aB = data.positions[m_indexB].a;
  17984.  
  17985.     b2Rot qA(aA), qB(aB);
  17986.  
  17987.     float mA = m_invMassA, mB = m_invMassB;
  17988.     float iA = m_invIA, iB = m_invIB;
  17989.  
  17990.     b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  17991.     b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  17992.  
  17993.     float positionError, angularError;
  17994.  
  17995.     b2Mat33 K;
  17996.     K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB;
  17997.     K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB;
  17998.     K.ez.x = -rA.y * iA - rB.y * iB;
  17999.     K.ex.y = K.ey.x;
  18000.     K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB;
  18001.     K.ez.y = rA.x * iA + rB.x * iB;
  18002.     K.ex.z = K.ez.x;
  18003.     K.ey.z = K.ez.y;
  18004.     K.ez.z = iA + iB;
  18005.  
  18006.     if (m_stiffness > 0.0f) {
  18007.         b2Vec2 C1 = cB + rB - cA - rA;
  18008.  
  18009.         positionError = C1.Length();
  18010.         angularError = 0.0f;
  18011.  
  18012.         b2Vec2 P = -K.Solve22(C1);
  18013.  
  18014.         cA -= mA * P;
  18015.         aA -= iA * b2Cross(rA, P);
  18016.  
  18017.         cB += mB * P;
  18018.         aB += iB * b2Cross(rB, P);
  18019.     } else {
  18020.         b2Vec2 C1 = cB + rB - cA - rA;
  18021.         float C2 = aB - aA - m_referenceAngle;
  18022.  
  18023.         positionError = C1.Length();
  18024.         angularError = b2Abs(C2);
  18025.  
  18026.         b2Vec3 C(C1.x, C1.y, C2);
  18027.  
  18028.         b2Vec3 impulse;
  18029.         if (K.ez.z > 0.0f) {
  18030.             impulse = -K.Solve33(C);
  18031.         } else {
  18032.             b2Vec2 impulse2 = -K.Solve22(C1);
  18033.             impulse.Set(impulse2.x, impulse2.y, 0.0f);
  18034.         }
  18035.  
  18036.         b2Vec2 P(impulse.x, impulse.y);
  18037.  
  18038.         cA -= mA * P;
  18039.         aA -= iA * (b2Cross(rA, P) + impulse.z);
  18040.  
  18041.         cB += mB * P;
  18042.         aB += iB * (b2Cross(rB, P) + impulse.z);
  18043.     }
  18044.  
  18045.     data.positions[m_indexA].c = cA;
  18046.     data.positions[m_indexA].a = aA;
  18047.     data.positions[m_indexB].c = cB;
  18048.     data.positions[m_indexB].a = aB;
  18049.  
  18050.     return positionError <= b2_linearSlop && angularError <= b2_angularSlop;
  18051. }
  18052.  
  18053. b2Vec2 b2WeldJoint::GetAnchorA() const {
  18054.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  18055. }
  18056.  
  18057. b2Vec2 b2WeldJoint::GetAnchorB() const {
  18058.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  18059. }
  18060.  
  18061. b2Vec2 b2WeldJoint::GetReactionForce(float inv_dt) const {
  18062.     b2Vec2 P(m_impulse.x, m_impulse.y);
  18063.     return inv_dt * P;
  18064. }
  18065.  
  18066. float b2WeldJoint::GetReactionTorque(float inv_dt) const {
  18067.     return inv_dt * m_impulse.z;
  18068. }
  18069.  
  18070. void b2WeldJoint::Dump() {
  18071.     int32 indexA = m_bodyA->m_islandIndex;
  18072.     int32 indexB = m_bodyB->m_islandIndex;
  18073.  
  18074.     b2Dump("  b2WeldJointDef jd;\n");
  18075.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  18076.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  18077.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  18078.     b2Dump("  jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
  18079.     b2Dump("  jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
  18080.     b2Dump("  jd.referenceAngle = %.9g;\n", m_referenceAngle);
  18081.     b2Dump("  jd.stiffness = %.9g;\n", m_stiffness);
  18082.     b2Dump("  jd.damping = %.9g;\n", m_damping);
  18083.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  18084. }
  18085. // MIT License
  18086.  
  18087. // Copyright (c) 2019 Erin Catto
  18088.  
  18089. // Permission is hereby granted, free of charge, to any person obtaining a copy
  18090. // of this software and associated documentation files (the "Software"), to deal
  18091. // in the Software without restriction, including without limitation the rights
  18092. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18093. // copies of the Software, and to permit persons to whom the Software is
  18094. // furnished to do so, subject to the following conditions:
  18095.  
  18096. // The above copyright notice and this permission notice shall be included in all
  18097. // copies or substantial portions of the Software.
  18098.  
  18099. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18100. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18101. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18102. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18103. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18104. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18105. // SOFTWARE.
  18106.  
  18107. //#include "box2d/b2_body.h"
  18108. //#include "box2d/b2_draw.h"
  18109. //#include "box2d/b2_wheel_joint.h"
  18110. //#include "box2d/b2_time_step.h"
  18111.  
  18112. // Linear constraint (point-to-line)
  18113. // d = pB - pA = xB + rB - xA - rA
  18114. // C = dot(ay, d)
  18115. // Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA))
  18116. //      = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB)
  18117. // J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)]
  18118.  
  18119. // Spring linear constraint
  18120. // C = dot(ax, d)
  18121. // Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB)
  18122. // J = [-ax -cross(d+rA, ax) ax cross(rB, ax)]
  18123.  
  18124. // Motor rotational constraint
  18125. // Cdot = wB - wA
  18126. // J = [0 0 -1 0 0 1]
  18127.  
  18128. void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) {
  18129.     bodyA = bA;
  18130.     bodyB = bB;
  18131.     localAnchorA = bodyA->GetLocalPoint(anchor);
  18132.     localAnchorB = bodyB->GetLocalPoint(anchor);
  18133.     localAxisA = bodyA->GetLocalVector(axis);
  18134. }
  18135.  
  18136. b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def)
  18137.     : b2Joint(def) {
  18138.     m_localAnchorA = def->localAnchorA;
  18139.     m_localAnchorB = def->localAnchorB;
  18140.     m_localXAxisA = def->localAxisA;
  18141.     m_localYAxisA = b2Cross(1.0f, m_localXAxisA);
  18142.  
  18143.     m_mass = 0.0f;
  18144.     m_impulse = 0.0f;
  18145.     m_motorMass = 0.0f;
  18146.     m_motorImpulse = 0.0f;
  18147.     m_springMass = 0.0f;
  18148.     m_springImpulse = 0.0f;
  18149.  
  18150.     m_axialMass = 0.0f;
  18151.     m_lowerImpulse = 0.0f;
  18152.     m_upperImpulse = 0.0f;
  18153.     m_lowerTranslation = def->lowerTranslation;
  18154.     m_upperTranslation = def->upperTranslation;
  18155.     m_enableLimit = def->enableLimit;
  18156.  
  18157.     m_maxMotorTorque = def->maxMotorTorque;
  18158.     m_motorSpeed = def->motorSpeed;
  18159.     m_enableMotor = def->enableMotor;
  18160.  
  18161.     m_bias = 0.0f;
  18162.     m_gamma = 0.0f;
  18163.  
  18164.     m_ax.SetZero();
  18165.     m_ay.SetZero();
  18166.  
  18167.     m_stiffness = def->stiffness;
  18168.     m_damping = def->damping;
  18169. }
  18170.  
  18171. void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) {
  18172.     m_indexA = m_bodyA->m_islandIndex;
  18173.     m_indexB = m_bodyB->m_islandIndex;
  18174.     m_localCenterA = m_bodyA->m_sweep.localCenter;
  18175.     m_localCenterB = m_bodyB->m_sweep.localCenter;
  18176.     m_invMassA = m_bodyA->m_invMass;
  18177.     m_invMassB = m_bodyB->m_invMass;
  18178.     m_invIA = m_bodyA->m_invI;
  18179.     m_invIB = m_bodyB->m_invI;
  18180.  
  18181.     float mA = m_invMassA, mB = m_invMassB;
  18182.     float iA = m_invIA, iB = m_invIB;
  18183.  
  18184.     b2Vec2 cA = data.positions[m_indexA].c;
  18185.     float aA = data.positions[m_indexA].a;
  18186.     b2Vec2 vA = data.velocities[m_indexA].v;
  18187.     float wA = data.velocities[m_indexA].w;
  18188.  
  18189.     b2Vec2 cB = data.positions[m_indexB].c;
  18190.     float aB = data.positions[m_indexB].a;
  18191.     b2Vec2 vB = data.velocities[m_indexB].v;
  18192.     float wB = data.velocities[m_indexB].w;
  18193.  
  18194.     b2Rot qA(aA), qB(aB);
  18195.  
  18196.     // Compute the effective masses.
  18197.     b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  18198.     b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  18199.     b2Vec2 d = cB + rB - cA - rA;
  18200.  
  18201.     // Point to line constraint
  18202.     {
  18203.         m_ay = b2Mul(qA, m_localYAxisA);
  18204.         m_sAy = b2Cross(d + rA, m_ay);
  18205.         m_sBy = b2Cross(rB, m_ay);
  18206.  
  18207.         m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy;
  18208.  
  18209.         if (m_mass > 0.0f) {
  18210.             m_mass = 1.0f / m_mass;
  18211.         }
  18212.     }
  18213.  
  18214.     // Spring constraint
  18215.     m_ax = b2Mul(qA, m_localXAxisA);
  18216.     m_sAx = b2Cross(d + rA, m_ax);
  18217.     m_sBx = b2Cross(rB, m_ax);
  18218.  
  18219.     const float invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx;
  18220.     if (invMass > 0.0f) {
  18221.         m_axialMass = 1.0f / invMass;
  18222.     } else {
  18223.         m_axialMass = 0.0f;
  18224.     }
  18225.  
  18226.     m_springMass = 0.0f;
  18227.     m_bias = 0.0f;
  18228.     m_gamma = 0.0f;
  18229.  
  18230.     if (m_stiffness > 0.0f && invMass > 0.0f) {
  18231.         m_springMass = 1.0f / invMass;
  18232.  
  18233.         float C = b2Dot(d, m_ax);
  18234.  
  18235.         // magic formulas
  18236.         float h = data.step.dt;
  18237.         m_gamma = h * (m_damping + h * m_stiffness);
  18238.         if (m_gamma > 0.0f) {
  18239.             m_gamma = 1.0f / m_gamma;
  18240.         }
  18241.  
  18242.         m_bias = C * h * m_stiffness * m_gamma;
  18243.  
  18244.         m_springMass = invMass + m_gamma;
  18245.         if (m_springMass > 0.0f) {
  18246.             m_springMass = 1.0f / m_springMass;
  18247.         }
  18248.     } else {
  18249.         m_springImpulse = 0.0f;
  18250.     }
  18251.  
  18252.     if (m_enableLimit) {
  18253.         m_translation = b2Dot(m_ax, d);
  18254.     } else {
  18255.         m_lowerImpulse = 0.0f;
  18256.         m_upperImpulse = 0.0f;
  18257.     }
  18258.  
  18259.     if (m_enableMotor) {
  18260.         m_motorMass = iA + iB;
  18261.         if (m_motorMass > 0.0f) {
  18262.             m_motorMass = 1.0f / m_motorMass;
  18263.         }
  18264.     } else {
  18265.         m_motorMass = 0.0f;
  18266.         m_motorImpulse = 0.0f;
  18267.     }
  18268.  
  18269.     if (data.step.warmStarting) {
  18270.         // Account for variable time step.
  18271.         m_impulse *= data.step.dtRatio;
  18272.         m_springImpulse *= data.step.dtRatio;
  18273.         m_motorImpulse *= data.step.dtRatio;
  18274.  
  18275.         float axialImpulse = m_springImpulse + m_lowerImpulse - m_upperImpulse;
  18276.         b2Vec2 P = m_impulse * m_ay + axialImpulse * m_ax;
  18277.         float LA = m_impulse * m_sAy + axialImpulse * m_sAx + m_motorImpulse;
  18278.         float LB = m_impulse * m_sBy + axialImpulse * m_sBx + m_motorImpulse;
  18279.  
  18280.         vA -= m_invMassA * P;
  18281.         wA -= m_invIA * LA;
  18282.  
  18283.         vB += m_invMassB * P;
  18284.         wB += m_invIB * LB;
  18285.     } else {
  18286.         m_impulse = 0.0f;
  18287.         m_springImpulse = 0.0f;
  18288.         m_motorImpulse = 0.0f;
  18289.         m_lowerImpulse = 0.0f;
  18290.         m_upperImpulse = 0.0f;
  18291.     }
  18292.  
  18293.     data.velocities[m_indexA].v = vA;
  18294.     data.velocities[m_indexA].w = wA;
  18295.     data.velocities[m_indexB].v = vB;
  18296.     data.velocities[m_indexB].w = wB;
  18297. }
  18298.  
  18299. void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) {
  18300.     float mA = m_invMassA, mB = m_invMassB;
  18301.     float iA = m_invIA, iB = m_invIB;
  18302.  
  18303.     b2Vec2 vA = data.velocities[m_indexA].v;
  18304.     float wA = data.velocities[m_indexA].w;
  18305.     b2Vec2 vB = data.velocities[m_indexB].v;
  18306.     float wB = data.velocities[m_indexB].w;
  18307.  
  18308.     // Solve spring constraint
  18309.     {
  18310.         float Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA;
  18311.         float impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse);
  18312.         m_springImpulse += impulse;
  18313.  
  18314.         b2Vec2 P = impulse * m_ax;
  18315.         float LA = impulse * m_sAx;
  18316.         float LB = impulse * m_sBx;
  18317.  
  18318.         vA -= mA * P;
  18319.         wA -= iA * LA;
  18320.  
  18321.         vB += mB * P;
  18322.         wB += iB * LB;
  18323.     }
  18324.  
  18325.     // Solve rotational motor constraint
  18326.     {
  18327.         float Cdot = wB - wA - m_motorSpeed;
  18328.         float impulse = -m_motorMass * Cdot;
  18329.  
  18330.         float oldImpulse = m_motorImpulse;
  18331.         float maxImpulse = data.step.dt * m_maxMotorTorque;
  18332.         m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
  18333.         impulse = m_motorImpulse - oldImpulse;
  18334.  
  18335.         wA -= iA * impulse;
  18336.         wB += iB * impulse;
  18337.     }
  18338.  
  18339.     if (m_enableLimit) {
  18340.         // Lower limit
  18341.         {
  18342.             float C = m_translation - m_lowerTranslation;
  18343.             float Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA;
  18344.             float impulse = -m_axialMass * (Cdot + b2Max(C, 0.0f) * data.step.inv_dt);
  18345.             float oldImpulse = m_lowerImpulse;
  18346.             m_lowerImpulse = b2Max(m_lowerImpulse + impulse, 0.0f);
  18347.             impulse = m_lowerImpulse - oldImpulse;
  18348.  
  18349.             b2Vec2 P = impulse * m_ax;
  18350.             float LA = impulse * m_sAx;
  18351.             float LB = impulse * m_sBx;
  18352.  
  18353.             vA -= mA * P;
  18354.             wA -= iA * LA;
  18355.             vB += mB * P;
  18356.             wB += iB * LB;
  18357.         }
  18358.  
  18359.         // Upper limit
  18360.         // Note: signs are flipped to keep C positive when the constraint is satisfied.
  18361.         // This also keeps the impulse positive when the limit is active.
  18362.         {
  18363.             float C = m_upperTranslation - m_translation;
  18364.             float Cdot = b2Dot(m_ax, vA - vB) + m_sAx * wA - m_sBx * wB;
  18365.             float impulse = -m_axialMass * (Cdot + b2Max(C, 0.0f) * data.step.inv_dt);
  18366.             float oldImpulse = m_upperImpulse;
  18367.             m_upperImpulse = b2Max(m_upperImpulse + impulse, 0.0f);
  18368.             impulse = m_upperImpulse - oldImpulse;
  18369.  
  18370.             b2Vec2 P = impulse * m_ax;
  18371.             float LA = impulse * m_sAx;
  18372.             float LB = impulse * m_sBx;
  18373.  
  18374.             vA += mA * P;
  18375.             wA += iA * LA;
  18376.             vB -= mB * P;
  18377.             wB -= iB * LB;
  18378.         }
  18379.     }
  18380.  
  18381.     // Solve point to line constraint
  18382.     {
  18383.         float Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA;
  18384.         float impulse = -m_mass * Cdot;
  18385.         m_impulse += impulse;
  18386.  
  18387.         b2Vec2 P = impulse * m_ay;
  18388.         float LA = impulse * m_sAy;
  18389.         float LB = impulse * m_sBy;
  18390.  
  18391.         vA -= mA * P;
  18392.         wA -= iA * LA;
  18393.  
  18394.         vB += mB * P;
  18395.         wB += iB * LB;
  18396.     }
  18397.  
  18398.     data.velocities[m_indexA].v = vA;
  18399.     data.velocities[m_indexA].w = wA;
  18400.     data.velocities[m_indexB].v = vB;
  18401.     data.velocities[m_indexB].w = wB;
  18402. }
  18403.  
  18404. bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) {
  18405.     b2Vec2 cA = data.positions[m_indexA].c;
  18406.     float aA = data.positions[m_indexA].a;
  18407.     b2Vec2 cB = data.positions[m_indexB].c;
  18408.     float aB = data.positions[m_indexB].a;
  18409.  
  18410.     float linearError = 0.0f;
  18411.  
  18412.     if (m_enableLimit) {
  18413.         b2Rot qA(aA), qB(aB);
  18414.  
  18415.         b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  18416.         b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  18417.         b2Vec2 d = (cB - cA) + rB - rA;
  18418.  
  18419.         b2Vec2 ax = b2Mul(qA, m_localXAxisA);
  18420.         float sAx = b2Cross(d + rA, m_ax);
  18421.         float sBx = b2Cross(rB, m_ax);
  18422.  
  18423.         float C = 0.0f;
  18424.         float translation = b2Dot(ax, d);
  18425.         if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) {
  18426.             C = translation;
  18427.         } else if (translation <= m_lowerTranslation) {
  18428.             C = b2Min(translation - m_lowerTranslation, 0.0f);
  18429.         } else if (translation >= m_upperTranslation) {
  18430.             C = b2Max(translation - m_upperTranslation, 0.0f);
  18431.         }
  18432.  
  18433.         if (C != 0.0f) {
  18434.  
  18435.             float invMass = m_invMassA + m_invMassB + m_invIA * sAx * sAx + m_invIB * sBx * sBx;
  18436.             float impulse = 0.0f;
  18437.             if (invMass != 0.0f) {
  18438.                 impulse = -C / invMass;
  18439.             }
  18440.  
  18441.             b2Vec2 P = impulse * ax;
  18442.             float LA = impulse * sAx;
  18443.             float LB = impulse * sBx;
  18444.  
  18445.             cA -= m_invMassA * P;
  18446.             aA -= m_invIA * LA;
  18447.             cB += m_invMassB * P;
  18448.             aB += m_invIB * LB;
  18449.  
  18450.             linearError = b2Abs(C);
  18451.         }
  18452.     }
  18453.  
  18454.     // Solve perpendicular constraint
  18455.     {
  18456.         b2Rot qA(aA), qB(aB);
  18457.  
  18458.         b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
  18459.         b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
  18460.         b2Vec2 d = (cB - cA) + rB - rA;
  18461.  
  18462.         b2Vec2 ay = b2Mul(qA, m_localYAxisA);
  18463.  
  18464.         float sAy = b2Cross(d + rA, ay);
  18465.         float sBy = b2Cross(rB, ay);
  18466.  
  18467.         float C = b2Dot(d, ay);
  18468.  
  18469.         float invMass = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy;
  18470.  
  18471.         float impulse = 0.0f;
  18472.         if (invMass != 0.0f) {
  18473.             impulse = -C / invMass;
  18474.         }
  18475.  
  18476.         b2Vec2 P = impulse * ay;
  18477.         float LA = impulse * sAy;
  18478.         float LB = impulse * sBy;
  18479.  
  18480.         cA -= m_invMassA * P;
  18481.         aA -= m_invIA * LA;
  18482.         cB += m_invMassB * P;
  18483.         aB += m_invIB * LB;
  18484.  
  18485.         linearError = b2Max(linearError, b2Abs(C));
  18486.     }
  18487.  
  18488.     data.positions[m_indexA].c = cA;
  18489.     data.positions[m_indexA].a = aA;
  18490.     data.positions[m_indexB].c = cB;
  18491.     data.positions[m_indexB].a = aB;
  18492.  
  18493.     return linearError <= b2_linearSlop;
  18494. }
  18495.  
  18496. b2Vec2 b2WheelJoint::GetAnchorA() const {
  18497.     return m_bodyA->GetWorldPoint(m_localAnchorA);
  18498. }
  18499.  
  18500. b2Vec2 b2WheelJoint::GetAnchorB() const {
  18501.     return m_bodyB->GetWorldPoint(m_localAnchorB);
  18502. }
  18503.  
  18504. b2Vec2 b2WheelJoint::GetReactionForce(float inv_dt) const {
  18505.     return inv_dt * (m_impulse * m_ay + (m_springImpulse + m_lowerImpulse - m_upperImpulse) * m_ax);
  18506. }
  18507.  
  18508. float b2WheelJoint::GetReactionTorque(float inv_dt) const {
  18509.     return inv_dt * m_motorImpulse;
  18510. }
  18511.  
  18512. float b2WheelJoint::GetJointTranslation() const {
  18513.     b2Body* bA = m_bodyA;
  18514.     b2Body* bB = m_bodyB;
  18515.  
  18516.     b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA);
  18517.     b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB);
  18518.     b2Vec2 d = pB - pA;
  18519.     b2Vec2 axis = bA->GetWorldVector(m_localXAxisA);
  18520.  
  18521.     float translation = b2Dot(d, axis);
  18522.     return translation;
  18523. }
  18524.  
  18525. float b2WheelJoint::GetJointLinearSpeed() const {
  18526.     b2Body* bA = m_bodyA;
  18527.     b2Body* bB = m_bodyB;
  18528.  
  18529.     b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter);
  18530.     b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter);
  18531.     b2Vec2 p1 = bA->m_sweep.c + rA;
  18532.     b2Vec2 p2 = bB->m_sweep.c + rB;
  18533.     b2Vec2 d = p2 - p1;
  18534.     b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA);
  18535.  
  18536.     b2Vec2 vA = bA->m_linearVelocity;
  18537.     b2Vec2 vB = bB->m_linearVelocity;
  18538.     float wA = bA->m_angularVelocity;
  18539.     float wB = bB->m_angularVelocity;
  18540.  
  18541.     float speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA));
  18542.     return speed;
  18543. }
  18544.  
  18545. float b2WheelJoint::GetJointAngle() const {
  18546.     b2Body* bA = m_bodyA;
  18547.     b2Body* bB = m_bodyB;
  18548.     return bB->m_sweep.a - bA->m_sweep.a;
  18549. }
  18550.  
  18551. float b2WheelJoint::GetJointAngularSpeed() const {
  18552.     float wA = m_bodyA->m_angularVelocity;
  18553.     float wB = m_bodyB->m_angularVelocity;
  18554.     return wB - wA;
  18555. }
  18556.  
  18557. bool b2WheelJoint::IsLimitEnabled() const {
  18558.     return m_enableLimit;
  18559. }
  18560.  
  18561. void b2WheelJoint::EnableLimit(bool flag) {
  18562.     if (flag != m_enableLimit) {
  18563.         m_bodyA->SetAwake(true);
  18564.         m_bodyB->SetAwake(true);
  18565.         m_enableLimit = flag;
  18566.         m_lowerImpulse = 0.0f;
  18567.         m_upperImpulse = 0.0f;
  18568.     }
  18569. }
  18570.  
  18571. float b2WheelJoint::GetLowerLimit() const {
  18572.     return m_lowerTranslation;
  18573. }
  18574.  
  18575. float b2WheelJoint::GetUpperLimit() const {
  18576.     return m_upperTranslation;
  18577. }
  18578.  
  18579. void b2WheelJoint::SetLimits(float lower, float upper) {
  18580.     b2Assert(lower <= upper);
  18581.     if (lower != m_lowerTranslation || upper != m_upperTranslation) {
  18582.         m_bodyA->SetAwake(true);
  18583.         m_bodyB->SetAwake(true);
  18584.         m_lowerTranslation = lower;
  18585.         m_upperTranslation = upper;
  18586.         m_lowerImpulse = 0.0f;
  18587.         m_upperImpulse = 0.0f;
  18588.     }
  18589. }
  18590.  
  18591. bool b2WheelJoint::IsMotorEnabled() const {
  18592.     return m_enableMotor;
  18593. }
  18594.  
  18595. void b2WheelJoint::EnableMotor(bool flag) {
  18596.     if (flag != m_enableMotor) {
  18597.         m_bodyA->SetAwake(true);
  18598.         m_bodyB->SetAwake(true);
  18599.         m_enableMotor = flag;
  18600.     }
  18601. }
  18602.  
  18603. void b2WheelJoint::SetMotorSpeed(float speed) {
  18604.     if (speed != m_motorSpeed) {
  18605.         m_bodyA->SetAwake(true);
  18606.         m_bodyB->SetAwake(true);
  18607.         m_motorSpeed = speed;
  18608.     }
  18609. }
  18610.  
  18611. void b2WheelJoint::SetMaxMotorTorque(float torque) {
  18612.     if (torque != m_maxMotorTorque) {
  18613.         m_bodyA->SetAwake(true);
  18614.         m_bodyB->SetAwake(true);
  18615.         m_maxMotorTorque = torque;
  18616.     }
  18617. }
  18618.  
  18619. float b2WheelJoint::GetMotorTorque(float inv_dt) const {
  18620.     return inv_dt * m_motorImpulse;
  18621. }
  18622.  
  18623. void b2WheelJoint::SetStiffness(float stiffness) {
  18624.     m_stiffness = stiffness;
  18625. }
  18626.  
  18627. float b2WheelJoint::GetStiffness() const {
  18628.     return m_stiffness;
  18629. }
  18630.  
  18631. void b2WheelJoint::SetDamping(float damping) {
  18632.     m_damping = damping;
  18633. }
  18634.  
  18635. float b2WheelJoint::GetDamping() const {
  18636.     return m_damping;
  18637. }
  18638.  
  18639. void b2WheelJoint::Dump() {
  18640.     // FLT_DECIMAL_DIG == 9
  18641.  
  18642.     int32 indexA = m_bodyA->m_islandIndex;
  18643.     int32 indexB = m_bodyB->m_islandIndex;
  18644.  
  18645.     b2Dump("  b2WheelJointDef jd;\n");
  18646.     b2Dump("  jd.bodyA = bodies[%d];\n", indexA);
  18647.     b2Dump("  jd.bodyB = bodies[%d];\n", indexB);
  18648.     b2Dump("  jd.collideConnected = bool(%d);\n", m_collideConnected);
  18649.     b2Dump("  jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
  18650.     b2Dump("  jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
  18651.     b2Dump("  jd.localAxisA.Set(%.9g, %.9g);\n", m_localXAxisA.x, m_localXAxisA.y);
  18652.     b2Dump("  jd.enableMotor = bool(%d);\n", m_enableMotor);
  18653.     b2Dump("  jd.motorSpeed = %.9g;\n", m_motorSpeed);
  18654.     b2Dump("  jd.maxMotorTorque = %.9g;\n", m_maxMotorTorque);
  18655.     b2Dump("  jd.stiffness = %.9g;\n", m_stiffness);
  18656.     b2Dump("  jd.damping = %.9g;\n", m_damping);
  18657.     b2Dump("  joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
  18658. }
  18659.  
  18660. ///
  18661. void b2WheelJoint::Draw(b2Draw* draw) const {
  18662.     const b2Transform& xfA = m_bodyA->GetTransform();
  18663.     const b2Transform& xfB = m_bodyB->GetTransform();
  18664.     b2Vec2 pA = b2Mul(xfA, m_localAnchorA);
  18665.     b2Vec2 pB = b2Mul(xfB, m_localAnchorB);
  18666.  
  18667.     b2Vec2 axis = b2Mul(xfA.q, m_localXAxisA);
  18668.  
  18669.     b2Color c1(0.7f, 0.7f, 0.7f);
  18670.     b2Color c2(0.3f, 0.9f, 0.3f);
  18671.     b2Color c3(0.9f, 0.3f, 0.3f);
  18672.     b2Color c4(0.3f, 0.3f, 0.9f);
  18673.     b2Color c5(0.4f, 0.4f, 0.4f);
  18674.  
  18675.     draw->DrawSegment(pA, pB, c5);
  18676.  
  18677.     if (m_enableLimit) {
  18678.         b2Vec2 lower = pA + m_lowerTranslation * axis;
  18679.         b2Vec2 upper = pA + m_upperTranslation * axis;
  18680.         b2Vec2 perp = b2Mul(xfA.q, m_localYAxisA);
  18681.         draw->DrawSegment(lower, upper, c1);
  18682.         draw->DrawSegment(lower - 0.5f * perp, lower + 0.5f * perp, c2);
  18683.         draw->DrawSegment(upper - 0.5f * perp, upper + 0.5f * perp, c3);
  18684.     } else {
  18685.         draw->DrawSegment(pA - 1.0f * axis, pA + 1.0f * axis, c1);
  18686.     }
  18687.  
  18688.     draw->DrawPoint(pA, 5.0f, c1);
  18689.     draw->DrawPoint(pB, 5.0f, c4);
  18690. }
  18691. // MIT License
  18692.  
  18693. // Copyright (c) 2019 Erin Catto
  18694.  
  18695. // Permission is hereby granted, free of charge, to any person obtaining a copy
  18696. // of this software and associated documentation files (the "Software"), to deal
  18697. // in the Software without restriction, including without limitation the rights
  18698. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18699. // copies of the Software, and to permit persons to whom the Software is
  18700. // furnished to do so, subject to the following conditions:
  18701.  
  18702. // The above copyright notice and this permission notice shall be included in all
  18703. // copies or substantial portions of the Software.
  18704.  
  18705. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18706. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18707. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18708. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18709. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18710. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18711. // SOFTWARE.
  18712.  
  18713. //#include "b2_contact_solver.h"
  18714. //#include "b2_island.h"
  18715.  
  18716. //#include "box2d/b2_body.h"
  18717. //#include "box2d/b2_broad_phase.h"
  18718. //#include "box2d/b2_chain_shape.h"
  18719. //#include "box2d/b2_circle_shape.h"
  18720. //#include "box2d/b2_collision.h"
  18721. //#include "box2d/b2_contact.h"
  18722. //#include "box2d/b2_draw.h"
  18723. //#include "box2d/b2_edge_shape.h"
  18724. //#include "box2d/b2_fixture.h"
  18725. //#include "box2d/b2_polygon_shape.h"
  18726. //#include "box2d/b2_pulley_joint.h"
  18727. //#include "box2d/b2_time_of_impact.h"
  18728. //#include "box2d/b2_timer.h"
  18729. //#include "box2d/b2_world.h"
  18730.  
  18731. #include <new>
  18732.  
  18733. b2World::b2World(const b2Vec2& gravity) {
  18734.     m_destructionListener = nullptr;
  18735.     m_debugDraw = nullptr;
  18736.  
  18737.     m_bodyList = nullptr;
  18738.     m_jointList = nullptr;
  18739.  
  18740.     m_bodyCount = 0;
  18741.     m_jointCount = 0;
  18742.  
  18743.     m_warmStarting = true;
  18744.     m_continuousPhysics = true;
  18745.     m_subStepping = false;
  18746.  
  18747.     m_stepComplete = true;
  18748.  
  18749.     m_allowSleep = true;
  18750.     m_gravity = gravity;
  18751.  
  18752.     m_newContacts = false;
  18753.     m_locked = false;
  18754.     m_clearForces = true;
  18755.  
  18756.     m_inv_dt0 = 0.0f;
  18757.  
  18758.     m_contactManager.m_allocator = &m_blockAllocator;
  18759.  
  18760.     memset(&m_profile, 0, sizeof(b2Profile));
  18761. }
  18762.  
  18763. b2World::~b2World() {
  18764.     // Some shapes allocate using b2Alloc.
  18765.     b2Body* b = m_bodyList;
  18766.     while (b) {
  18767.         b2Body* bNext = b->m_next;
  18768.  
  18769.         b2Fixture* f = b->m_fixtureList;
  18770.         while (f) {
  18771.             b2Fixture* fNext = f->m_next;
  18772.             f->m_proxyCount = 0;
  18773.             f->Destroy(&m_blockAllocator);
  18774.             f = fNext;
  18775.         }
  18776.  
  18777.         b = bNext;
  18778.     }
  18779. }
  18780.  
  18781. void b2World::SetDestructionListener(b2DestructionListener* listener) {
  18782.     m_destructionListener = listener;
  18783. }
  18784.  
  18785. void b2World::SetContactFilter(b2ContactFilter* filter) {
  18786.     m_contactManager.m_contactFilter = filter;
  18787. }
  18788.  
  18789. void b2World::SetContactListener(b2ContactListener* listener) {
  18790.     m_contactManager.m_contactListener = listener;
  18791. }
  18792.  
  18793. void b2World::SetDebugDraw(b2Draw* debugDraw) {
  18794.     m_debugDraw = debugDraw;
  18795. }
  18796.  
  18797. b2Body* b2World::CreateBody(const b2BodyDef* def) {
  18798.     b2Assert(IsLocked() == false);
  18799.     if (IsLocked()) {
  18800.         return nullptr;
  18801.     }
  18802.  
  18803.     void* mem = m_blockAllocator.Allocate(sizeof(b2Body));
  18804.     b2Body* b = new (mem) b2Body(def, this);
  18805.  
  18806.     // Add to world doubly linked list.
  18807.     b->m_prev = nullptr;
  18808.     b->m_next = m_bodyList;
  18809.     if (m_bodyList) {
  18810.         m_bodyList->m_prev = b;
  18811.     }
  18812.     m_bodyList = b;
  18813.     ++m_bodyCount;
  18814.  
  18815.     return b;
  18816. }
  18817.  
  18818. void b2World::DestroyBody(b2Body* b) {
  18819.     b2Assert(m_bodyCount > 0);
  18820.     b2Assert(IsLocked() == false);
  18821.     if (IsLocked()) {
  18822.         return;
  18823.     }
  18824.  
  18825.     // Delete the attached joints.
  18826.     b2JointEdge* je = b->m_jointList;
  18827.     while (je) {
  18828.         b2JointEdge* je0 = je;
  18829.         je = je->next;
  18830.  
  18831.         if (m_destructionListener) {
  18832.             m_destructionListener->SayGoodbye(je0->joint);
  18833.         }
  18834.  
  18835.         DestroyJoint(je0->joint);
  18836.  
  18837.         b->m_jointList = je;
  18838.     }
  18839.     b->m_jointList = nullptr;
  18840.  
  18841.     // Delete the attached contacts.
  18842.     b2ContactEdge* ce = b->m_contactList;
  18843.     while (ce) {
  18844.         b2ContactEdge* ce0 = ce;
  18845.         ce = ce->next;
  18846.         m_contactManager.Destroy(ce0->contact);
  18847.     }
  18848.     b->m_contactList = nullptr;
  18849.  
  18850.     // Delete the attached fixtures. This destroys broad-phase proxies.
  18851.     b2Fixture* f = b->m_fixtureList;
  18852.     while (f) {
  18853.         b2Fixture* f0 = f;
  18854.         f = f->m_next;
  18855.  
  18856.         if (m_destructionListener) {
  18857.             m_destructionListener->SayGoodbye(f0);
  18858.         }
  18859.  
  18860.         f0->DestroyProxies(&m_contactManager.m_broadPhase);
  18861.         f0->Destroy(&m_blockAllocator);
  18862.         f0->~b2Fixture();
  18863.         m_blockAllocator.Free(f0, sizeof(b2Fixture));
  18864.  
  18865.         b->m_fixtureList = f;
  18866.         b->m_fixtureCount -= 1;
  18867.     }
  18868.     b->m_fixtureList = nullptr;
  18869.     b->m_fixtureCount = 0;
  18870.  
  18871.     // Remove world body list.
  18872.     if (b->m_prev) {
  18873.         b->m_prev->m_next = b->m_next;
  18874.     }
  18875.  
  18876.     if (b->m_next) {
  18877.         b->m_next->m_prev = b->m_prev;
  18878.     }
  18879.  
  18880.     if (b == m_bodyList) {
  18881.         m_bodyList = b->m_next;
  18882.     }
  18883.  
  18884.     --m_bodyCount;
  18885.     b->~b2Body();
  18886.     m_blockAllocator.Free(b, sizeof(b2Body));
  18887. }
  18888.  
  18889. b2Joint* b2World::CreateJoint(const b2JointDef* def) {
  18890.     b2Assert(IsLocked() == false);
  18891.     if (IsLocked()) {
  18892.         return nullptr;
  18893.     }
  18894.  
  18895.     b2Joint* j = b2Joint::Create(def, &m_blockAllocator);
  18896.  
  18897.     // Connect to the world list.
  18898.     j->m_prev = nullptr;
  18899.     j->m_next = m_jointList;
  18900.     if (m_jointList) {
  18901.         m_jointList->m_prev = j;
  18902.     }
  18903.     m_jointList = j;
  18904.     ++m_jointCount;
  18905.  
  18906.     // Connect to the bodies' doubly linked lists.
  18907.     j->m_edgeA.joint = j;
  18908.     j->m_edgeA.other = j->m_bodyB;
  18909.     j->m_edgeA.prev = nullptr;
  18910.     j->m_edgeA.next = j->m_bodyA->m_jointList;
  18911.     if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA;
  18912.     j->m_bodyA->m_jointList = &j->m_edgeA;
  18913.  
  18914.     j->m_edgeB.joint = j;
  18915.     j->m_edgeB.other = j->m_bodyA;
  18916.     j->m_edgeB.prev = nullptr;
  18917.     j->m_edgeB.next = j->m_bodyB->m_jointList;
  18918.     if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB;
  18919.     j->m_bodyB->m_jointList = &j->m_edgeB;
  18920.  
  18921.     b2Body* bodyA = def->bodyA;
  18922.     b2Body* bodyB = def->bodyB;
  18923.  
  18924.     // If the joint prevents collisions, then flag any contacts for filtering.
  18925.     if (def->collideConnected == false) {
  18926.         b2ContactEdge* edge = bodyB->GetContactList();
  18927.         while (edge) {
  18928.             if (edge->other == bodyA) {
  18929.                 // Flag the contact for filtering at the next time step (where either
  18930.                 // body is awake).
  18931.                 edge->contact->FlagForFiltering();
  18932.             }
  18933.  
  18934.             edge = edge->next;
  18935.         }
  18936.     }
  18937.  
  18938.     // Note: creating a joint doesn't wake the bodies.
  18939.  
  18940.     return j;
  18941. }
  18942.  
  18943. void b2World::DestroyJoint(b2Joint* j) {
  18944.     b2Assert(IsLocked() == false);
  18945.     if (IsLocked()) {
  18946.         return;
  18947.     }
  18948.  
  18949.     bool collideConnected = j->m_collideConnected;
  18950.  
  18951.     // Remove from the doubly linked list.
  18952.     if (j->m_prev) {
  18953.         j->m_prev->m_next = j->m_next;
  18954.     }
  18955.  
  18956.     if (j->m_next) {
  18957.         j->m_next->m_prev = j->m_prev;
  18958.     }
  18959.  
  18960.     if (j == m_jointList) {
  18961.         m_jointList = j->m_next;
  18962.     }
  18963.  
  18964.     // Disconnect from island graph.
  18965.     b2Body* bodyA = j->m_bodyA;
  18966.     b2Body* bodyB = j->m_bodyB;
  18967.  
  18968.     // Wake up connected bodies.
  18969.     bodyA->SetAwake(true);
  18970.     bodyB->SetAwake(true);
  18971.  
  18972.     // Remove from body 1.
  18973.     if (j->m_edgeA.prev) {
  18974.         j->m_edgeA.prev->next = j->m_edgeA.next;
  18975.     }
  18976.  
  18977.     if (j->m_edgeA.next) {
  18978.         j->m_edgeA.next->prev = j->m_edgeA.prev;
  18979.     }
  18980.  
  18981.     if (&j->m_edgeA == bodyA->m_jointList) {
  18982.         bodyA->m_jointList = j->m_edgeA.next;
  18983.     }
  18984.  
  18985.     j->m_edgeA.prev = nullptr;
  18986.     j->m_edgeA.next = nullptr;
  18987.  
  18988.     // Remove from body 2
  18989.     if (j->m_edgeB.prev) {
  18990.         j->m_edgeB.prev->next = j->m_edgeB.next;
  18991.     }
  18992.  
  18993.     if (j->m_edgeB.next) {
  18994.         j->m_edgeB.next->prev = j->m_edgeB.prev;
  18995.     }
  18996.  
  18997.     if (&j->m_edgeB == bodyB->m_jointList) {
  18998.         bodyB->m_jointList = j->m_edgeB.next;
  18999.     }
  19000.  
  19001.     j->m_edgeB.prev = nullptr;
  19002.     j->m_edgeB.next = nullptr;
  19003.  
  19004.     b2Joint::Destroy(j, &m_blockAllocator);
  19005.  
  19006.     b2Assert(m_jointCount > 0);
  19007.     --m_jointCount;
  19008.  
  19009.     // If the joint prevents collisions, then flag any contacts for filtering.
  19010.     if (collideConnected == false) {
  19011.         b2ContactEdge* edge = bodyB->GetContactList();
  19012.         while (edge) {
  19013.             if (edge->other == bodyA) {
  19014.                 // Flag the contact for filtering at the next time step (where either
  19015.                 // body is awake).
  19016.                 edge->contact->FlagForFiltering();
  19017.             }
  19018.  
  19019.             edge = edge->next;
  19020.         }
  19021.     }
  19022. }
  19023.  
  19024. //
  19025. void b2World::SetAllowSleeping(bool flag) {
  19026.     if (flag == m_allowSleep) {
  19027.         return;
  19028.     }
  19029.  
  19030.     m_allowSleep = flag;
  19031.     if (m_allowSleep == false) {
  19032.         for (b2Body* b = m_bodyList; b; b = b->m_next) {
  19033.             b->SetAwake(true);
  19034.         }
  19035.     }
  19036. }
  19037.  
  19038. // Find islands, integrate and solve constraints, solve position constraints
  19039. void b2World::Solve(const b2TimeStep& step) {
  19040.     m_profile.solveInit = 0.0f;
  19041.     m_profile.solveVelocity = 0.0f;
  19042.     m_profile.solvePosition = 0.0f;
  19043.  
  19044.     // Size the island for the worst case.
  19045.     b2Island island(m_bodyCount,
  19046.         m_contactManager.m_contactCount,
  19047.         m_jointCount,
  19048.         &m_stackAllocator,
  19049.         m_contactManager.m_contactListener);
  19050.  
  19051.     // Clear all the island flags.
  19052.     for (b2Body* b = m_bodyList; b; b = b->m_next) {
  19053.         b->m_flags &= ~b2Body::e_islandFlag;
  19054.     }
  19055.     for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) {
  19056.         c->m_flags &= ~b2Contact::e_islandFlag;
  19057.     }
  19058.     for (b2Joint* j = m_jointList; j; j = j->m_next) {
  19059.         j->m_islandFlag = false;
  19060.     }
  19061.  
  19062.     // Build and simulate all awake islands.
  19063.     int32 stackSize = m_bodyCount;
  19064.     b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*));
  19065.     for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) {
  19066.         if (seed->m_flags & b2Body::e_islandFlag) {
  19067.             continue;
  19068.         }
  19069.  
  19070.         if (seed->IsAwake() == false || seed->IsEnabled() == false) {
  19071.             continue;
  19072.         }
  19073.  
  19074.         // The seed can be dynamic or kinematic.
  19075.         if (seed->GetType() == b2_staticBody) {
  19076.             continue;
  19077.         }
  19078.  
  19079.         // Reset island and stack.
  19080.         island.Clear();
  19081.         int32 stackCount = 0;
  19082.         stack[stackCount++] = seed;
  19083.         seed->m_flags |= b2Body::e_islandFlag;
  19084.  
  19085.         // Perform a depth first search (DFS) on the constraint graph.
  19086.         while (stackCount > 0) {
  19087.             // Grab the next body off the stack and add it to the island.
  19088.             b2Body* b = stack[--stackCount];
  19089.             b2Assert(b->IsEnabled() == true);
  19090.             island.Add(b);
  19091.  
  19092.             // To keep islands as small as possible, we don't
  19093.             // propagate islands across static bodies.
  19094.             if (b->GetType() == b2_staticBody) {
  19095.                 continue;
  19096.             }
  19097.  
  19098.             // Make sure the body is awake (without resetting sleep timer).
  19099.             b->m_flags |= b2Body::e_awakeFlag;
  19100.  
  19101.             // Search all contacts connected to this body.
  19102.             for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) {
  19103.                 b2Contact* contact = ce->contact;
  19104.  
  19105.                 // Has this contact already been added to an island?
  19106.                 if (contact->m_flags & b2Contact::e_islandFlag) {
  19107.                     continue;
  19108.                 }
  19109.  
  19110.                 // Is this contact solid and touching?
  19111.                 if (contact->IsEnabled() == false ||
  19112.                     contact->IsTouching() == false) {
  19113.                     continue;
  19114.                 }
  19115.  
  19116.                 // Skip sensors.
  19117.                 bool sensorA = contact->m_fixtureA->m_isSensor;
  19118.                 bool sensorB = contact->m_fixtureB->m_isSensor;
  19119.                 if (sensorA || sensorB) {
  19120.                     continue;
  19121.                 }
  19122.  
  19123.                 island.Add(contact);
  19124.                 contact->m_flags |= b2Contact::e_islandFlag;
  19125.  
  19126.                 b2Body* other = ce->other;
  19127.  
  19128.                 // Was the other body already added to this island?
  19129.                 if (other->m_flags & b2Body::e_islandFlag) {
  19130.                     continue;
  19131.                 }
  19132.  
  19133.                 b2Assert(stackCount < stackSize);
  19134.                 stack[stackCount++] = other;
  19135.                 other->m_flags |= b2Body::e_islandFlag;
  19136.             }
  19137.  
  19138.             // Search all joints connect to this body.
  19139.             for (b2JointEdge* je = b->m_jointList; je; je = je->next) {
  19140.                 if (je->joint->m_islandFlag == true) {
  19141.                     continue;
  19142.                 }
  19143.  
  19144.                 b2Body* other = je->other;
  19145.  
  19146.                 // Don't simulate joints connected to diabled bodies.
  19147.                 if (other->IsEnabled() == false) {
  19148.                     continue;
  19149.                 }
  19150.  
  19151.                 island.Add(je->joint);
  19152.                 je->joint->m_islandFlag = true;
  19153.  
  19154.                 if (other->m_flags & b2Body::e_islandFlag) {
  19155.                     continue;
  19156.                 }
  19157.  
  19158.                 b2Assert(stackCount < stackSize);
  19159.                 stack[stackCount++] = other;
  19160.                 other->m_flags |= b2Body::e_islandFlag;
  19161.             }
  19162.         }
  19163.  
  19164.         b2Profile profile;
  19165.         island.Solve(&profile, step, m_gravity, m_allowSleep);
  19166.         m_profile.solveInit += profile.solveInit;
  19167.         m_profile.solveVelocity += profile.solveVelocity;
  19168.         m_profile.solvePosition += profile.solvePosition;
  19169.  
  19170.         // Post solve cleanup.
  19171.         for (int32 i = 0; i < island.m_bodyCount; ++i) {
  19172.             // Allow static bodies to participate in other islands.
  19173.             b2Body* b = island.m_bodies[i];
  19174.             if (b->GetType() == b2_staticBody) {
  19175.                 b->m_flags &= ~b2Body::e_islandFlag;
  19176.             }
  19177.         }
  19178.     }
  19179.  
  19180.     m_stackAllocator.Free(stack);
  19181.  
  19182.     {
  19183.         b2Timer timer;
  19184.         // Synchronize fixtures, check for out of range bodies.
  19185.         for (b2Body* b = m_bodyList; b; b = b->GetNext()) {
  19186.             // If a body was not in an island then it did not move.
  19187.             if ((b->m_flags & b2Body::e_islandFlag) == 0) {
  19188.                 continue;
  19189.             }
  19190.  
  19191.             if (b->GetType() == b2_staticBody) {
  19192.                 continue;
  19193.             }
  19194.  
  19195.             // Update fixtures (for broad-phase).
  19196.             b->SynchronizeFixtures();
  19197.         }
  19198.  
  19199.         // Look for new contacts.
  19200.         m_contactManager.FindNewContacts();
  19201.         m_profile.broadphase = timer.GetMilliseconds();
  19202.     }
  19203. }
  19204.  
  19205. // Find TOI contacts and solve them.
  19206. void b2World::SolveTOI(const b2TimeStep& step) {
  19207.     b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener);
  19208.  
  19209.     if (m_stepComplete) {
  19210.         for (b2Body* b = m_bodyList; b; b = b->m_next) {
  19211.             b->m_flags &= ~b2Body::e_islandFlag;
  19212.             b->m_sweep.alpha0 = 0.0f;
  19213.         }
  19214.  
  19215.         for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) {
  19216.             // Invalidate TOI
  19217.             c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
  19218.             c->m_toiCount = 0;
  19219.             c->m_toi = 1.0f;
  19220.         }
  19221.     }
  19222.  
  19223.     // Find TOI events and solve them.
  19224.     for (;;) {
  19225.         // Find the first TOI.
  19226.         b2Contact* minContact = nullptr;
  19227.         float minAlpha = 1.0f;
  19228.  
  19229.         for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) {
  19230.             // Is this contact disabled?
  19231.             if (c->IsEnabled() == false) {
  19232.                 continue;
  19233.             }
  19234.  
  19235.             // Prevent excessive sub-stepping.
  19236.             if (c->m_toiCount > b2_maxSubSteps) {
  19237.                 continue;
  19238.             }
  19239.  
  19240.             float alpha = 1.0f;
  19241.             if (c->m_flags & b2Contact::e_toiFlag) {
  19242.                 // This contact has a valid cached TOI.
  19243.                 alpha = c->m_toi;
  19244.             } else {
  19245.                 b2Fixture* fA = c->GetFixtureA();
  19246.                 b2Fixture* fB = c->GetFixtureB();
  19247.  
  19248.                 // Is there a sensor?
  19249.                 if (fA->IsSensor() || fB->IsSensor()) {
  19250.                     continue;
  19251.                 }
  19252.  
  19253.                 b2Body* bA = fA->GetBody();
  19254.                 b2Body* bB = fB->GetBody();
  19255.  
  19256.                 b2BodyType typeA = bA->m_type;
  19257.                 b2BodyType typeB = bB->m_type;
  19258.                 b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody);
  19259.  
  19260.                 bool activeA = bA->IsAwake() && typeA != b2_staticBody;
  19261.                 bool activeB = bB->IsAwake() && typeB != b2_staticBody;
  19262.  
  19263.                 // Is at least one body active (awake and dynamic or kinematic)?
  19264.                 if (activeA == false && activeB == false) {
  19265.                     continue;
  19266.                 }
  19267.  
  19268.                 bool collideA = bA->IsBullet() || typeA != b2_dynamicBody;
  19269.                 bool collideB = bB->IsBullet() || typeB != b2_dynamicBody;
  19270.  
  19271.                 // Are these two non-bullet dynamic bodies?
  19272.                 if (collideA == false && collideB == false) {
  19273.                     continue;
  19274.                 }
  19275.  
  19276.                 // Compute the TOI for this contact.
  19277.                 // Put the sweeps onto the same time interval.
  19278.                 float alpha0 = bA->m_sweep.alpha0;
  19279.  
  19280.                 if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) {
  19281.                     alpha0 = bB->m_sweep.alpha0;
  19282.                     bA->m_sweep.Advance(alpha0);
  19283.                 } else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) {
  19284.                     alpha0 = bA->m_sweep.alpha0;
  19285.                     bB->m_sweep.Advance(alpha0);
  19286.                 }
  19287.  
  19288.                 b2Assert(alpha0 < 1.0f);
  19289.  
  19290.                 int32 indexA = c->GetChildIndexA();
  19291.                 int32 indexB = c->GetChildIndexB();
  19292.  
  19293.                 // Compute the time of impact in interval [0, minTOI]
  19294.                 b2TOIInput input;
  19295.                 input.proxyA.Set(fA->GetShape(), indexA);
  19296.                 input.proxyB.Set(fB->GetShape(), indexB);
  19297.                 input.sweepA = bA->m_sweep;
  19298.                 input.sweepB = bB->m_sweep;
  19299.                 input.tMax = 1.0f;
  19300.  
  19301.                 b2TOIOutput output;
  19302.                 b2TimeOfImpact(&output, &input);
  19303.  
  19304.                 // Beta is the fraction of the remaining portion of the .
  19305.                 float beta = output.t;
  19306.                 if (output.state == b2TOIOutput::e_touching) {
  19307.                     alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f);
  19308.                 } else {
  19309.                     alpha = 1.0f;
  19310.                 }
  19311.  
  19312.                 c->m_toi = alpha;
  19313.                 c->m_flags |= b2Contact::e_toiFlag;
  19314.             }
  19315.  
  19316.             if (alpha < minAlpha) {
  19317.                 // This is the minimum TOI found so far.
  19318.                 minContact = c;
  19319.                 minAlpha = alpha;
  19320.             }
  19321.         }
  19322.  
  19323.         if (minContact == nullptr || 1.0f - 10.0f * b2_epsilon < minAlpha) {
  19324.             // No more TOI events. Done!
  19325.             m_stepComplete = true;
  19326.             break;
  19327.         }
  19328.  
  19329.         // Advance the bodies to the TOI.
  19330.         b2Fixture* fA = minContact->GetFixtureA();
  19331.         b2Fixture* fB = minContact->GetFixtureB();
  19332.         b2Body* bA = fA->GetBody();
  19333.         b2Body* bB = fB->GetBody();
  19334.  
  19335.         b2Sweep backup1 = bA->m_sweep;
  19336.         b2Sweep backup2 = bB->m_sweep;
  19337.  
  19338.         bA->Advance(minAlpha);
  19339.         bB->Advance(minAlpha);
  19340.  
  19341.         // The TOI contact likely has some new contact points.
  19342.         minContact->Update(m_contactManager.m_contactListener);
  19343.         minContact->m_flags &= ~b2Contact::e_toiFlag;
  19344.         ++minContact->m_toiCount;
  19345.  
  19346.         // Is the contact solid?
  19347.         if (minContact->IsEnabled() == false || minContact->IsTouching() == false) {
  19348.             // Restore the sweeps.
  19349.             minContact->SetEnabled(false);
  19350.             bA->m_sweep = backup1;
  19351.             bB->m_sweep = backup2;
  19352.             bA->SynchronizeTransform();
  19353.             bB->SynchronizeTransform();
  19354.             continue;
  19355.         }
  19356.  
  19357.         bA->SetAwake(true);
  19358.         bB->SetAwake(true);
  19359.  
  19360.         // Build the island
  19361.         island.Clear();
  19362.         island.Add(bA);
  19363.         island.Add(bB);
  19364.         island.Add(minContact);
  19365.  
  19366.         bA->m_flags |= b2Body::e_islandFlag;
  19367.         bB->m_flags |= b2Body::e_islandFlag;
  19368.         minContact->m_flags |= b2Contact::e_islandFlag;
  19369.  
  19370.         // Get contacts on bodyA and bodyB.
  19371.         b2Body* bodies[2] = { bA, bB };
  19372.         for (int32 i = 0; i < 2; ++i) {
  19373.             b2Body* body = bodies[i];
  19374.             if (body->m_type == b2_dynamicBody) {
  19375.                 for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) {
  19376.                     if (island.m_bodyCount == island.m_bodyCapacity) {
  19377.                         break;
  19378.                     }
  19379.  
  19380.                     if (island.m_contactCount == island.m_contactCapacity) {
  19381.                         break;
  19382.                     }
  19383.  
  19384.                     b2Contact* contact = ce->contact;
  19385.  
  19386.                     // Has this contact already been added to the island?
  19387.                     if (contact->m_flags & b2Contact::e_islandFlag) {
  19388.                         continue;
  19389.                     }
  19390.  
  19391.                     // Only add static, kinematic, or bullet bodies.
  19392.                     b2Body* other = ce->other;
  19393.                     if (other->m_type == b2_dynamicBody &&
  19394.                         body->IsBullet() == false && other->IsBullet() == false) {
  19395.                         continue;
  19396.                     }
  19397.  
  19398.                     // Skip sensors.
  19399.                     bool sensorA = contact->m_fixtureA->m_isSensor;
  19400.                     bool sensorB = contact->m_fixtureB->m_isSensor;
  19401.                     if (sensorA || sensorB) {
  19402.                         continue;
  19403.                     }
  19404.  
  19405.                     // Tentatively advance the body to the TOI.
  19406.                     b2Sweep backup = other->m_sweep;
  19407.                     if ((other->m_flags & b2Body::e_islandFlag) == 0) {
  19408.                         other->Advance(minAlpha);
  19409.                     }
  19410.  
  19411.                     // Update the contact points
  19412.                     contact->Update(m_contactManager.m_contactListener);
  19413.  
  19414.                     // Was the contact disabled by the user?
  19415.                     if (contact->IsEnabled() == false) {
  19416.                         other->m_sweep = backup;
  19417.                         other->SynchronizeTransform();
  19418.                         continue;
  19419.                     }
  19420.  
  19421.                     // Are there contact points?
  19422.                     if (contact->IsTouching() == false) {
  19423.                         other->m_sweep = backup;
  19424.                         other->SynchronizeTransform();
  19425.                         continue;
  19426.                     }
  19427.  
  19428.                     // Add the contact to the island
  19429.                     contact->m_flags |= b2Contact::e_islandFlag;
  19430.                     island.Add(contact);
  19431.  
  19432.                     // Has the other body already been added to the island?
  19433.                     if (other->m_flags & b2Body::e_islandFlag) {
  19434.                         continue;
  19435.                     }
  19436.  
  19437.                     // Add the other body to the island.
  19438.                     other->m_flags |= b2Body::e_islandFlag;
  19439.  
  19440.                     if (other->m_type != b2_staticBody) {
  19441.                         other->SetAwake(true);
  19442.                     }
  19443.  
  19444.                     island.Add(other);
  19445.                 }
  19446.             }
  19447.         }
  19448.  
  19449.         b2TimeStep subStep;
  19450.         subStep.dt = (1.0f - minAlpha) * step.dt;
  19451.         subStep.inv_dt = 1.0f / subStep.dt;
  19452.         subStep.dtRatio = 1.0f;
  19453.         subStep.positionIterations = 20;
  19454.         subStep.velocityIterations = step.velocityIterations;
  19455.         subStep.warmStarting = false;
  19456.         island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex);
  19457.  
  19458.         // Reset island flags and synchronize broad-phase proxies.
  19459.         for (int32 i = 0; i < island.m_bodyCount; ++i) {
  19460.             b2Body* body = island.m_bodies[i];
  19461.             body->m_flags &= ~b2Body::e_islandFlag;
  19462.  
  19463.             if (body->m_type != b2_dynamicBody) {
  19464.                 continue;
  19465.             }
  19466.  
  19467.             body->SynchronizeFixtures();
  19468.  
  19469.             // Invalidate all contact TOIs on this displaced body.
  19470.             for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) {
  19471.                 ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
  19472.             }
  19473.         }
  19474.  
  19475.         // Commit fixture proxy movements to the broad-phase so that new contacts are created.
  19476.         // Also, some contacts can be destroyed.
  19477.         m_contactManager.FindNewContacts();
  19478.  
  19479.         if (m_subStepping) {
  19480.             m_stepComplete = false;
  19481.             break;
  19482.         }
  19483.     }
  19484. }
  19485.  
  19486. void b2World::Step(float dt, int32 velocityIterations, int32 positionIterations) {
  19487.     b2Timer stepTimer;
  19488.  
  19489.     // If new fixtures were added, we need to find the new contacts.
  19490.     if (m_newContacts) {
  19491.         m_contactManager.FindNewContacts();
  19492.         m_newContacts = false;
  19493.     }
  19494.  
  19495.     m_locked = true;
  19496.  
  19497.     b2TimeStep step;
  19498.     step.dt = dt;
  19499.     step.velocityIterations = velocityIterations;
  19500.     step.positionIterations = positionIterations;
  19501.     if (dt > 0.0f) {
  19502.         step.inv_dt = 1.0f / dt;
  19503.     } else {
  19504.         step.inv_dt = 0.0f;
  19505.     }
  19506.  
  19507.     step.dtRatio = m_inv_dt0 * dt;
  19508.  
  19509.     step.warmStarting = m_warmStarting;
  19510.  
  19511.     // Update contacts. This is where some contacts are destroyed.
  19512.     {
  19513.         b2Timer timer;
  19514.         m_contactManager.Collide();
  19515.         m_profile.collide = timer.GetMilliseconds();
  19516.     }
  19517.  
  19518.     // Integrate velocities, solve velocity constraints, and integrate positions.
  19519.     if (m_stepComplete && step.dt > 0.0f) {
  19520.         b2Timer timer;
  19521.         Solve(step);
  19522.         m_profile.solve = timer.GetMilliseconds();
  19523.     }
  19524.  
  19525.     // Handle TOI events.
  19526.     if (m_continuousPhysics && step.dt > 0.0f) {
  19527.         b2Timer timer;
  19528.         SolveTOI(step);
  19529.         m_profile.solveTOI = timer.GetMilliseconds();
  19530.     }
  19531.  
  19532.     if (step.dt > 0.0f) {
  19533.         m_inv_dt0 = step.inv_dt;
  19534.     }
  19535.  
  19536.     if (m_clearForces) {
  19537.         ClearForces();
  19538.     }
  19539.  
  19540.     m_locked = false;
  19541.  
  19542.     m_profile.step = stepTimer.GetMilliseconds();
  19543. }
  19544.  
  19545. void b2World::ClearForces() {
  19546.     for (b2Body* body = m_bodyList; body; body = body->GetNext()) {
  19547.         body->m_force.SetZero();
  19548.         body->m_torque = 0.0f;
  19549.     }
  19550. }
  19551.  
  19552. struct b2WorldQueryWrapper {
  19553.     bool QueryCallback(int32 proxyId) {
  19554.         b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId);
  19555.         return callback->ReportFixture(proxy->fixture);
  19556.     }
  19557.  
  19558.     const b2BroadPhase* broadPhase;
  19559.     b2QueryCallback* callback;
  19560. };
  19561.  
  19562. void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const {
  19563.     b2WorldQueryWrapper wrapper;
  19564.     wrapper.broadPhase = &m_contactManager.m_broadPhase;
  19565.     wrapper.callback = callback;
  19566.     m_contactManager.m_broadPhase.Query(&wrapper, aabb);
  19567. }
  19568.  
  19569. struct b2WorldRayCastWrapper {
  19570.     float RayCastCallback(const b2RayCastInput& input, int32 proxyId) {
  19571.         void* userData = broadPhase->GetUserData(proxyId);
  19572.         b2FixtureProxy* proxy = (b2FixtureProxy*)userData;
  19573.         b2Fixture* fixture = proxy->fixture;
  19574.         int32 index = proxy->childIndex;
  19575.         b2RayCastOutput output;
  19576.         bool hit = fixture->RayCast(&output, input, index);
  19577.  
  19578.         if (hit) {
  19579.             float fraction = output.fraction;
  19580.             b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2;
  19581.             return callback->ReportFixture(fixture, point, output.normal, fraction);
  19582.         }
  19583.  
  19584.         return input.maxFraction;
  19585.     }
  19586.  
  19587.     const b2BroadPhase* broadPhase;
  19588.     b2RayCastCallback* callback;
  19589. };
  19590.  
  19591. void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const {
  19592.     b2WorldRayCastWrapper wrapper;
  19593.     wrapper.broadPhase = &m_contactManager.m_broadPhase;
  19594.     wrapper.callback = callback;
  19595.     b2RayCastInput input;
  19596.     input.maxFraction = 1.0f;
  19597.     input.p1 = point1;
  19598.     input.p2 = point2;
  19599.     m_contactManager.m_broadPhase.RayCast(&wrapper, input);
  19600. }
  19601.  
  19602. void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) {
  19603.     switch (fixture->GetType()) {
  19604.     case b2Shape::e_circle:
  19605.     {
  19606.         b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
  19607.  
  19608.         b2Vec2 center = b2Mul(xf, circle->m_p);
  19609.         float radius = circle->m_radius;
  19610.         b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f));
  19611.  
  19612.         m_debugDraw->DrawSolidCircle(center, radius, axis, color);
  19613.     }
  19614.     break;
  19615.  
  19616.     case b2Shape::e_edge:
  19617.     {
  19618.         b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
  19619.         b2Vec2 v1 = b2Mul(xf, edge->m_vertex1);
  19620.         b2Vec2 v2 = b2Mul(xf, edge->m_vertex2);
  19621.         m_debugDraw->DrawSegment(v1, v2, color);
  19622.  
  19623.         if (edge->m_oneSided == false) {
  19624.             m_debugDraw->DrawPoint(v1, 4.0f, color);
  19625.             m_debugDraw->DrawPoint(v2, 4.0f, color);
  19626.         }
  19627.     }
  19628.     break;
  19629.  
  19630.     case b2Shape::e_chain:
  19631.     {
  19632.         b2ChainShape* chain = (b2ChainShape*)fixture->GetShape();
  19633.         int32 count = chain->m_count;
  19634.         const b2Vec2* vertices = chain->m_vertices;
  19635.  
  19636.         b2Vec2 v1 = b2Mul(xf, vertices[0]);
  19637.         for (int32 i = 1; i < count; ++i) {
  19638.             b2Vec2 v2 = b2Mul(xf, vertices[i]);
  19639.             m_debugDraw->DrawSegment(v1, v2, color);
  19640.             v1 = v2;
  19641.         }
  19642.     }
  19643.     break;
  19644.  
  19645.     case b2Shape::e_polygon:
  19646.     {
  19647.         b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
  19648.         int32 vertexCount = poly->m_count;
  19649.         b2Assert(vertexCount <= b2_maxPolygonVertices);
  19650.         b2Vec2 vertices[b2_maxPolygonVertices];
  19651.  
  19652.         for (int32 i = 0; i < vertexCount; ++i) {
  19653.             vertices[i] = b2Mul(xf, poly->m_vertices[i]);
  19654.         }
  19655.  
  19656.         m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color);
  19657.     }
  19658.     break;
  19659.  
  19660.     default:
  19661.         break;
  19662.     }
  19663. }
  19664.  
  19665. void b2World::DebugDraw() {
  19666.     if (m_debugDraw == nullptr) {
  19667.         return;
  19668.     }
  19669.  
  19670.     uint32 flags = m_debugDraw->GetFlags();
  19671.  
  19672.     if (flags & b2Draw::e_shapeBit) {
  19673.         for (b2Body* b = m_bodyList; b; b = b->GetNext()) {
  19674.             const b2Transform& xf = b->GetTransform();
  19675.             for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) {
  19676.                 if (b->GetType() == b2_dynamicBody && b->m_mass == 0.0f) {
  19677.                     // Bad body
  19678.                     DrawShape(f, xf, b2Color(1.0f, 0.0f, 0.0f));
  19679.                 } else if (b->IsEnabled() == false) {
  19680.                     DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f));
  19681.                 } else if (b->GetType() == b2_staticBody) {
  19682.                     DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f));
  19683.                 } else if (b->GetType() == b2_kinematicBody) {
  19684.                     DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f));
  19685.                 } else if (b->IsAwake() == false) {
  19686.                     DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f));
  19687.                 } else {
  19688.                     DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f));
  19689.                 }
  19690.             }
  19691.         }
  19692.     }
  19693.  
  19694.     if (flags & b2Draw::e_jointBit) {
  19695.         for (b2Joint* j = m_jointList; j; j = j->GetNext()) {
  19696.             j->Draw(m_debugDraw);
  19697.         }
  19698.     }
  19699.  
  19700.     if (flags & b2Draw::e_pairBit) {
  19701.         b2Color color(0.3f, 0.9f, 0.9f);
  19702.         for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) {
  19703.             b2Fixture* fixtureA = c->GetFixtureA();
  19704.             b2Fixture* fixtureB = c->GetFixtureB();
  19705.             int32 indexA = c->GetChildIndexA();
  19706.             int32 indexB = c->GetChildIndexB();
  19707.             b2Vec2 cA = fixtureA->GetAABB(indexA).GetCenter();
  19708.             b2Vec2 cB = fixtureB->GetAABB(indexB).GetCenter();
  19709.  
  19710.             m_debugDraw->DrawSegment(cA, cB, color);
  19711.         }
  19712.     }
  19713.  
  19714.     if (flags & b2Draw::e_aabbBit) {
  19715.         b2Color color(0.9f, 0.3f, 0.9f);
  19716.         b2BroadPhase* bp = &m_contactManager.m_broadPhase;
  19717.  
  19718.         for (b2Body* b = m_bodyList; b; b = b->GetNext()) {
  19719.             if (b->IsEnabled() == false) {
  19720.                 continue;
  19721.             }
  19722.  
  19723.             for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) {
  19724.                 for (int32 i = 0; i < f->m_proxyCount; ++i) {
  19725.                     b2FixtureProxy* proxy = f->m_proxies + i;
  19726.                     b2AABB aabb = bp->GetFatAABB(proxy->proxyId);
  19727.                     b2Vec2 vs[4];
  19728.                     vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y);
  19729.                     vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y);
  19730.                     vs[2].Set(aabb.upperBound.x, aabb.upperBound.y);
  19731.                     vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y);
  19732.  
  19733.                     m_debugDraw->DrawPolygon(vs, 4, color);
  19734.                 }
  19735.             }
  19736.         }
  19737.     }
  19738.  
  19739.     if (flags & b2Draw::e_centerOfMassBit) {
  19740.         for (b2Body* b = m_bodyList; b; b = b->GetNext()) {
  19741.             b2Transform xf = b->GetTransform();
  19742.             xf.p = b->GetWorldCenter();
  19743.             m_debugDraw->DrawTransform(xf);
  19744.         }
  19745.     }
  19746. }
  19747.  
  19748. int32 b2World::GetProxyCount() const {
  19749.     return m_contactManager.m_broadPhase.GetProxyCount();
  19750. }
  19751.  
  19752. int32 b2World::GetTreeHeight() const {
  19753.     return m_contactManager.m_broadPhase.GetTreeHeight();
  19754. }
  19755.  
  19756. int32 b2World::GetTreeBalance() const {
  19757.     return m_contactManager.m_broadPhase.GetTreeBalance();
  19758. }
  19759.  
  19760. float b2World::GetTreeQuality() const {
  19761.     return m_contactManager.m_broadPhase.GetTreeQuality();
  19762. }
  19763.  
  19764. void b2World::ShiftOrigin(const b2Vec2& newOrigin) {
  19765.     b2Assert(m_locked == false);
  19766.     if (m_locked) {
  19767.         return;
  19768.     }
  19769.  
  19770.     for (b2Body* b = m_bodyList; b; b = b->m_next) {
  19771.         b->m_xf.p -= newOrigin;
  19772.         b->m_sweep.c0 -= newOrigin;
  19773.         b->m_sweep.c -= newOrigin;
  19774.     }
  19775.  
  19776.     for (b2Joint* j = m_jointList; j; j = j->m_next) {
  19777.         j->ShiftOrigin(newOrigin);
  19778.     }
  19779.  
  19780.     m_contactManager.m_broadPhase.ShiftOrigin(newOrigin);
  19781. }
  19782.  
  19783. void b2World::Dump() {
  19784.     if (m_locked) {
  19785.         return;
  19786.     }
  19787.  
  19788.     b2OpenDump("box2d_dump.inl");
  19789.  
  19790.     b2Dump("b2Vec2 g(%.9g, %.9g);\n", m_gravity.x, m_gravity.y);
  19791.     b2Dump("m_world->SetGravity(g);\n");
  19792.  
  19793.     b2Dump("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount);
  19794.     b2Dump("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount);
  19795.  
  19796.     int32 i = 0;
  19797.     for (b2Body* b = m_bodyList; b; b = b->m_next) {
  19798.         b->m_islandIndex = i;
  19799.         b->Dump();
  19800.         ++i;
  19801.     }
  19802.  
  19803.     i = 0;
  19804.     for (b2Joint* j = m_jointList; j; j = j->m_next) {
  19805.         j->m_index = i;
  19806.         ++i;
  19807.     }
  19808.  
  19809.     // First pass on joints, skip gear joints.
  19810.     for (b2Joint* j = m_jointList; j; j = j->m_next) {
  19811.         if (j->m_type == e_gearJoint) {
  19812.             continue;
  19813.         }
  19814.  
  19815.         b2Dump("{\n");
  19816.         j->Dump();
  19817.         b2Dump("}\n");
  19818.     }
  19819.  
  19820.     // Second pass on joints, only gear joints.
  19821.     for (b2Joint* j = m_jointList; j; j = j->m_next) {
  19822.         if (j->m_type != e_gearJoint) {
  19823.             continue;
  19824.         }
  19825.  
  19826.         b2Dump("{\n");
  19827.         j->Dump();
  19828.         b2Dump("}\n");
  19829.     }
  19830.  
  19831.     b2Dump("b2Free(joints);\n");
  19832.     b2Dump("b2Free(bodies);\n");
  19833.     b2Dump("joints = nullptr;\n");
  19834.     b2Dump("bodies = nullptr;\n");
  19835.  
  19836.     b2CloseDump();
  19837. }
  19838. // MIT License
  19839.  
  19840. // Copyright (c) 2019 Erin Catto
  19841.  
  19842. // Permission is hereby granted, free of charge, to any person obtaining a copy
  19843. // of this software and associated documentation files (the "Software"), to deal
  19844. // in the Software without restriction, including without limitation the rights
  19845. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19846. // copies of the Software, and to permit persons to whom the Software is
  19847. // furnished to do so, subject to the following conditions:
  19848.  
  19849. // The above copyright notice and this permission notice shall be included in all
  19850. // copies or substantial portions of the Software.
  19851.  
  19852. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19853. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19854. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19855. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19856. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19857. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19858. // SOFTWARE.
  19859.  
  19860. //#include "box2d/b2_fixture.h"
  19861. //#include "box2d/b2_world_callbacks.h"
  19862.  
  19863. // Return true if contact calculations should be performed between these two shapes.
  19864. // If you implement your own collision filter you may want to build from this implementation.
  19865. bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) {
  19866.     const b2Filter& filterA = fixtureA->GetFilterData();
  19867.     const b2Filter& filterB = fixtureB->GetFilterData();
  19868.  
  19869.     if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) {
  19870.         return filterA.groupIndex > 0;
  19871.     }
  19872.  
  19873.     bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0;
  19874.     return collide;
  19875. }
  19876. // MIT License
  19877.  
  19878. // Copyright (c) 2019 Erin Catto
  19879.  
  19880. // Permission is hereby granted, free of charge, to any person obtaining a copy
  19881. // of this software and associated documentation files (the "Software"), to deal
  19882. // in the Software without restriction, including without limitation the rights
  19883. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19884. // copies of the Software, and to permit persons to whom the Software is
  19885. // furnished to do so, subject to the following conditions:
  19886.  
  19887. // The above copyright notice and this permission notice shall be included in all
  19888. // copies or substantial portions of the Software.
  19889.  
  19890. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19891. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19892. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19893. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19894. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19895. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19896. // SOFTWARE.
  19897.  
  19898. //#include "box2d/b2_draw.h"
  19899. //#include "box2d/b2_rope.h"
  19900.  
  19901. #include <stdio.h>
  19902.  
  19903. struct b2RopeStretch {
  19904.     int32 i1, i2;
  19905.     float invMass1, invMass2;
  19906.     float L;
  19907.     float lambda;
  19908.     float spring;
  19909.     float damper;
  19910. };
  19911.  
  19912. struct b2RopeBend {
  19913.     int32 i1, i2, i3;
  19914.     float invMass1, invMass2, invMass3;
  19915.     float invEffectiveMass;
  19916.     float lambda;
  19917.     float L1, L2;
  19918.     float alpha1, alpha2;
  19919.     float spring;
  19920.     float damper;
  19921. };
  19922.  
  19923. b2Rope::b2Rope() {
  19924.     m_position.SetZero();
  19925.     m_count = 0;
  19926.     m_stretchCount = 0;
  19927.     m_bendCount = 0;
  19928.     m_stretchConstraints = nullptr;
  19929.     m_bendConstraints = nullptr;
  19930.     m_bindPositions = nullptr;
  19931.     m_ps = nullptr;
  19932.     m_p0s = nullptr;
  19933.     m_vs = nullptr;
  19934.     m_invMasses = nullptr;
  19935.     m_gravity.SetZero();
  19936. }
  19937.  
  19938. b2Rope::~b2Rope() {
  19939.     b2Free(m_stretchConstraints);
  19940.     b2Free(m_bendConstraints);
  19941.     b2Free(m_bindPositions);
  19942.     b2Free(m_ps);
  19943.     b2Free(m_p0s);
  19944.     b2Free(m_vs);
  19945.     b2Free(m_invMasses);
  19946. }
  19947.  
  19948. void b2Rope::Create(const b2RopeDef& def) {
  19949.     b2Assert(def.count >= 3);
  19950.     m_position = def.position;
  19951.     m_count = def.count;
  19952.     m_bindPositions = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2));
  19953.     m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2));
  19954.     m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2));
  19955.     m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2));
  19956.     m_invMasses = (float*)b2Alloc(m_count * sizeof(float));
  19957.  
  19958.     for (int32 i = 0; i < m_count; ++i) {
  19959.         m_bindPositions[i] = def.vertices[i];
  19960.         m_ps[i] = def.vertices[i] + m_position;
  19961.         m_p0s[i] = def.vertices[i] + m_position;
  19962.         m_vs[i].SetZero();
  19963.  
  19964.         float m = def.masses[i];
  19965.         if (m > 0.0f) {
  19966.             m_invMasses[i] = 1.0f / m;
  19967.         } else {
  19968.             m_invMasses[i] = 0.0f;
  19969.         }
  19970.     }
  19971.  
  19972.     m_stretchCount = m_count - 1;
  19973.     m_bendCount = m_count - 2;
  19974.  
  19975.     m_stretchConstraints = (b2RopeStretch*)b2Alloc(m_stretchCount * sizeof(b2RopeStretch));
  19976.     m_bendConstraints = (b2RopeBend*)b2Alloc(m_bendCount * sizeof(b2RopeBend));
  19977.  
  19978.     for (int32 i = 0; i < m_stretchCount; ++i) {
  19979.         b2RopeStretch& c = m_stretchConstraints[i];
  19980.  
  19981.         b2Vec2 p1 = m_ps[i];
  19982.         b2Vec2 p2 = m_ps[i + 1];
  19983.  
  19984.         c.i1 = i;
  19985.         c.i2 = i + 1;
  19986.         c.L = b2Distance(p1, p2);
  19987.         c.invMass1 = m_invMasses[i];
  19988.         c.invMass2 = m_invMasses[i + 1];
  19989.         c.lambda = 0.0f;
  19990.         c.damper = 0.0f;
  19991.         c.spring = 0.0f;
  19992.     }
  19993.  
  19994.     for (int32 i = 0; i < m_bendCount; ++i) {
  19995.         b2RopeBend& c = m_bendConstraints[i];
  19996.  
  19997.         b2Vec2 p1 = m_ps[i];
  19998.         b2Vec2 p2 = m_ps[i + 1];
  19999.         b2Vec2 p3 = m_ps[i + 2];
  20000.  
  20001.         c.i1 = i;
  20002.         c.i2 = i + 1;
  20003.         c.i3 = i + 2;
  20004.         c.invMass1 = m_invMasses[i];
  20005.         c.invMass2 = m_invMasses[i + 1];
  20006.         c.invMass3 = m_invMasses[i + 2];
  20007.         c.invEffectiveMass = 0.0f;
  20008.         c.L1 = b2Distance(p1, p2);
  20009.         c.L2 = b2Distance(p2, p3);
  20010.         c.lambda = 0.0f;
  20011.  
  20012.         // Pre-compute effective mass (TODO use flattened config)
  20013.         b2Vec2 e1 = p2 - p1;
  20014.         b2Vec2 e2 = p3 - p2;
  20015.         float L1sqr = e1.LengthSquared();
  20016.         float L2sqr = e2.LengthSquared();
  20017.  
  20018.         if (L1sqr * L2sqr == 0.0f) {
  20019.             continue;
  20020.         }
  20021.  
  20022.         b2Vec2 Jd1 = (-1.0f / L1sqr) * e1.Skew();
  20023.         b2Vec2 Jd2 = (1.0f / L2sqr) * e2.Skew();
  20024.  
  20025.         b2Vec2 J1 = -Jd1;
  20026.         b2Vec2 J2 = Jd1 - Jd2;
  20027.         b2Vec2 J3 = Jd2;
  20028.  
  20029.         c.invEffectiveMass = c.invMass1 * b2Dot(J1, J1) + c.invMass2 * b2Dot(J2, J2) + c.invMass3 * b2Dot(J3, J3);
  20030.  
  20031.         b2Vec2 r = p3 - p1;
  20032.  
  20033.         float rr = r.LengthSquared();
  20034.         if (rr == 0.0f) {
  20035.             continue;
  20036.         }
  20037.  
  20038.         // a1 = h2 / (h1 + h2)
  20039.         // a2 = h1 / (h1 + h2)
  20040.         c.alpha1 = b2Dot(e2, r) / rr;
  20041.         c.alpha2 = b2Dot(e1, r) / rr;
  20042.     }
  20043.  
  20044.     m_gravity = def.gravity;
  20045.  
  20046.     SetTuning(def.tuning);
  20047. }
  20048.  
  20049. void b2Rope::SetTuning(const b2RopeTuning& tuning) {
  20050.     m_tuning = tuning;
  20051.  
  20052.     // Pre-compute spring and damper values based on tuning
  20053.  
  20054.     const float bendOmega = 2.0f * b2_pi * m_tuning.bendHertz;
  20055.  
  20056.     for (int32 i = 0; i < m_bendCount; ++i) {
  20057.         b2RopeBend& c = m_bendConstraints[i];
  20058.  
  20059.         float L1sqr = c.L1 * c.L1;
  20060.         float L2sqr = c.L2 * c.L2;
  20061.  
  20062.         if (L1sqr * L2sqr == 0.0f) {
  20063.             c.spring = 0.0f;
  20064.             c.damper = 0.0f;
  20065.             continue;
  20066.         }
  20067.  
  20068.         // Flatten the triangle formed by the two edges
  20069.         float J2 = 1.0f / c.L1 + 1.0f / c.L2;
  20070.         float sum = c.invMass1 / L1sqr + c.invMass2 * J2 * J2 + c.invMass3 / L2sqr;
  20071.         if (sum == 0.0f) {
  20072.             c.spring = 0.0f;
  20073.             c.damper = 0.0f;
  20074.             continue;
  20075.         }
  20076.  
  20077.         float mass = 1.0f / sum;
  20078.  
  20079.         c.spring = mass * bendOmega * bendOmega;
  20080.         c.damper = 2.0f * mass * m_tuning.bendDamping * bendOmega;
  20081.     }
  20082.  
  20083.     const float stretchOmega = 2.0f * b2_pi * m_tuning.stretchHertz;
  20084.  
  20085.     for (int32 i = 0; i < m_stretchCount; ++i) {
  20086.         b2RopeStretch& c = m_stretchConstraints[i];
  20087.  
  20088.         float sum = c.invMass1 + c.invMass2;
  20089.         if (sum == 0.0f) {
  20090.             continue;
  20091.         }
  20092.  
  20093.         float mass = 1.0f / sum;
  20094.  
  20095.         c.spring = mass * stretchOmega * stretchOmega;
  20096.         c.damper = 2.0f * mass * m_tuning.stretchDamping * stretchOmega;
  20097.     }
  20098. }
  20099.  
  20100. void b2Rope::Step(float dt, int32 iterations, const b2Vec2& position) {
  20101.     if (dt == 0.0) {
  20102.         return;
  20103.     }
  20104.  
  20105.     const float inv_dt = 1.0f / dt;
  20106.     float d = expf(-dt * m_tuning.damping);
  20107.  
  20108.     // Apply gravity and damping
  20109.     for (int32 i = 0; i < m_count; ++i) {
  20110.         if (m_invMasses[i] > 0.0f) {
  20111.             m_vs[i] *= d;
  20112.             m_vs[i] += dt * m_gravity;
  20113.         } else {
  20114.             m_vs[i] = inv_dt * (m_bindPositions[i] + position - m_p0s[i]);
  20115.         }
  20116.     }
  20117.  
  20118.     // Apply bending spring
  20119.     if (m_tuning.bendingModel == b2_springAngleBendingModel) {
  20120.         ApplyBendForces(dt);
  20121.     }
  20122.  
  20123.     for (int32 i = 0; i < m_bendCount; ++i) {
  20124.         m_bendConstraints[i].lambda = 0.0f;
  20125.     }
  20126.  
  20127.     for (int32 i = 0; i < m_stretchCount; ++i) {
  20128.         m_stretchConstraints[i].lambda = 0.0f;
  20129.     }
  20130.  
  20131.     // Update position
  20132.     for (int32 i = 0; i < m_count; ++i) {
  20133.         m_ps[i] += dt * m_vs[i];
  20134.     }
  20135.  
  20136.     // Solve constraints
  20137.     for (int32 i = 0; i < iterations; ++i) {
  20138.         if (m_tuning.bendingModel == b2_pbdAngleBendingModel) {
  20139.             SolveBend_PBD_Angle();
  20140.         } else if (m_tuning.bendingModel == b2_xpbdAngleBendingModel) {
  20141.             SolveBend_XPBD_Angle(dt);
  20142.         } else if (m_tuning.bendingModel == b2_pbdDistanceBendingModel) {
  20143.             SolveBend_PBD_Distance();
  20144.         } else if (m_tuning.bendingModel == b2_pbdHeightBendingModel) {
  20145.             SolveBend_PBD_Height();
  20146.         } else if (m_tuning.bendingModel == b2_pbdTriangleBendingModel) {
  20147.             SolveBend_PBD_Triangle();
  20148.         }
  20149.  
  20150.         if (m_tuning.stretchingModel == b2_pbdStretchingModel) {
  20151.             SolveStretch_PBD();
  20152.         } else if (m_tuning.stretchingModel == b2_xpbdStretchingModel) {
  20153.             SolveStretch_XPBD(dt);
  20154.         }
  20155.     }
  20156.  
  20157.     // Constrain velocity
  20158.     for (int32 i = 0; i < m_count; ++i) {
  20159.         m_vs[i] = inv_dt * (m_ps[i] - m_p0s[i]);
  20160.         m_p0s[i] = m_ps[i];
  20161.     }
  20162. }
  20163.  
  20164. void b2Rope::Reset(const b2Vec2& position) {
  20165.     m_position = position;
  20166.  
  20167.     for (int32 i = 0; i < m_count; ++i) {
  20168.         m_ps[i] = m_bindPositions[i] + m_position;
  20169.         m_p0s[i] = m_bindPositions[i] + m_position;
  20170.         m_vs[i].SetZero();
  20171.     }
  20172.  
  20173.     for (int32 i = 0; i < m_bendCount; ++i) {
  20174.         m_bendConstraints[i].lambda = 0.0f;
  20175.     }
  20176.  
  20177.     for (int32 i = 0; i < m_stretchCount; ++i) {
  20178.         m_stretchConstraints[i].lambda = 0.0f;
  20179.     }
  20180. }
  20181.  
  20182. void b2Rope::SolveStretch_PBD() {
  20183.     const float stiffness = m_tuning.stretchStiffness;
  20184.  
  20185.     for (int32 i = 0; i < m_stretchCount; ++i) {
  20186.         const b2RopeStretch& c = m_stretchConstraints[i];
  20187.  
  20188.         b2Vec2 p1 = m_ps[c.i1];
  20189.         b2Vec2 p2 = m_ps[c.i2];
  20190.  
  20191.         b2Vec2 d = p2 - p1;
  20192.         float L = d.Normalize();
  20193.  
  20194.         float sum = c.invMass1 + c.invMass2;
  20195.         if (sum == 0.0f) {
  20196.             continue;
  20197.         }
  20198.  
  20199.         float s1 = c.invMass1 / sum;
  20200.         float s2 = c.invMass2 / sum;
  20201.  
  20202.         p1 -= stiffness * s1 * (c.L - L) * d;
  20203.         p2 += stiffness * s2 * (c.L - L) * d;
  20204.  
  20205.         m_ps[c.i1] = p1;
  20206.         m_ps[c.i2] = p2;
  20207.     }
  20208. }
  20209.  
  20210. void b2Rope::SolveStretch_XPBD(float dt) {
  20211.     b2Assert(dt > 0.0f);
  20212.  
  20213.     for (int32 i = 0; i < m_stretchCount; ++i) {
  20214.         b2RopeStretch& c = m_stretchConstraints[i];
  20215.  
  20216.         b2Vec2 p1 = m_ps[c.i1];
  20217.         b2Vec2 p2 = m_ps[c.i2];
  20218.  
  20219.         b2Vec2 dp1 = p1 - m_p0s[c.i1];
  20220.         b2Vec2 dp2 = p2 - m_p0s[c.i2];
  20221.  
  20222.         b2Vec2 u = p2 - p1;
  20223.         float L = u.Normalize();
  20224.  
  20225.         b2Vec2 J1 = -u;
  20226.         b2Vec2 J2 = u;
  20227.  
  20228.         float sum = c.invMass1 + c.invMass2;
  20229.         if (sum == 0.0f) {
  20230.             continue;
  20231.         }
  20232.  
  20233.         const float alpha = 1.0f / (c.spring * dt * dt);    // 1 / kg
  20234.         const float beta = dt * dt * c.damper;              // kg * s
  20235.         const float sigma = alpha * beta / dt;              // non-dimensional
  20236.         float C = L - c.L;
  20237.  
  20238.         // This is using the initial velocities
  20239.         float Cdot = b2Dot(J1, dp1) + b2Dot(J2, dp2);
  20240.  
  20241.         float B = C + alpha * c.lambda + sigma * Cdot;
  20242.         float sum2 = (1.0f + sigma) * sum + alpha;
  20243.  
  20244.         float impulse = -B / sum2;
  20245.  
  20246.         p1 += (c.invMass1 * impulse) * J1;
  20247.         p2 += (c.invMass2 * impulse) * J2;
  20248.  
  20249.         m_ps[c.i1] = p1;
  20250.         m_ps[c.i2] = p2;
  20251.         c.lambda += impulse;
  20252.     }
  20253. }
  20254.  
  20255. void b2Rope::SolveBend_PBD_Angle() {
  20256.     const float stiffness = m_tuning.bendStiffness;
  20257.  
  20258.     for (int32 i = 0; i < m_bendCount; ++i) {
  20259.         const b2RopeBend& c = m_bendConstraints[i];
  20260.  
  20261.         b2Vec2 p1 = m_ps[c.i1];
  20262.         b2Vec2 p2 = m_ps[c.i2];
  20263.         b2Vec2 p3 = m_ps[c.i3];
  20264.  
  20265.         b2Vec2 d1 = p2 - p1;
  20266.         b2Vec2 d2 = p3 - p2;
  20267.         float a = b2Cross(d1, d2);
  20268.         float b = b2Dot(d1, d2);
  20269.  
  20270.         float angle = b2Atan2(a, b);
  20271.  
  20272.         float L1sqr, L2sqr;
  20273.  
  20274.         if (m_tuning.isometric) {
  20275.             L1sqr = c.L1 * c.L1;
  20276.             L2sqr = c.L2 * c.L2;
  20277.         } else {
  20278.             L1sqr = d1.LengthSquared();
  20279.             L2sqr = d2.LengthSquared();
  20280.         }
  20281.  
  20282.         if (L1sqr * L2sqr == 0.0f) {
  20283.             continue;
  20284.         }
  20285.  
  20286.         b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew();
  20287.         b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew();
  20288.  
  20289.         b2Vec2 J1 = -Jd1;
  20290.         b2Vec2 J2 = Jd1 - Jd2;
  20291.         b2Vec2 J3 = Jd2;
  20292.  
  20293.         float sum;
  20294.         if (m_tuning.fixedEffectiveMass) {
  20295.             sum = c.invEffectiveMass;
  20296.         } else {
  20297.             sum = c.invMass1 * b2Dot(J1, J1) + c.invMass2 * b2Dot(J2, J2) + c.invMass3 * b2Dot(J3, J3);
  20298.         }
  20299.  
  20300.         if (sum == 0.0f) {
  20301.             sum = c.invEffectiveMass;
  20302.         }
  20303.  
  20304.         float impulse = -stiffness * angle / sum;
  20305.  
  20306.         p1 += (c.invMass1 * impulse) * J1;
  20307.         p2 += (c.invMass2 * impulse) * J2;
  20308.         p3 += (c.invMass3 * impulse) * J3;
  20309.  
  20310.         m_ps[c.i1] = p1;
  20311.         m_ps[c.i2] = p2;
  20312.         m_ps[c.i3] = p3;
  20313.     }
  20314. }
  20315.  
  20316. void b2Rope::SolveBend_XPBD_Angle(float dt) {
  20317.     b2Assert(dt > 0.0f);
  20318.  
  20319.     for (int32 i = 0; i < m_bendCount; ++i) {
  20320.         b2RopeBend& c = m_bendConstraints[i];
  20321.  
  20322.         b2Vec2 p1 = m_ps[c.i1];
  20323.         b2Vec2 p2 = m_ps[c.i2];
  20324.         b2Vec2 p3 = m_ps[c.i3];
  20325.  
  20326.         b2Vec2 dp1 = p1 - m_p0s[c.i1];
  20327.         b2Vec2 dp2 = p2 - m_p0s[c.i2];
  20328.         b2Vec2 dp3 = p3 - m_p0s[c.i3];
  20329.  
  20330.         b2Vec2 d1 = p2 - p1;
  20331.         b2Vec2 d2 = p3 - p2;
  20332.  
  20333.         float L1sqr, L2sqr;
  20334.  
  20335.         if (m_tuning.isometric) {
  20336.             L1sqr = c.L1 * c.L1;
  20337.             L2sqr = c.L2 * c.L2;
  20338.         } else {
  20339.             L1sqr = d1.LengthSquared();
  20340.             L2sqr = d2.LengthSquared();
  20341.         }
  20342.  
  20343.         if (L1sqr * L2sqr == 0.0f) {
  20344.             continue;
  20345.         }
  20346.  
  20347.         float a = b2Cross(d1, d2);
  20348.         float b = b2Dot(d1, d2);
  20349.  
  20350.         float angle = b2Atan2(a, b);
  20351.  
  20352.         b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew();
  20353.         b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew();
  20354.  
  20355.         b2Vec2 J1 = -Jd1;
  20356.         b2Vec2 J2 = Jd1 - Jd2;
  20357.         b2Vec2 J3 = Jd2;
  20358.  
  20359.         float sum;
  20360.         if (m_tuning.fixedEffectiveMass) {
  20361.             sum = c.invEffectiveMass;
  20362.         } else {
  20363.             sum = c.invMass1 * b2Dot(J1, J1) + c.invMass2 * b2Dot(J2, J2) + c.invMass3 * b2Dot(J3, J3);
  20364.         }
  20365.  
  20366.         if (sum == 0.0f) {
  20367.             continue;
  20368.         }
  20369.  
  20370.         const float alpha = 1.0f / (c.spring * dt * dt);
  20371.         const float beta = dt * dt * c.damper;
  20372.         const float sigma = alpha * beta / dt;
  20373.         float C = angle;
  20374.  
  20375.         // This is using the initial velocities
  20376.         float Cdot = b2Dot(J1, dp1) + b2Dot(J2, dp2) + b2Dot(J3, dp3);
  20377.  
  20378.         float B = C + alpha * c.lambda + sigma * Cdot;
  20379.         float sum2 = (1.0f + sigma) * sum + alpha;
  20380.  
  20381.         float impulse = -B / sum2;
  20382.  
  20383.         p1 += (c.invMass1 * impulse) * J1;
  20384.         p2 += (c.invMass2 * impulse) * J2;
  20385.         p3 += (c.invMass3 * impulse) * J3;
  20386.  
  20387.         m_ps[c.i1] = p1;
  20388.         m_ps[c.i2] = p2;
  20389.         m_ps[c.i3] = p3;
  20390.         c.lambda += impulse;
  20391.     }
  20392. }
  20393.  
  20394. void b2Rope::ApplyBendForces(float dt) {
  20395.     // omega = 2 * pi * hz
  20396.     const float omega = 2.0f * b2_pi * m_tuning.bendHertz;
  20397.  
  20398.     for (int32 i = 0; i < m_bendCount; ++i) {
  20399.         const b2RopeBend& c = m_bendConstraints[i];
  20400.  
  20401.         b2Vec2 p1 = m_ps[c.i1];
  20402.         b2Vec2 p2 = m_ps[c.i2];
  20403.         b2Vec2 p3 = m_ps[c.i3];
  20404.  
  20405.         b2Vec2 v1 = m_vs[c.i1];
  20406.         b2Vec2 v2 = m_vs[c.i2];
  20407.         b2Vec2 v3 = m_vs[c.i3];
  20408.  
  20409.         b2Vec2 d1 = p2 - p1;
  20410.         b2Vec2 d2 = p3 - p2;
  20411.  
  20412.         float L1sqr, L2sqr;
  20413.  
  20414.         if (m_tuning.isometric) {
  20415.             L1sqr = c.L1 * c.L1;
  20416.             L2sqr = c.L2 * c.L2;
  20417.         } else {
  20418.             L1sqr = d1.LengthSquared();
  20419.             L2sqr = d2.LengthSquared();
  20420.         }
  20421.  
  20422.         if (L1sqr * L2sqr == 0.0f) {
  20423.             continue;
  20424.         }
  20425.  
  20426.         float a = b2Cross(d1, d2);
  20427.         float b = b2Dot(d1, d2);
  20428.  
  20429.         float angle = b2Atan2(a, b);
  20430.  
  20431.         b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew();
  20432.         b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew();
  20433.  
  20434.         b2Vec2 J1 = -Jd1;
  20435.         b2Vec2 J2 = Jd1 - Jd2;
  20436.         b2Vec2 J3 = Jd2;
  20437.  
  20438.         float sum;
  20439.         if (m_tuning.fixedEffectiveMass) {
  20440.             sum = c.invEffectiveMass;
  20441.         } else {
  20442.             sum = c.invMass1 * b2Dot(J1, J1) + c.invMass2 * b2Dot(J2, J2) + c.invMass3 * b2Dot(J3, J3);
  20443.         }
  20444.  
  20445.         if (sum == 0.0f) {
  20446.             continue;
  20447.         }
  20448.  
  20449.         float mass = 1.0f / sum;
  20450.  
  20451.         const float spring = mass * omega * omega;
  20452.         const float damper = 2.0f * mass * m_tuning.bendDamping * omega;
  20453.  
  20454.         float C = angle;
  20455.         float Cdot = b2Dot(J1, v1) + b2Dot(J2, v2) + b2Dot(J3, v3);
  20456.  
  20457.         float impulse = -dt * (spring * C + damper * Cdot);
  20458.  
  20459.         m_vs[c.i1] += (c.invMass1 * impulse) * J1;
  20460.         m_vs[c.i2] += (c.invMass2 * impulse) * J2;
  20461.         m_vs[c.i3] += (c.invMass3 * impulse) * J3;
  20462.     }
  20463. }
  20464.  
  20465. void b2Rope::SolveBend_PBD_Distance() {
  20466.     const float stiffness = m_tuning.bendStiffness;
  20467.  
  20468.     for (int32 i = 0; i < m_bendCount; ++i) {
  20469.         const b2RopeBend& c = m_bendConstraints[i];
  20470.  
  20471.         int32 i1 = c.i1;
  20472.         int32 i2 = c.i3;
  20473.  
  20474.         b2Vec2 p1 = m_ps[i1];
  20475.         b2Vec2 p2 = m_ps[i2];
  20476.  
  20477.         b2Vec2 d = p2 - p1;
  20478.         float L = d.Normalize();
  20479.  
  20480.         float sum = c.invMass1 + c.invMass3;
  20481.         if (sum == 0.0f) {
  20482.             continue;
  20483.         }
  20484.  
  20485.         float s1 = c.invMass1 / sum;
  20486.         float s2 = c.invMass3 / sum;
  20487.  
  20488.         p1 -= stiffness * s1 * (c.L1 + c.L2 - L) * d;
  20489.         p2 += stiffness * s2 * (c.L1 + c.L2 - L) * d;
  20490.  
  20491.         m_ps[i1] = p1;
  20492.         m_ps[i2] = p2;
  20493.     }
  20494. }
  20495.  
  20496. // Constraint based implementation of:
  20497. // P. Volino: Simple Linear Bending Stiffness in Particle Systems
  20498. void b2Rope::SolveBend_PBD_Height() {
  20499.     const float stiffness = m_tuning.bendStiffness;
  20500.  
  20501.     for (int32 i = 0; i < m_bendCount; ++i) {
  20502.         const b2RopeBend& c = m_bendConstraints[i];
  20503.  
  20504.         b2Vec2 p1 = m_ps[c.i1];
  20505.         b2Vec2 p2 = m_ps[c.i2];
  20506.         b2Vec2 p3 = m_ps[c.i3];
  20507.  
  20508.         // Barycentric coordinates are held constant
  20509.         b2Vec2 d = c.alpha1 * p1 + c.alpha2 * p3 - p2;
  20510.         float dLen = d.Length();
  20511.  
  20512.         if (dLen == 0.0f) {
  20513.             continue;
  20514.         }
  20515.  
  20516.         b2Vec2 dHat = (1.0f / dLen) * d;
  20517.  
  20518.         b2Vec2 J1 = c.alpha1 * dHat;
  20519.         b2Vec2 J2 = -dHat;
  20520.         b2Vec2 J3 = c.alpha2 * dHat;
  20521.  
  20522.         float sum = c.invMass1 * c.alpha1 * c.alpha1 + c.invMass2 + c.invMass3 * c.alpha2 * c.alpha2;
  20523.  
  20524.         if (sum == 0.0f) {
  20525.             continue;
  20526.         }
  20527.  
  20528.         float C = dLen;
  20529.         float mass = 1.0f / sum;
  20530.         float impulse = -stiffness * mass * C;
  20531.  
  20532.         p1 += (c.invMass1 * impulse) * J1;
  20533.         p2 += (c.invMass2 * impulse) * J2;
  20534.         p3 += (c.invMass3 * impulse) * J3;
  20535.  
  20536.         m_ps[c.i1] = p1;
  20537.         m_ps[c.i2] = p2;
  20538.         m_ps[c.i3] = p3;
  20539.     }
  20540. }
  20541.  
  20542. // M. Kelager: A Triangle Bending Constraint Model for PBD
  20543. void b2Rope::SolveBend_PBD_Triangle() {
  20544.     const float stiffness = m_tuning.bendStiffness;
  20545.  
  20546.     for (int32 i = 0; i < m_bendCount; ++i) {
  20547.         const b2RopeBend& c = m_bendConstraints[i];
  20548.  
  20549.         b2Vec2 b0 = m_ps[c.i1];
  20550.         b2Vec2 v = m_ps[c.i2];
  20551.         b2Vec2 b1 = m_ps[c.i3];
  20552.  
  20553.         float wb0 = c.invMass1;
  20554.         float wv = c.invMass2;
  20555.         float wb1 = c.invMass3;
  20556.  
  20557.         float W = wb0 + wb1 + 2.0f * wv;
  20558.         float invW = stiffness / W;
  20559.  
  20560.         b2Vec2 d = v - (1.0f / 3.0f) * (b0 + v + b1);
  20561.  
  20562.         b2Vec2 db0 = 2.0f * wb0 * invW * d;
  20563.         b2Vec2 dv = -4.0f * wv * invW * d;
  20564.         b2Vec2 db1 = 2.0f * wb1 * invW * d;
  20565.  
  20566.         b0 += db0;
  20567.         v += dv;
  20568.         b1 += db1;
  20569.  
  20570.         m_ps[c.i1] = b0;
  20571.         m_ps[c.i2] = v;
  20572.         m_ps[c.i3] = b1;
  20573.     }
  20574. }
  20575.  
  20576. void b2Rope::Draw(b2Draw* draw) const {
  20577.     b2Color c(0.4f, 0.5f, 0.7f);
  20578.     b2Color pg(0.1f, 0.8f, 0.1f);
  20579.     b2Color pd(0.7f, 0.2f, 0.4f);
  20580.  
  20581.     for (int32 i = 0; i < m_count - 1; ++i) {
  20582.         draw->DrawSegment(m_ps[i], m_ps[i + 1], c);
  20583.  
  20584.         const b2Color& pc = m_invMasses[i] > 0.0f ? pd : pg;
  20585.         draw->DrawPoint(m_ps[i], 5.0f, pc);
  20586.     }
  20587.  
  20588.     const b2Color& pc = m_invMasses[m_count - 1] > 0.0f ? pd : pg;
  20589.     draw->DrawPoint(m_ps[m_count - 1], 5.0f, pc);
  20590. }
  20591.  
  20592. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement