b2PolygonShape.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. * Permission is granted to anyone to use this software for any purpose,
  8. * including commercial applications, and to alter it and redistribute it
  9. * freely, subject to the following restrictions:
  10. * 1. The origin of this software must not be misrepresented; you must not
  11. * claim that you wrote the original software. If you use this software
  12. * in a product, an acknowledgment in the product documentation would be
  13. * appreciated but is not required.
  14. * 2. Altered source versions must be plainly marked as such, and must not be
  15. * misrepresented as being the original software.
  16. * 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include <Box2D/Collision/Shapes/b2PolygonShape.h>
  19. #include <new>
  20. b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const
  21. {
  22. void* mem = allocator->Allocate(sizeof(b2PolygonShape));
  23. b2PolygonShape* clone = new (mem) b2PolygonShape;
  24. *clone = *this;
  25. return clone;
  26. }
  27. void b2PolygonShape::SetAsBox(float32 hx, float32 hy)
  28. {
  29. m_count = 4;
  30. m_vertices[0].Set(-hx, -hy);
  31. m_vertices[1].Set( hx, -hy);
  32. m_vertices[2].Set( hx, hy);
  33. m_vertices[3].Set(-hx, hy);
  34. m_normals[0].Set(0.0f, -1.0f);
  35. m_normals[1].Set(1.0f, 0.0f);
  36. m_normals[2].Set(0.0f, 1.0f);
  37. m_normals[3].Set(-1.0f, 0.0f);
  38. m_centroid.SetZero();
  39. }
  40. void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)
  41. {
  42. m_count = 4;
  43. m_vertices[0].Set(-hx, -hy);
  44. m_vertices[1].Set( hx, -hy);
  45. m_vertices[2].Set( hx, hy);
  46. m_vertices[3].Set(-hx, hy);
  47. m_normals[0].Set(0.0f, -1.0f);
  48. m_normals[1].Set(1.0f, 0.0f);
  49. m_normals[2].Set(0.0f, 1.0f);
  50. m_normals[3].Set(-1.0f, 0.0f);
  51. m_centroid = center;
  52. b2Transform xf;
  53. xf.p = center;
  54. xf.q.Set(angle);
  55. // Transform vertices and normals.
  56. for (int32 i = 0; i < m_count; ++i)
  57. {
  58. m_vertices[i] = b2Mul(xf, m_vertices[i]);
  59. m_normals[i] = b2Mul(xf.q, m_normals[i]);
  60. }
  61. }
  62. int32 b2PolygonShape::GetChildCount() const
  63. {
  64. return 1;
  65. }
  66. static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count)
  67. {
  68. b2Assert(count >= 3);
  69. b2Vec2 c; c.Set(0.0f, 0.0f);
  70. float32 area = 0.0f;
  71. // pRef is the reference point for forming triangles.
  72. // It's location doesn't change the result (except for rounding error).
  73. b2Vec2 pRef(0.0f, 0.0f);
  74. #if 0
  75. // This code would put the reference point inside the polygon.
  76. for (int32 i = 0; i < count; ++i)
  77. {
  78. pRef += vs[i];
  79. }
  80. pRef *= 1.0f / count;
  81. #endif
  82. const float32 inv3 = 1.0f / 3.0f;
  83. for (int32 i = 0; i < count; ++i)
  84. {
  85. // Triangle vertices.
  86. b2Vec2 p1 = pRef;
  87. b2Vec2 p2 = vs[i];
  88. b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0];
  89. b2Vec2 e1 = p2 - p1;
  90. b2Vec2 e2 = p3 - p1;
  91. float32 D = b2Cross(e1, e2);
  92. float32 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;
  100. return c;
  101. }
  102. void b2PolygonShape::Set(const b2Vec2* vertices, int32 count)
  103. {
  104. b2Assert(3 <= count && count <= b2_maxPolygonVertices);
  105. if (count < 3)
  106. {
  107. SetAsBox(1.0f, 1.0f);
  108. return;
  109. }
  110. int32 n = b2Min(count, b2_maxPolygonVertices);
  111. // Perform welding and copy vertices into local buffer.
  112. b2Vec2 ps[b2_maxPolygonVertices];
  113. int32 tempCount = 0;
  114. for (int32 i = 0; i < n; ++i)
  115. {
  116. b2Vec2 v = vertices[i];
  117. bool unique = true;
  118. for (int32 j = 0; j < tempCount; ++j)
  119. {
  120. if (b2DistanceSquared(v, ps[j]) < ((0.5f * b2_linearSlop) * (0.5f * b2_linearSlop)))
  121. {
  122. unique = false;
  123. break;
  124. }
  125. }
  126. if (unique)
  127. {
  128. ps[tempCount++] = v;
  129. }
  130. }
  131. n = tempCount;
  132. if (n < 3)
  133. {
  134. // Polygon is degenerate.
  135. b2Assert(false);
  136. SetAsBox(1.0f, 1.0f);
  137. return;
  138. }
  139. // Create the convex hull using the Gift wrapping algorithm
  140. // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm
  141. // Find the right most point on the hull
  142. int32 i0 = 0;
  143. float32 x0 = ps[0].x;
  144. for (int32 i = 1; i < n; ++i)
  145. {
  146. float32 x = ps[i].x;
  147. if (x > x0 || (x == x0 && ps[i].y < ps[i0].y))
  148. {
  149. i0 = i;
  150. x0 = x;
  151. }
  152. }
  153. int32 hull[b2_maxPolygonVertices];
  154. int32 m = 0;
  155. int32 ih = i0;
  156. for (;;)
  157. {
  158. hull[m] = ih;
  159. int32 ie = 0;
  160. for (int32 j = 1; j < n; ++j)
  161. {
  162. if (ie == ih)
  163. {
  164. ie = j;
  165. continue;
  166. }
  167. b2Vec2 r = ps[ie] - ps[hull[m]];
  168. b2Vec2 v = ps[j] - ps[hull[m]];
  169. float32 c = b2Cross(r, v);
  170. if (c < 0.0f)
  171. {
  172. ie = j;
  173. }
  174. // Collinearity check
  175. if (c == 0.0f && v.LengthSquared() > r.LengthSquared())
  176. {
  177. ie = j;
  178. }
  179. }
  180. ++m;
  181. ih = ie;
  182. if (ie == i0)
  183. {
  184. break;
  185. }
  186. }
  187. if (m < 3)
  188. {
  189. // Polygon is degenerate.
  190. b2Assert(false);
  191. SetAsBox(1.0f, 1.0f);
  192. return;
  193. }
  194. m_count = m;
  195. // Copy vertices.
  196. for (int32 i = 0; i < m; ++i)
  197. {
  198. m_vertices[i] = ps[hull[i]];
  199. }
  200. // Compute normals. Ensure the edges have non-zero length.
  201. for (int32 i = 0; i < m; ++i)
  202. {
  203. int32 i1 = i;
  204. int32 i2 = i + 1 < m ? i + 1 : 0;
  205. b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
  206. b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
  207. m_normals[i] = b2Cross(edge, 1.0f);
  208. m_normals[i].Normalize();
  209. }
  210. // Compute the polygon centroid.
  211. m_centroid = ComputeCentroid(m_vertices, m);
  212. }
  213. bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
  214. {
  215. b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);
  216. for (int32 i = 0; i < m_count; ++i)
  217. {
  218. float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
  219. if (dot > 0.0f)
  220. {
  221. return false;
  222. }
  223. }
  224. return true;
  225. }
  226. bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  227. const b2Transform& xf, int32 childIndex) const
  228. {
  229. B2_NOT_USED(childIndex);
  230. // Put the ray into the polygon's frame of reference.
  231. b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
  232. b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
  233. b2Vec2 d = p2 - p1;
  234. float32 lower = 0.0f, upper = input.maxFraction;
  235. int32 index = -1;
  236. for (int32 i = 0; i < m_count; ++i)
  237. {
  238. // p = p1 + a * d
  239. // dot(normal, p - v) = 0
  240. // dot(normal, p1 - v) + a * dot(normal, d) = 0
  241. float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
  242. float32 denominator = b2Dot(m_normals[i], d);
  243. if (denominator == 0.0f)
  244. {
  245. if (numerator < 0.0f)
  246. {
  247. return false;
  248. }
  249. }
  250. else
  251. {
  252. // Note: we want this predicate without division:
  253. // lower < numerator / denominator, where denominator < 0
  254. // Since denominator < 0, we have to flip the inequality:
  255. // lower < numerator / denominator <==> denominator * lower > numerator.
  256. if (denominator < 0.0f && numerator < lower * denominator)
  257. {
  258. // Increase lower.
  259. // The segment enters this half-space.
  260. lower = numerator / denominator;
  261. index = i;
  262. }
  263. else if (denominator > 0.0f && numerator < upper * denominator)
  264. {
  265. // Decrease upper.
  266. // The segment exits this half-space.
  267. upper = numerator / denominator;
  268. }
  269. }
  270. // The use of epsilon here causes the assert on lower to trip
  271. // in some cases. Apparently the use of epsilon was to make edge
  272. // shapes work, but now those are handled separately.
  273. //if (upper < lower - b2_epsilon)
  274. if (upper < lower)
  275. {
  276. return false;
  277. }
  278. }
  279. b2Assert(0.0f <= lower && lower <= input.maxFraction);
  280. if (index >= 0)
  281. {
  282. output->fraction = lower;
  283. output->normal = b2Mul(xf.q, m_normals[index]);
  284. return true;
  285. }
  286. return false;
  287. }
  288. void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
  289. {
  290. B2_NOT_USED(childIndex);
  291. b2Vec2 lower = b2Mul(xf, m_vertices[0]);
  292. b2Vec2 upper = lower;
  293. for (int32 i = 1; i < m_count; ++i)
  294. {
  295. b2Vec2 v = b2Mul(xf, m_vertices[i]);
  296. lower = b2Min(lower, v);
  297. upper = b2Max(upper, v);
  298. }
  299. b2Vec2 r(m_radius, m_radius);
  300. aabb->lowerBound = lower - r;
  301. aabb->upperBound = upper + r;
  302. }
  303. void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const
  304. {
  305. // Polygon mass, centroid, and inertia.
  306. // Let rho be the polygon density in mass per unit area.
  307. // Then:
  308. // mass = rho * int(dA)
  309. // centroid.x = (1/mass) * rho * int(x * dA)
  310. // centroid.y = (1/mass) * rho * int(y * dA)
  311. // I = rho * int((x*x + y*y) * dA)
  312. //
  313. // We can compute these integrals by summing all the integrals
  314. // for each triangle of the polygon. To evaluate the integral
  315. // for a single triangle, we make a change of variables to
  316. // the (u,v) coordinates of the triangle:
  317. // x = x0 + e1x * u + e2x * v
  318. // y = y0 + e1y * u + e2y * v
  319. // where 0 <= u && 0 <= v && u + v <= 1.
  320. //
  321. // We integrate u from [0,1-v] and then v from [0,1].
  322. // We also need to use the Jacobian of the transformation:
  323. // D = cross(e1, e2)
  324. //
  325. // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
  326. //
  327. // The rest of the derivation is handled by computer algebra.
  328. b2Assert(m_count >= 3);
  329. b2Vec2 center; center.Set(0.0f, 0.0f);
  330. float32 area = 0.0f;
  331. float32 I = 0.0f;
  332. // s is the reference point for forming triangles.
  333. // It's location doesn't change the result (except for rounding error).
  334. b2Vec2 s(0.0f, 0.0f);
  335. // This code would put the reference point inside the polygon.
  336. for (int32 i = 0; i < m_count; ++i)
  337. {
  338. s += m_vertices[i];
  339. }
  340. s *= 1.0f / m_count;
  341. const float32 k_inv3 = 1.0f / 3.0f;
  342. for (int32 i = 0; i < m_count; ++i)
  343. {
  344. // Triangle vertices.
  345. b2Vec2 e1 = m_vertices[i] - s;
  346. b2Vec2 e2 = i + 1 < m_count ? m_vertices[i+1] - s : m_vertices[0] - s;
  347. float32 D = b2Cross(e1, e2);
  348. float32 triangleArea = 0.5f * D;
  349. area += triangleArea;
  350. // Area weighted centroid
  351. center += triangleArea * k_inv3 * (e1 + e2);
  352. float32 ex1 = e1.x, ey1 = e1.y;
  353. float32 ex2 = e2.x, ey2 = e2.y;
  354. float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2;
  355. float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2;
  356. I += (0.25f * k_inv3 * D) * (intx2 + inty2);
  357. }
  358. // Total mass
  359. massData->mass = density * area;
  360. // Center of mass
  361. b2Assert(area > b2_epsilon);
  362. center *= 1.0f / area;
  363. massData->center = center + s;
  364. // Inertia tensor relative to the local origin (point s).
  365. massData->I = density * I;
  366. // Shift to center of mass then to original body origin.
  367. massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
  368. }
  369. bool b2PolygonShape::Validate() const
  370. {
  371. for (int32 i = 0; i < m_count; ++i)
  372. {
  373. int32 i1 = i;
  374. int32 i2 = i < m_count - 1 ? i1 + 1 : 0;
  375. b2Vec2 p = m_vertices[i1];
  376. b2Vec2 e = m_vertices[i2] - p;
  377. for (int32 j = 0; j < m_count; ++j)
  378. {
  379. if (j == i1 || j == i2)
  380. {
  381. continue;
  382. }
  383. b2Vec2 v = m_vertices[j] - p;
  384. float32 c = b2Cross(e, v);
  385. if (c < 0.0f)
  386. {
  387. return false;
  388. }
  389. }
  390. }
  391. return true;
  392. }