b2_polygon_shape.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // MIT License
  2. // Copyright (c) 2019 Erin Catto
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. // The above copyright notice and this permission notice shall be included in all
  10. // copies or substantial portions of the Software.
  11. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. // SOFTWARE.
  18. #include "box2d/b2_polygon_shape.h"
  19. #include "box2d/b2_block_allocator.h"
  20. #include <new>
  21. b2PolygonShape::b2PolygonShape()
  22. {
  23. m_type = e_polygon;
  24. m_radius = b2_polygonRadius;
  25. m_count = 0;
  26. m_centroid.SetZero();
  27. }
  28. b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const
  29. {
  30. void* mem = allocator->Allocate(sizeof(b2PolygonShape));
  31. b2PolygonShape* clone = new (mem) b2PolygonShape;
  32. *clone = *this;
  33. return clone;
  34. }
  35. void b2PolygonShape::SetAsBox(float hx, float hy)
  36. {
  37. m_count = 4;
  38. m_vertices[0].Set(-hx, -hy);
  39. m_vertices[1].Set( hx, -hy);
  40. m_vertices[2].Set( hx, hy);
  41. m_vertices[3].Set(-hx, hy);
  42. m_normals[0].Set(0.0f, -1.0f);
  43. m_normals[1].Set(1.0f, 0.0f);
  44. m_normals[2].Set(0.0f, 1.0f);
  45. m_normals[3].Set(-1.0f, 0.0f);
  46. m_centroid.SetZero();
  47. }
  48. void b2PolygonShape::SetAsBox(float hx, float hy, const b2Vec2& center, float angle)
  49. {
  50. m_count = 4;
  51. m_vertices[0].Set(-hx, -hy);
  52. m_vertices[1].Set( hx, -hy);
  53. m_vertices[2].Set( hx, hy);
  54. m_vertices[3].Set(-hx, hy);
  55. m_normals[0].Set(0.0f, -1.0f);
  56. m_normals[1].Set(1.0f, 0.0f);
  57. m_normals[2].Set(0.0f, 1.0f);
  58. m_normals[3].Set(-1.0f, 0.0f);
  59. m_centroid = center;
  60. b2Transform xf;
  61. xf.p = center;
  62. xf.q.Set(angle);
  63. // Transform vertices and normals.
  64. for (int32 i = 0; i < m_count; ++i)
  65. {
  66. m_vertices[i] = b2Mul(xf, m_vertices[i]);
  67. m_normals[i] = b2Mul(xf.q, m_normals[i]);
  68. }
  69. }
  70. int32 b2PolygonShape::GetChildCount() const
  71. {
  72. return 1;
  73. }
  74. static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count)
  75. {
  76. b2Assert(count >= 3);
  77. b2Vec2 c(0.0f, 0.0f);
  78. float area = 0.0f;
  79. // Get a reference point for forming triangles.
  80. // Use the first vertex to reduce round-off errors.
  81. b2Vec2 s = vs[0];
  82. const float inv3 = 1.0f / 3.0f;
  83. for (int32 i = 0; i < count; ++i)
  84. {
  85. // Triangle vertices.
  86. b2Vec2 p1 = vs[0] - s;
  87. b2Vec2 p2 = vs[i] - s;
  88. b2Vec2 p3 = i + 1 < count ? vs[i+1] - s : vs[0] - s;
  89. b2Vec2 e1 = p2 - p1;
  90. b2Vec2 e2 = p3 - p1;
  91. float D = b2Cross(e1, e2);
  92. float triangleArea = 0.5f * D;
  93. area += triangleArea;
  94. // Area weighted centroid
  95. c += triangleArea * inv3 * (p1 + p2 + p3);
  96. }
  97. // Centroid
  98. b2Assert(area > b2_epsilon);
  99. c = (1.0f / area) * c + s;
  100. return c;
  101. }
  102. bool b2PolygonShape::Set(const b2Vec2* vertices, int32 count)
  103. {
  104. b2Hull hull = b2ComputeHull(vertices, count);
  105. if (hull.count < 3)
  106. {
  107. return false;
  108. }
  109. Set(hull);
  110. return true;
  111. }
  112. void b2PolygonShape::Set(const b2Hull& hull)
  113. {
  114. b2Assert(hull.count >= 3);
  115. m_count = hull.count;
  116. // Copy vertices
  117. for (int32 i = 0; i < hull.count; ++i)
  118. {
  119. m_vertices[i] = hull.points[i];
  120. }
  121. // Compute normals. Ensure the edges have non-zero length.
  122. for (int32 i = 0; i < m_count; ++i)
  123. {
  124. int32 i1 = i;
  125. int32 i2 = i + 1 < m_count ? i + 1 : 0;
  126. b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
  127. b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
  128. m_normals[i] = b2Cross(edge, 1.0f);
  129. m_normals[i].Normalize();
  130. }
  131. // Compute the polygon centroid.
  132. m_centroid = ComputeCentroid(m_vertices, m_count);
  133. }
  134. bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
  135. {
  136. b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);
  137. for (int32 i = 0; i < m_count; ++i)
  138. {
  139. float dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
  140. if (dot > 0.0f)
  141. {
  142. return false;
  143. }
  144. }
  145. return true;
  146. }
  147. bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  148. const b2Transform& xf, int32 childIndex) const
  149. {
  150. B2_NOT_USED(childIndex);
  151. // Put the ray into the polygon's frame of reference.
  152. b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
  153. b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
  154. b2Vec2 d = p2 - p1;
  155. float lower = 0.0f, upper = input.maxFraction;
  156. int32 index = -1;
  157. for (int32 i = 0; i < m_count; ++i)
  158. {
  159. // p = p1 + a * d
  160. // dot(normal, p - v) = 0
  161. // dot(normal, p1 - v) + a * dot(normal, d) = 0
  162. float numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
  163. float denominator = b2Dot(m_normals[i], d);
  164. if (denominator == 0.0f)
  165. {
  166. if (numerator < 0.0f)
  167. {
  168. return false;
  169. }
  170. }
  171. else
  172. {
  173. // Note: we want this predicate without division:
  174. // lower < numerator / denominator, where denominator < 0
  175. // Since denominator < 0, we have to flip the inequality:
  176. // lower < numerator / denominator <==> denominator * lower > numerator.
  177. if (denominator < 0.0f && numerator < lower * denominator)
  178. {
  179. // Increase lower.
  180. // The segment enters this half-space.
  181. lower = numerator / denominator;
  182. index = i;
  183. }
  184. else if (denominator > 0.0f && numerator < upper * denominator)
  185. {
  186. // Decrease upper.
  187. // The segment exits this half-space.
  188. upper = numerator / denominator;
  189. }
  190. }
  191. // The use of epsilon here causes the assert on lower to trip
  192. // in some cases. Apparently the use of epsilon was to make edge
  193. // shapes work, but now those are handled separately.
  194. //if (upper < lower - b2_epsilon)
  195. if (upper < lower)
  196. {
  197. return false;
  198. }
  199. }
  200. b2Assert(0.0f <= lower && lower <= input.maxFraction);
  201. if (index >= 0)
  202. {
  203. output->fraction = lower;
  204. output->normal = b2Mul(xf.q, m_normals[index]);
  205. return true;
  206. }
  207. return false;
  208. }
  209. void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
  210. {
  211. B2_NOT_USED(childIndex);
  212. b2Vec2 lower = b2Mul(xf, m_vertices[0]);
  213. b2Vec2 upper = lower;
  214. for (int32 i = 1; i < m_count; ++i)
  215. {
  216. b2Vec2 v = b2Mul(xf, m_vertices[i]);
  217. lower = b2Min(lower, v);
  218. upper = b2Max(upper, v);
  219. }
  220. b2Vec2 r(m_radius, m_radius);
  221. aabb->lowerBound = lower - r;
  222. aabb->upperBound = upper + r;
  223. }
  224. void b2PolygonShape::ComputeMass(b2MassData* massData, float density) const
  225. {
  226. // Polygon mass, centroid, and inertia.
  227. // Let rho be the polygon density in mass per unit area.
  228. // Then:
  229. // mass = rho * int(dA)
  230. // centroid.x = (1/mass) * rho * int(x * dA)
  231. // centroid.y = (1/mass) * rho * int(y * dA)
  232. // I = rho * int((x*x + y*y) * dA)
  233. //
  234. // We can compute these integrals by summing all the integrals
  235. // for each triangle of the polygon. To evaluate the integral
  236. // for a single triangle, we make a change of variables to
  237. // the (u,v) coordinates of the triangle:
  238. // x = x0 + e1x * u + e2x * v
  239. // y = y0 + e1y * u + e2y * v
  240. // where 0 <= u && 0 <= v && u + v <= 1.
  241. //
  242. // We integrate u from [0,1-v] and then v from [0,1].
  243. // We also need to use the Jacobian of the transformation:
  244. // D = cross(e1, e2)
  245. //
  246. // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
  247. //
  248. // The rest of the derivation is handled by computer algebra.
  249. b2Assert(m_count >= 3);
  250. b2Vec2 center(0.0f, 0.0f);
  251. float area = 0.0f;
  252. float I = 0.0f;
  253. // Get a reference point for forming triangles.
  254. // Use the first vertex to reduce round-off errors.
  255. b2Vec2 s = m_vertices[0];
  256. const float k_inv3 = 1.0f / 3.0f;
  257. for (int32 i = 0; i < m_count; ++i)
  258. {
  259. // Triangle vertices.
  260. b2Vec2 e1 = m_vertices[i] - s;
  261. b2Vec2 e2 = i + 1 < m_count ? m_vertices[i+1] - s : m_vertices[0] - s;
  262. float D = b2Cross(e1, e2);
  263. float triangleArea = 0.5f * D;
  264. area += triangleArea;
  265. // Area weighted centroid
  266. center += triangleArea * k_inv3 * (e1 + e2);
  267. float ex1 = e1.x, ey1 = e1.y;
  268. float ex2 = e2.x, ey2 = e2.y;
  269. float intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2;
  270. float inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2;
  271. I += (0.25f * k_inv3 * D) * (intx2 + inty2);
  272. }
  273. // Total mass
  274. massData->mass = density * area;
  275. // Center of mass
  276. b2Assert(area > b2_epsilon);
  277. center *= 1.0f / area;
  278. massData->center = center + s;
  279. // Inertia tensor relative to the local origin (point s).
  280. massData->I = density * I;
  281. // Shift to center of mass then to original body origin.
  282. massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
  283. }
  284. bool b2PolygonShape::Validate() const
  285. {
  286. if (m_count < 3 || b2_maxPolygonVertices < m_count)
  287. {
  288. return false;
  289. }
  290. b2Hull hull;
  291. for (int32 i = 0; i < m_count; ++i)
  292. {
  293. hull.points[i] = m_vertices[i];
  294. }
  295. hull.count = m_count;
  296. return b2ValidateHull(hull);
  297. }