b2PolygonShape.cpp 11 KB

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