b2PolygonShape.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /*
  2. * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. * Permission is granted to anyone to use this software for any purpose,
  8. * including commercial applications, and to alter it and redistribute it
  9. * freely, subject to the following restrictions:
  10. * 1. The origin of this software must not be misrepresented; you must not
  11. * claim that you wrote the original software. If you use this software
  12. * in a product, an acknowledgment in the product documentation would be
  13. * appreciated but is not required.
  14. * 2. Altered source versions must be plainly marked as such, and must not be
  15. * misrepresented as being the original software.
  16. * 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "b2PolygonShape.h"
  19. void b2PolygonDef::SetAsBox(float32 hx, float32 hy)
  20. {
  21. vertexCount = 4;
  22. vertices[0].Set(-hx, -hy);
  23. vertices[1].Set( hx, -hy);
  24. vertices[2].Set( hx, hy);
  25. vertices[3].Set(-hx, hy);
  26. }
  27. void b2PolygonDef::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)
  28. {
  29. SetAsBox(hx, hy);
  30. b2XForm xf;
  31. xf.position = center;
  32. xf.R.Set(angle);
  33. for (int32 i = 0; i < vertexCount; ++i)
  34. {
  35. vertices[i] = b2Mul(xf, vertices[i]);
  36. }
  37. }
  38. static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count)
  39. {
  40. b2Assert(count >= 3);
  41. b2Vec2 c; c.Set(0.0f, 0.0f);
  42. float32 area = 0.0f;
  43. // pRef is the reference point for forming triangles.
  44. // It's location doesn't change the result (except for rounding error).
  45. b2Vec2 pRef(0.0f, 0.0f);
  46. #if 0
  47. // This code would put the reference point inside the polygon.
  48. for (int32 i = 0; i < count; ++i)
  49. {
  50. pRef += vs[i];
  51. }
  52. pRef *= 1.0f / count;
  53. #endif
  54. const float32 inv3 = 1.0f / 3.0f;
  55. for (int32 i = 0; i < count; ++i)
  56. {
  57. // Triangle vertices.
  58. b2Vec2 p1 = pRef;
  59. b2Vec2 p2 = vs[i];
  60. b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0];
  61. b2Vec2 e1 = p2 - p1;
  62. b2Vec2 e2 = p3 - p1;
  63. float32 D = b2Cross(e1, e2);
  64. float32 triangleArea = 0.5f * D;
  65. area += triangleArea;
  66. // Area weighted centroid
  67. c += triangleArea * inv3 * (p1 + p2 + p3);
  68. }
  69. // Centroid
  70. b2Assert(area > B2_FLT_EPSILON);
  71. c *= 1.0f / area;
  72. return c;
  73. }
  74. // http://www.geometrictools.com/Documentation/MinimumAreaRectangle.pdf
  75. static void ComputeOBB(b2OBB* obb, const b2Vec2* vs, int32 count)
  76. {
  77. b2Assert(count <= b2_maxPolygonVertices);
  78. b2Vec2 p[b2_maxPolygonVertices + 1];
  79. for (int32 i = 0; i < count; ++i)
  80. {
  81. p[i] = vs[i];
  82. }
  83. p[count] = p[0];
  84. float32 minArea = B2_FLT_MAX;
  85. for (int32 i = 1; i <= count; ++i)
  86. {
  87. b2Vec2 root = p[i-1];
  88. b2Vec2 ux = p[i] - root;
  89. float32 length = ux.Normalize();
  90. b2Assert(length > B2_FLT_EPSILON);
  91. b2Vec2 uy(-ux.y, ux.x);
  92. b2Vec2 lower(B2_FLT_MAX, B2_FLT_MAX);
  93. b2Vec2 upper(-B2_FLT_MAX, -B2_FLT_MAX);
  94. for (int32 j = 0; j < count; ++j)
  95. {
  96. b2Vec2 d = p[j] - root;
  97. b2Vec2 r;
  98. r.x = b2Dot(ux, d);
  99. r.y = b2Dot(uy, d);
  100. lower = b2Min(lower, r);
  101. upper = b2Max(upper, r);
  102. }
  103. float32 area = (upper.x - lower.x) * (upper.y - lower.y);
  104. if (area < 0.95f * minArea)
  105. {
  106. minArea = area;
  107. obb->R.col1 = ux;
  108. obb->R.col2 = uy;
  109. b2Vec2 center = 0.5f * (lower + upper);
  110. obb->center = root + b2Mul(obb->R, center);
  111. obb->extents = 0.5f * (upper - lower);
  112. }
  113. }
  114. b2Assert(minArea < B2_FLT_MAX);
  115. }
  116. b2PolygonShape::b2PolygonShape(const b2ShapeDef* def)
  117. : b2Shape(def)
  118. {
  119. b2Assert(def->type == e_polygonShape);
  120. m_type = e_polygonShape;
  121. const b2PolygonDef* poly = (const b2PolygonDef*)def;
  122. // Get the vertices transformed into the body frame.
  123. m_vertexCount = poly->vertexCount;
  124. b2Assert(3 <= m_vertexCount && m_vertexCount <= b2_maxPolygonVertices);
  125. // Copy vertices.
  126. for (int32 i = 0; i < m_vertexCount; ++i)
  127. {
  128. m_vertices[i] = poly->vertices[i];
  129. }
  130. // Compute normals. Ensure the edges have non-zero length.
  131. for (int32 i = 0; i < m_vertexCount; ++i)
  132. {
  133. int32 i1 = i;
  134. int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0;
  135. b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
  136. b2Assert(edge.LengthSquared() > B2_FLT_EPSILON * B2_FLT_EPSILON);
  137. m_normals[i] = b2Cross(edge, 1.0f);
  138. m_normals[i].Normalize();
  139. }
  140. #ifdef _DEBUG
  141. // Ensure the polygon is convex.
  142. for (int32 i = 0; i < m_vertexCount; ++i)
  143. {
  144. for (int32 j = 0; j < m_vertexCount; ++j)
  145. {
  146. // Don't check vertices on the current edge.
  147. if (j == i || j == (i + 1) % m_vertexCount)
  148. {
  149. continue;
  150. }
  151. // Your polygon is non-convex (it has an indentation).
  152. // Or your polygon is too skinny.
  153. float32 s = b2Dot(m_normals[i], m_vertices[j] - m_vertices[i]);
  154. b2Assert(s < -b2_linearSlop);
  155. }
  156. }
  157. // Ensure the polygon is counter-clockwise.
  158. for (int32 i = 1; i < m_vertexCount; ++i)
  159. {
  160. float32 cross = b2Cross(m_normals[i-1], m_normals[i]);
  161. // Keep asinf happy.
  162. cross = b2Clamp(cross, -1.0f, 1.0f);
  163. // You have consecutive edges that are almost parallel on your polygon.
  164. float32 angle = asinf(cross);
  165. b2Assert(angle > b2_angularSlop);
  166. }
  167. #endif
  168. // Compute the polygon centroid.
  169. m_centroid = ComputeCentroid(poly->vertices, poly->vertexCount);
  170. // Compute the oriented bounding box.
  171. ComputeOBB(&m_obb, m_vertices, m_vertexCount);
  172. // Create core polygon shape by shifting edges inward.
  173. // Also compute the min/max radius for CCD.
  174. for (int32 i = 0; i < m_vertexCount; ++i)
  175. {
  176. int32 i1 = i - 1 >= 0 ? i - 1 : m_vertexCount - 1;
  177. int32 i2 = i;
  178. b2Vec2 n1 = m_normals[i1];
  179. b2Vec2 n2 = m_normals[i2];
  180. b2Vec2 v = m_vertices[i] - m_centroid;;
  181. b2Vec2 d;
  182. d.x = b2Dot(n1, v) - b2_toiSlop;
  183. d.y = b2Dot(n2, v) - b2_toiSlop;
  184. // Shifting the edge inward by b2_toiSlop should
  185. // not cause the plane to pass the centroid.
  186. // Your shape has a radius/extent less than b2_toiSlop.
  187. b2Assert(d.x >= 0.0f);
  188. b2Assert(d.y >= 0.0f);
  189. b2Mat22 A;
  190. A.col1.x = n1.x; A.col2.x = n1.y;
  191. A.col1.y = n2.x; A.col2.y = n2.y;
  192. m_coreVertices[i] = A.Solve(d) + m_centroid;
  193. }
  194. }
  195. void b2PolygonShape::UpdateSweepRadius(const b2Vec2& center)
  196. {
  197. // Update the sweep radius (maximum radius) as measured from
  198. // a local center point.
  199. m_sweepRadius = 0.0f;
  200. for (int32 i = 0; i < m_vertexCount; ++i)
  201. {
  202. b2Vec2 d = m_coreVertices[i] - center;
  203. m_sweepRadius = b2Max(m_sweepRadius, d.Length());
  204. }
  205. }
  206. bool b2PolygonShape::TestPoint(const b2XForm& xf, const b2Vec2& p) const
  207. {
  208. b2Vec2 pLocal = b2MulT(xf.R, p - xf.position);
  209. for (int32 i = 0; i < m_vertexCount; ++i)
  210. {
  211. float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
  212. if (dot > 0.0f)
  213. {
  214. return false;
  215. }
  216. }
  217. return true;
  218. }
  219. b2SegmentCollide b2PolygonShape::TestSegment(
  220. const b2XForm& xf,
  221. float32* lambda,
  222. b2Vec2* normal,
  223. const b2Segment& segment,
  224. float32 maxLambda) const
  225. {
  226. float32 lower = 0.0f, upper = maxLambda;
  227. b2Vec2 p1 = b2MulT(xf.R, segment.p1 - xf.position);
  228. b2Vec2 p2 = b2MulT(xf.R, segment.p2 - xf.position);
  229. b2Vec2 d = p2 - p1;
  230. int32 index = -1;
  231. for (int32 i = 0; i < m_vertexCount; ++i)
  232. {
  233. // p = p1 + a * d
  234. // dot(normal, p - v) = 0
  235. // dot(normal, p1 - v) + a * dot(normal, d) = 0
  236. float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
  237. float32 denominator = b2Dot(m_normals[i], d);
  238. if (denominator == 0.0f)
  239. {
  240. if (numerator < 0.0f)
  241. {
  242. return e_missCollide;
  243. }
  244. }
  245. else
  246. {
  247. // Note: we want this predicate without division:
  248. // lower < numerator / denominator, where denominator < 0
  249. // Since denominator < 0, we have to flip the inequality:
  250. // lower < numerator / denominator <==> denominator * lower > numerator.
  251. if (denominator < 0.0f && numerator < lower * denominator)
  252. {
  253. // Increase lower.
  254. // The segment enters this half-space.
  255. lower = numerator / denominator;
  256. index = i;
  257. }
  258. else if (denominator > 0.0f && numerator < upper * denominator)
  259. {
  260. // Decrease upper.
  261. // The segment exits this half-space.
  262. upper = numerator / denominator;
  263. }
  264. }
  265. if (upper < lower)
  266. {
  267. return e_missCollide;
  268. }
  269. }
  270. b2Assert(0.0f <= lower && lower <= maxLambda);
  271. if (index >= 0)
  272. {
  273. *lambda = lower;
  274. *normal = b2Mul(xf.R, m_normals[index]);
  275. return e_hitCollide;
  276. }
  277. *lambda = 0;
  278. return e_startsInsideCollide;
  279. }
  280. void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2XForm& xf) const
  281. {
  282. b2Mat22 R = b2Mul(xf.R, m_obb.R);
  283. b2Mat22 absR = b2Abs(R);
  284. b2Vec2 h = b2Mul(absR, m_obb.extents);
  285. b2Vec2 position = xf.position + b2Mul(xf.R, m_obb.center);
  286. aabb->lowerBound = position - h;
  287. aabb->upperBound = position + h;
  288. }
  289. void b2PolygonShape::ComputeSweptAABB(b2AABB* aabb,
  290. const b2XForm& transform1,
  291. const b2XForm& transform2) const
  292. {
  293. b2AABB aabb1, aabb2;
  294. ComputeAABB(&aabb1, transform1);
  295. ComputeAABB(&aabb2, transform2);
  296. aabb->lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound);
  297. aabb->upperBound = b2Max(aabb1.upperBound, aabb2.upperBound);
  298. }
  299. void b2PolygonShape::ComputeMass(b2MassData* massData) const
  300. {
  301. // Polygon mass, centroid, and inertia.
  302. // Let rho be the polygon density in mass per unit area.
  303. // Then:
  304. // mass = rho * int(dA)
  305. // centroid.x = (1/mass) * rho * int(x * dA)
  306. // centroid.y = (1/mass) * rho * int(y * dA)
  307. // I = rho * int((x*x + y*y) * dA)
  308. //
  309. // We can compute these integrals by summing all the integrals
  310. // for each triangle of the polygon. To evaluate the integral
  311. // for a single triangle, we make a change of variables to
  312. // the (u,v) coordinates of the triangle:
  313. // x = x0 + e1x * u + e2x * v
  314. // y = y0 + e1y * u + e2y * v
  315. // where 0 <= u && 0 <= v && u + v <= 1.
  316. //
  317. // We integrate u from [0,1-v] and then v from [0,1].
  318. // We also need to use the Jacobian of the transformation:
  319. // D = cross(e1, e2)
  320. //
  321. // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
  322. //
  323. // The rest of the derivation is handled by computer algebra.
  324. b2Assert(m_vertexCount >= 3);
  325. b2Vec2 center; center.Set(0.0f, 0.0f);
  326. float32 area = 0.0f;
  327. float32 I = 0.0f;
  328. // pRef is the reference point for forming triangles.
  329. // It's location doesn't change the result (except for rounding error).
  330. b2Vec2 pRef(0.0f, 0.0f);
  331. #if 0
  332. // This code would put the reference point inside the polygon.
  333. for (int32 i = 0; i < m_vertexCount; ++i)
  334. {
  335. pRef += m_vertices[i];
  336. }
  337. pRef *= 1.0f / count;
  338. #endif
  339. const float32 k_inv3 = 1.0f / 3.0f;
  340. for (int32 i = 0; i < m_vertexCount; ++i)
  341. {
  342. // Triangle vertices.
  343. b2Vec2 p1 = pRef;
  344. b2Vec2 p2 = m_vertices[i];
  345. b2Vec2 p3 = i + 1 < m_vertexCount ? m_vertices[i+1] : m_vertices[0];
  346. b2Vec2 e1 = p2 - p1;
  347. b2Vec2 e2 = p3 - p1;
  348. float32 D = b2Cross(e1, e2);
  349. float32 triangleArea = 0.5f * D;
  350. area += triangleArea;
  351. // Area weighted centroid
  352. center += triangleArea * k_inv3 * (p1 + p2 + p3);
  353. float32 px = p1.x, py = p1.y;
  354. float32 ex1 = e1.x, ey1 = e1.y;
  355. float32 ex2 = e2.x, ey2 = e2.y;
  356. float32 intx2 = k_inv3 * (0.25f * (ex1*ex1 + ex2*ex1 + ex2*ex2) + (px*ex1 + px*ex2)) + 0.5f*px*px;
  357. float32 inty2 = k_inv3 * (0.25f * (ey1*ey1 + ey2*ey1 + ey2*ey2) + (py*ey1 + py*ey2)) + 0.5f*py*py;
  358. I += D * (intx2 + inty2);
  359. }
  360. // Total mass
  361. massData->mass = m_density * area;
  362. // Center of mass
  363. b2Assert(area > B2_FLT_EPSILON);
  364. center *= 1.0f / area;
  365. massData->center = center;
  366. // Inertia tensor relative to the local origin.
  367. massData->I = m_density * I;
  368. }
  369. float32 b2PolygonShape::ComputeSubmergedArea( const b2Vec2& normal,
  370. float32 offset,
  371. const b2XForm& xf,
  372. b2Vec2* c) const
  373. {
  374. //Transform plane into shape co-ordinates
  375. b2Vec2 normalL = b2MulT(xf.R,normal);
  376. float32 offsetL = offset - b2Dot(normal,xf.position);
  377. float32 depths[b2_maxPolygonVertices];
  378. int32 diveCount = 0;
  379. int32 intoIndex = -1;
  380. int32 outoIndex = -1;
  381. bool lastSubmerged = false;
  382. int32 i;
  383. for(i=0;i<m_vertexCount;i++){
  384. depths[i] = b2Dot(normalL,m_vertices[i]) - offsetL;
  385. bool isSubmerged = depths[i]<-B2_FLT_EPSILON;
  386. if(i>0){
  387. if(isSubmerged){
  388. if(!lastSubmerged){
  389. intoIndex = i-1;
  390. diveCount++;
  391. }
  392. }else{
  393. if(lastSubmerged){
  394. outoIndex = i-1;
  395. diveCount++;
  396. }
  397. }
  398. }
  399. lastSubmerged = isSubmerged;
  400. }
  401. switch(diveCount){
  402. case 0:
  403. if(lastSubmerged){
  404. //Completely submerged
  405. b2MassData md;
  406. ComputeMass(&md);
  407. *c = b2Mul(xf,md.center);
  408. return md.mass/m_density;
  409. }else{
  410. //Completely dry
  411. return 0;
  412. }
  413. break;
  414. case 1:
  415. if(intoIndex==-1){
  416. intoIndex = m_vertexCount-1;
  417. }else{
  418. outoIndex = m_vertexCount-1;
  419. }
  420. break;
  421. }
  422. int32 intoIndex2 = (intoIndex+1)%m_vertexCount;
  423. int32 outoIndex2 = (outoIndex+1)%m_vertexCount;
  424. float32 intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]);
  425. float32 outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]);
  426. b2Vec2 intoVec( m_vertices[intoIndex].x*(1-intoLambda)+m_vertices[intoIndex2].x*intoLambda,
  427. m_vertices[intoIndex].y*(1-intoLambda)+m_vertices[intoIndex2].y*intoLambda);
  428. b2Vec2 outoVec( m_vertices[outoIndex].x*(1-outoLambda)+m_vertices[outoIndex2].x*outoLambda,
  429. m_vertices[outoIndex].y*(1-outoLambda)+m_vertices[outoIndex2].y*outoLambda);
  430. //Initialize accumulator
  431. float32 area = 0;
  432. b2Vec2 center(0,0);
  433. b2Vec2 p2 = m_vertices[intoIndex2];
  434. b2Vec2 p3;
  435. float32 k_inv3 = 1.0f / 3.0f;
  436. //An awkward loop from intoIndex2+1 to outIndex2
  437. i = intoIndex2;
  438. while(i!=outoIndex2){
  439. i=(i+1)%m_vertexCount;
  440. if(i==outoIndex2)
  441. p3 = outoVec;
  442. else
  443. p3 = m_vertices[i];
  444. //Add the triangle formed by intoVec,p2,p3
  445. {
  446. b2Vec2 e1 = p2 - intoVec;
  447. b2Vec2 e2 = p3 - intoVec;
  448. float32 D = b2Cross(e1, e2);
  449. float32 triangleArea = 0.5f * D;
  450. area += triangleArea;
  451. // Area weighted centroid
  452. center += triangleArea * k_inv3 * (intoVec + p2 + p3);
  453. }
  454. //
  455. p2=p3;
  456. }
  457. //Normalize and transform centroid
  458. center *= 1.0f/area;
  459. *c = b2Mul(xf,center);
  460. return area;
  461. }
  462. b2Vec2 b2PolygonShape::Centroid(const b2XForm& xf) const
  463. {
  464. return b2Mul(xf, m_centroid);
  465. }
  466. b2Vec2 b2PolygonShape::Support(const b2XForm& xf, const b2Vec2& d) const
  467. {
  468. b2Vec2 dLocal = b2MulT(xf.R, d);
  469. int32 bestIndex = 0;
  470. float32 bestValue = b2Dot(m_coreVertices[0], dLocal);
  471. for (int32 i = 1; i < m_vertexCount; ++i)
  472. {
  473. float32 value = b2Dot(m_coreVertices[i], dLocal);
  474. if (value > bestValue)
  475. {
  476. bestIndex = i;
  477. bestValue = value;
  478. }
  479. }
  480. return b2Mul(xf, m_coreVertices[bestIndex]);
  481. }