ConvexHullShape.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
  5. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  6. #include <Jolt/Physics/Collision/Shape/PolyhedronSubmergedVolumeCalculator.h>
  7. #include <Jolt/Physics/Collision/RayCast.h>
  8. #include <Jolt/Physics/Collision/CastResult.h>
  9. #include <Jolt/Physics/Collision/CollidePointResult.h>
  10. #include <Jolt/Physics/Collision/TransformedShape.h>
  11. #include <Jolt/Geometry/ConvexHullBuilder.h>
  12. #include <Jolt/ObjectStream/TypeDeclarations.h>
  13. #include <Jolt/Core/StringTools.h>
  14. #include <Jolt/Core/StreamIn.h>
  15. #include <Jolt/Core/StreamOut.h>
  16. #include <Jolt/Core/UnorderedMap.h>
  17. #include <Jolt/Core/UnorderedSet.h>
  18. JPH_NAMESPACE_BEGIN
  19. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(ConvexHullShapeSettings)
  20. {
  21. JPH_ADD_BASE_CLASS(ConvexHullShapeSettings, ConvexShapeSettings)
  22. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mPoints)
  23. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mMaxConvexRadius)
  24. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mMaxErrorConvexRadius)
  25. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mHullTolerance)
  26. }
  27. ShapeSettings::ShapeResult ConvexHullShapeSettings::Create() const
  28. {
  29. if (mCachedResult.IsEmpty())
  30. Ref<Shape> shape = new ConvexHullShape(*this, mCachedResult);
  31. return mCachedResult;
  32. }
  33. ConvexHullShape::ConvexHullShape(const ConvexHullShapeSettings &inSettings, ShapeResult &outResult) :
  34. ConvexShape(EShapeSubType::ConvexHull, inSettings, outResult),
  35. mConvexRadius(inSettings.mMaxConvexRadius)
  36. {
  37. using BuilderFace = ConvexHullBuilder::Face;
  38. using Edge = ConvexHullBuilder::Edge;
  39. using Faces = Array<BuilderFace *>;
  40. // Check convex radius
  41. if (mConvexRadius < 0.0f)
  42. {
  43. outResult.SetError("Invalid convex radius");
  44. return;
  45. }
  46. // Build convex hull
  47. const char *error = nullptr;
  48. ConvexHullBuilder builder(inSettings.mPoints);
  49. ConvexHullBuilder::EResult result = builder.Initialize(cMaxPointsInHull, inSettings.mHullTolerance, error);
  50. if (result != ConvexHullBuilder::EResult::Success && result != ConvexHullBuilder::EResult::MaxVerticesReached)
  51. {
  52. outResult.SetError(error);
  53. return;
  54. }
  55. const Faces &builder_faces = builder.GetFaces();
  56. // Check the consistency of the resulting hull if we fully built it
  57. if (result == ConvexHullBuilder::EResult::Success)
  58. {
  59. ConvexHullBuilder::Face *max_error_face;
  60. float max_error_distance, coplanar_distance;
  61. int max_error_idx;
  62. builder.DetermineMaxError(max_error_face, max_error_distance, max_error_idx, coplanar_distance);
  63. if (max_error_distance > 4.0f * max(coplanar_distance, inSettings.mHullTolerance)) // Coplanar distance could be bigger than the allowed tolerance if the points are far apart
  64. {
  65. outResult.SetError(StringFormat("Hull building failed, point %d had an error of %g (relative to tolerance: %g)", max_error_idx, (double)max_error_distance, double(max_error_distance / inSettings.mHullTolerance)));
  66. return;
  67. }
  68. }
  69. // Calculate center of mass and volume
  70. builder.GetCenterOfMassAndVolume(mCenterOfMass, mVolume);
  71. // Calculate covariance matrix
  72. // See:
  73. // - Why the inertia tensor is the inertia tensor - Jonathan Blow (http://number-none.com/blow/inertia/deriving_i.html)
  74. // - How to find the inertia tensor (or other mass properties) of a 3D solid body represented by a triangle mesh (Draft) - Jonathan Blow, Atman J Binstock (http://number-none.com/blow/inertia/bb_inertia.doc)
  75. Mat44 covariance_canonical(Vec4(1.0f / 60.0f, 1.0f / 120.0f, 1.0f / 120.0f, 0), Vec4(1.0f / 120.0f, 1.0f / 60.0f, 1.0f / 120.0f, 0), Vec4(1.0f / 120.0f, 1.0f / 120.0f, 1.0f / 60.0f, 0), Vec4(0, 0, 0, 1));
  76. Mat44 covariance_matrix = Mat44::sZero();
  77. for (BuilderFace *f : builder_faces)
  78. {
  79. // Fourth point of the tetrahedron is at the center of mass, we subtract it from the other points so we get a tetrahedron with one vertex at zero
  80. // The first point on the face will be used to form a triangle fan
  81. Edge *e = f->mFirstEdge;
  82. Vec3 v1 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  83. // Get the 2nd point
  84. e = e->mNextEdge;
  85. Vec3 v2 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  86. // Loop over the triangle fan
  87. for (e = e->mNextEdge; e != f->mFirstEdge; e = e->mNextEdge)
  88. {
  89. Vec3 v3 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  90. // Affine transform that transforms a unit tetrahedon (with vertices (0, 0, 0), (1, 0, 0), (0, 1, 0) and (0, 0, 1) to this tetrahedron
  91. Mat44 a(Vec4(v1, 0), Vec4(v2, 0), Vec4(v3, 0), Vec4(0, 0, 0, 1));
  92. // Calculate covariance matrix for this tetrahedron
  93. float det_a = a.GetDeterminant3x3();
  94. Mat44 c = det_a * (a * covariance_canonical * a.Transposed());
  95. // Add it
  96. covariance_matrix += c;
  97. // Prepare for next triangle
  98. v2 = v3;
  99. }
  100. }
  101. // Calculate inertia matrix assuming density is 1, note that element (3, 3) is garbage
  102. mInertia = Mat44::sIdentity() * (covariance_matrix(0, 0) + covariance_matrix(1, 1) + covariance_matrix(2, 2)) - covariance_matrix;
  103. // Convert polygons fron the builder to our internal representation
  104. using VtxMap = UnorderedMap<int, uint8>;
  105. VtxMap vertex_map;
  106. for (BuilderFace *builder_face : builder_faces)
  107. {
  108. // Determine where the vertices go
  109. uint16 first_vertex = (uint16)mVertexIdx.size();
  110. uint16 num_vertices = 0;
  111. // Loop over vertices in face
  112. Edge *edge = builder_face->mFirstEdge;
  113. do
  114. {
  115. // Remap to new index, not all points in the original input set are required to form the hull
  116. uint8 new_idx;
  117. int original_idx = edge->mStartIdx;
  118. VtxMap::iterator m = vertex_map.find(original_idx);
  119. if (m != vertex_map.end())
  120. {
  121. // Found, reuse
  122. new_idx = m->second;
  123. }
  124. else
  125. {
  126. // This is a new point
  127. // Make relative to center of mass
  128. Vec3 p = inSettings.mPoints[original_idx] - mCenterOfMass;
  129. // Update local bounds
  130. mLocalBounds.Encapsulate(p);
  131. // Add to point list
  132. JPH_ASSERT(mPoints.size() <= 0xff);
  133. new_idx = (uint8)mPoints.size();
  134. mPoints.push_back({ p });
  135. vertex_map[original_idx] = new_idx;
  136. }
  137. // Append to vertex list
  138. JPH_ASSERT(mVertexIdx.size() < 0xffff);
  139. mVertexIdx.push_back(new_idx);
  140. num_vertices++;
  141. edge = edge->mNextEdge;
  142. } while (edge != builder_face->mFirstEdge);
  143. // Add face
  144. mFaces.push_back({ first_vertex, num_vertices });
  145. // Add plane
  146. Plane plane = Plane::sFromPointAndNormal(builder_face->mCentroid - mCenterOfMass, builder_face->mNormal.Normalized());
  147. mPlanes.push_back(plane);
  148. }
  149. // Test if GetSupportFunction can support this many points
  150. if (mPoints.size() > cMaxPointsInHull)
  151. {
  152. outResult.SetError(StringFormat("Internal error: Too many points in hull (%d), max allowed %d", mPoints.size(), cMaxPointsInHull));
  153. return;
  154. }
  155. for (int p = 0; p < (int)mPoints.size(); ++p)
  156. {
  157. // For each point, find faces that use the point
  158. Array<int> faces;
  159. for (int f = 0; f < (int)mFaces.size(); ++f)
  160. {
  161. const Face &face = mFaces[f];
  162. for (int v = 0; v < face.mNumVertices; ++v)
  163. if (mVertexIdx[face.mFirstVertex + v] == p)
  164. {
  165. faces.push_back(f);
  166. break;
  167. }
  168. }
  169. if (faces.size() < 2)
  170. {
  171. outResult.SetError("A point must be connected to 2 or more faces!");
  172. return;
  173. }
  174. if (faces.size() > 1)
  175. {
  176. // Find the 3 normals that form the largest tetrahedron
  177. // The largest tetrahedron we can get is ((1, 0, 0) x (0, 1, 0)) . (0, 0, 1) = 1, if the volume is only 5% of that,
  178. // the three vectors are too coplanar and we fall back to using only 2 plane normals
  179. float biggest_volume = 0.05f;
  180. int best3[3] = { -1, -1, -1 };
  181. // When using 2 normals, we get the two with the biggest angle between them with a minimal difference of 1 degree
  182. // otherwise we fall back to just using 1 plane normal
  183. float smallest_dot = Cos(DegreesToRadians(1.0f));
  184. int best2[2] = { -1, -1 };
  185. for (int face1 = 0; face1 < (int)faces.size(); ++face1)
  186. {
  187. Vec3 normal1 = mPlanes[faces[face1]].GetNormal();
  188. for (int face2 = face1 + 1; face2 < (int)faces.size(); ++face2)
  189. {
  190. Vec3 normal2 = mPlanes[faces[face2]].GetNormal();
  191. Vec3 cross = normal1.Cross(normal2);
  192. // Determine the 2 face normals that are most apart
  193. float dot = normal1.Dot(normal2);
  194. if (dot < smallest_dot)
  195. {
  196. smallest_dot = dot;
  197. best2[0] = faces[face1];
  198. best2[1] = faces[face2];
  199. }
  200. // Determine the 3 face normals that form the largest tetrahedron
  201. for (int face3 = face2 + 1; face3 < (int)faces.size(); ++face3)
  202. {
  203. Vec3 normal3 = mPlanes[faces[face3]].GetNormal();
  204. float volume = abs(cross.Dot(normal3));
  205. if (volume > biggest_volume)
  206. {
  207. biggest_volume = volume;
  208. best3[0] = faces[face1];
  209. best3[1] = faces[face2];
  210. best3[2] = faces[face3];
  211. }
  212. }
  213. }
  214. }
  215. // If we didn't find 3 planes, use 2, if we didn't find 2 use 1
  216. if (best3[0] != -1)
  217. faces = { best3[0], best3[1], best3[2] };
  218. else if (best2[0] != -1)
  219. faces = { best2[0], best2[1] };
  220. else
  221. faces = { faces[0] };
  222. }
  223. // Copy the faces to the points buffer
  224. Point &point = mPoints[p];
  225. point.mNumFaces = (int)faces.size();
  226. for (int i = 0; i < (int)faces.size(); ++i)
  227. point.mFaces[i] = faces[i];
  228. }
  229. // If the convex radius is already zero, there's no point in further reducing it
  230. if (mConvexRadius > 0.0f)
  231. {
  232. // Find out how thin the hull is by walking over all planes and checking the thickness of the hull in that direction
  233. float min_size = FLT_MAX;
  234. for (const Plane &plane : mPlanes)
  235. {
  236. // Take the point that is furthest away from the plane as thickness of this hull
  237. float max_dist = 0.0f;
  238. for (const Point &point : mPoints)
  239. {
  240. float dist = -plane.SignedDistance(point.mPosition); // Point is always behind plane, so we need to negate
  241. if (dist > max_dist)
  242. max_dist = dist;
  243. }
  244. min_size = min(min_size, max_dist);
  245. }
  246. // We need to fit in 2x the convex radius in min_size, so reduce the convex radius if it's bigger than that
  247. mConvexRadius = min(mConvexRadius, 0.5f * min_size);
  248. }
  249. // Now walk over all points and see if we have to further reduce the convex radius because of sharp edges
  250. if (mConvexRadius > 0.0f)
  251. {
  252. for (const Point &point : mPoints)
  253. if (point.mNumFaces != 1) // If we have a single face, shifting back is easy and we don't need to reduce the convex radius
  254. {
  255. // Get first two planes
  256. Plane p1 = mPlanes[point.mFaces[0]];
  257. Plane p2 = mPlanes[point.mFaces[1]];
  258. Plane p3;
  259. Vec3 offset_mask;
  260. if (point.mNumFaces == 3)
  261. {
  262. // Get third plane
  263. p3 = mPlanes[point.mFaces[2]];
  264. // All 3 planes will be offset by the convex radius
  265. offset_mask = Vec3::sReplicate(1);
  266. }
  267. else
  268. {
  269. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  270. JPH_ASSERT(point.mNumFaces == 2);
  271. p3 = Plane::sFromPointAndNormal(point.mPosition, p1.GetNormal().Cross(p2.GetNormal()));
  272. // Only the first and 2nd plane will be offset, the 3rd plane is only there to guide the intersection point
  273. offset_mask = Vec3(1, 1, 0);
  274. }
  275. // Plane equation: point . normal + constant = 0
  276. // Offsetting the plane backwards with convex radius r: point . normal + constant + r = 0
  277. // To find the intersection 'point' of 3 planes we solve:
  278. // |n1x n1y n1z| |x| | r + c1 |
  279. // |n2x n2y n2z| |y| = - | r + c2 | <=> n point = -r (1, 1, 1) - (c1, c2, c3)
  280. // |n3x n3y n3z| |z| | r + c3 |
  281. // Where point = (x, y, z), n1x is the x component of the first plane, c1 = plane constant of plane 1, etc.
  282. // The relation between how much the interesection point shifts as a function of r is: -r * n^-1 (1, 1, 1) = r * offset
  283. // Where offset = -n^-1 (1, 1, 1) or -n^-1 (1, 1, 0) in case only the first 2 planes are offset
  284. // The error that is introduced by a convex radius r is: error = r * |offset| - r
  285. // So the max convex radius given error is: r = error / (|offset| - 1)
  286. Mat44 n = Mat44(Vec4(p1.GetNormal(), 0), Vec4(p2.GetNormal(), 0), Vec4(p3.GetNormal(), 0), Vec4(0, 0, 0, 1)).Transposed();
  287. float det_n = n.GetDeterminant3x3();
  288. if (det_n == 0.0f)
  289. {
  290. // If the determinant is zero, the matrix is not invertible so no solution exists to move the point backwards and we have to choose a convex radius of zero
  291. mConvexRadius = 0.0f;
  292. break;
  293. }
  294. Mat44 adj_n = n.Adjointed3x3();
  295. float offset = ((adj_n * offset_mask) / det_n).Length();
  296. JPH_ASSERT(offset > 1.0f);
  297. float max_convex_radius = inSettings.mMaxErrorConvexRadius / (offset - 1.0f);
  298. mConvexRadius = min(mConvexRadius, max_convex_radius);
  299. }
  300. }
  301. // Calculate the inner radius by getting the minimum distance from the origin to the planes of the hull
  302. mInnerRadius = FLT_MAX;
  303. for (const Plane &p : mPlanes)
  304. mInnerRadius = min(mInnerRadius, -p.GetConstant());
  305. mInnerRadius = max(0.0f, mInnerRadius); // Clamp against zero, this should do nothing as the shape is centered around the center of mass but for flat convex hulls there may be numerical round off issues
  306. outResult.Set(this);
  307. }
  308. MassProperties ConvexHullShape::GetMassProperties() const
  309. {
  310. MassProperties p;
  311. float density = GetDensity();
  312. // Calculate mass
  313. p.mMass = density * mVolume;
  314. // Calculate inertia matrix
  315. p.mInertia = density * mInertia;
  316. p.mInertia(3, 3) = 1.0f;
  317. return p;
  318. }
  319. Vec3 ConvexHullShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  320. {
  321. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  322. const Plane &first_plane = mPlanes[0];
  323. Vec3 best_normal = first_plane.GetNormal();
  324. float best_dist = abs(first_plane.SignedDistance(inLocalSurfacePosition));
  325. // Find the face that has the shortest distance to the surface point
  326. for (Array<Face>::size_type i = 1; i < mFaces.size(); ++i)
  327. {
  328. const Plane &plane = mPlanes[i];
  329. Vec3 plane_normal = plane.GetNormal();
  330. float dist = abs(plane.SignedDistance(inLocalSurfacePosition));
  331. if (dist < best_dist)
  332. {
  333. best_dist = dist;
  334. best_normal = plane_normal;
  335. }
  336. }
  337. return best_normal;
  338. }
  339. class ConvexHullShape::HullNoConvex final : public Support
  340. {
  341. public:
  342. explicit HullNoConvex(float inConvexRadius) :
  343. mConvexRadius(inConvexRadius)
  344. {
  345. static_assert(sizeof(HullNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  346. JPH_ASSERT(IsAligned(this, alignof(HullNoConvex)));
  347. }
  348. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  349. {
  350. // Find the point with the highest projection on inDirection
  351. float best_dot = -FLT_MAX;
  352. Vec3 best_point = Vec3::sZero();
  353. for (Vec3 point : mPoints)
  354. {
  355. // Check if its support is bigger than the current max
  356. float dot = point.Dot(inDirection);
  357. if (dot > best_dot)
  358. {
  359. best_dot = dot;
  360. best_point = point;
  361. }
  362. }
  363. return best_point;
  364. }
  365. virtual float GetConvexRadius() const override
  366. {
  367. return mConvexRadius;
  368. }
  369. using PointsArray = StaticArray<Vec3, cMaxPointsInHull>;
  370. inline PointsArray & GetPoints()
  371. {
  372. return mPoints;
  373. }
  374. const PointsArray & GetPoints() const
  375. {
  376. return mPoints;
  377. }
  378. private:
  379. float mConvexRadius;
  380. PointsArray mPoints;
  381. };
  382. class ConvexHullShape::HullWithConvex final : public Support
  383. {
  384. public:
  385. explicit HullWithConvex(const ConvexHullShape *inShape) :
  386. mShape(inShape)
  387. {
  388. static_assert(sizeof(HullWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  389. JPH_ASSERT(IsAligned(this, alignof(HullWithConvex)));
  390. }
  391. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  392. {
  393. // Find the point with the highest projection on inDirection
  394. float best_dot = -FLT_MAX;
  395. Vec3 best_point = Vec3::sZero();
  396. for (const Point &point : mShape->mPoints)
  397. {
  398. // Check if its support is bigger than the current max
  399. float dot = point.mPosition.Dot(inDirection);
  400. if (dot > best_dot)
  401. {
  402. best_dot = dot;
  403. best_point = point.mPosition;
  404. }
  405. }
  406. return best_point;
  407. }
  408. virtual float GetConvexRadius() const override
  409. {
  410. return 0.0f;
  411. }
  412. private:
  413. const ConvexHullShape * mShape;
  414. };
  415. class ConvexHullShape::HullWithConvexScaled final : public Support
  416. {
  417. public:
  418. HullWithConvexScaled(const ConvexHullShape *inShape, Vec3Arg inScale) :
  419. mShape(inShape),
  420. mScale(inScale)
  421. {
  422. static_assert(sizeof(HullWithConvexScaled) <= sizeof(SupportBuffer), "Buffer size too small");
  423. JPH_ASSERT(IsAligned(this, alignof(HullWithConvexScaled)));
  424. }
  425. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  426. {
  427. // Find the point with the highest projection on inDirection
  428. float best_dot = -FLT_MAX;
  429. Vec3 best_point = Vec3::sZero();
  430. for (const Point &point : mShape->mPoints)
  431. {
  432. // Calculate scaled position
  433. Vec3 pos = mScale * point.mPosition;
  434. // Check if its support is bigger than the current max
  435. float dot = pos.Dot(inDirection);
  436. if (dot > best_dot)
  437. {
  438. best_dot = dot;
  439. best_point = pos;
  440. }
  441. }
  442. return best_point;
  443. }
  444. virtual float GetConvexRadius() const override
  445. {
  446. return 0.0f;
  447. }
  448. private:
  449. const ConvexHullShape * mShape;
  450. Vec3 mScale;
  451. };
  452. const ConvexShape::Support *ConvexHullShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  453. {
  454. // If there's no convex radius, we don't need to shrink the hull
  455. if (mConvexRadius == 0.0f)
  456. {
  457. if (ScaleHelpers::IsNotScaled(inScale))
  458. return new (&inBuffer) HullWithConvex(this);
  459. else
  460. return new (&inBuffer) HullWithConvexScaled(this, inScale);
  461. }
  462. switch (inMode)
  463. {
  464. case ESupportMode::IncludeConvexRadius:
  465. if (ScaleHelpers::IsNotScaled(inScale))
  466. return new (&inBuffer) HullWithConvex(this);
  467. else
  468. return new (&inBuffer) HullWithConvexScaled(this, inScale);
  469. case ESupportMode::ExcludeConvexRadius:
  470. if (ScaleHelpers::IsNotScaled(inScale))
  471. {
  472. // Create support function
  473. HullNoConvex *hull = new (&inBuffer) HullNoConvex(mConvexRadius);
  474. HullNoConvex::PointsArray &transformed_points = hull->GetPoints();
  475. JPH_ASSERT(mPoints.size() <= cMaxPointsInHull, "Not enough space, this should have been caught during shape creation!");
  476. for (const Point &point : mPoints)
  477. {
  478. Vec3 new_point;
  479. if (point.mNumFaces == 1)
  480. {
  481. // Simply shift back by the convex radius using our 1 plane
  482. new_point = point.mPosition - mPlanes[point.mFaces[0]].GetNormal() * mConvexRadius;
  483. }
  484. else
  485. {
  486. // Get first two planes and offset inwards by convex radius
  487. Plane p1 = mPlanes[point.mFaces[0]].Offset(-mConvexRadius);
  488. Plane p2 = mPlanes[point.mFaces[1]].Offset(-mConvexRadius);
  489. Plane p3;
  490. if (point.mNumFaces == 3)
  491. {
  492. // Get third plane and offset inwards by convex radius
  493. p3 = mPlanes[point.mFaces[2]].Offset(-mConvexRadius);
  494. }
  495. else
  496. {
  497. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  498. JPH_ASSERT(point.mNumFaces == 2);
  499. p3 = Plane::sFromPointAndNormal(point.mPosition, p1.GetNormal().Cross(p2.GetNormal()));
  500. }
  501. // Find intersection point between the three planes
  502. if (!Plane::sIntersectPlanes(p1, p2, p3, new_point))
  503. {
  504. // Fallback: Just push point back using the first plane
  505. new_point = point.mPosition - p1.GetNormal() * mConvexRadius;
  506. }
  507. }
  508. // Add point
  509. transformed_points.push_back(new_point);
  510. }
  511. return hull;
  512. }
  513. else
  514. {
  515. // Calculate scaled convex radius
  516. float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  517. // Create new support function
  518. HullNoConvex *hull = new (&inBuffer) HullNoConvex(convex_radius);
  519. HullNoConvex::PointsArray &transformed_points = hull->GetPoints();
  520. JPH_ASSERT(mPoints.size() <= cMaxPointsInHull, "Not enough space, this should have been caught during shape creation!");
  521. // Precalculate inverse scale
  522. Vec3 inv_scale = inScale.Reciprocal();
  523. for (const Point &point : mPoints)
  524. {
  525. // Calculate scaled position
  526. Vec3 pos = inScale * point.mPosition;
  527. // Transform normals for plane 1 with scale
  528. Vec3 n1 = (inv_scale * mPlanes[point.mFaces[0]].GetNormal()).Normalized();
  529. Vec3 new_point;
  530. if (point.mNumFaces == 1)
  531. {
  532. // Simply shift back by the convex radius using our 1 plane
  533. new_point = pos - n1 * convex_radius;
  534. }
  535. else
  536. {
  537. // Transform normals for plane 2 with scale
  538. Vec3 n2 = (inv_scale * mPlanes[point.mFaces[1]].GetNormal()).Normalized();
  539. // Get first two planes and offset inwards by convex radius
  540. Plane p1 = Plane::sFromPointAndNormal(pos, n1).Offset(-convex_radius);
  541. Plane p2 = Plane::sFromPointAndNormal(pos, n2).Offset(-convex_radius);
  542. Plane p3;
  543. if (point.mNumFaces == 3)
  544. {
  545. // Transform last normal with scale
  546. Vec3 n3 = (inv_scale * mPlanes[point.mFaces[2]].GetNormal()).Normalized();
  547. // Get third plane and offset inwards by convex radius
  548. p3 = Plane::sFromPointAndNormal(pos, n3).Offset(-convex_radius);
  549. }
  550. else
  551. {
  552. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  553. JPH_ASSERT(point.mNumFaces == 2);
  554. p3 = Plane::sFromPointAndNormal(pos, n1.Cross(n2));
  555. }
  556. // Find intersection point between the three planes
  557. if (!Plane::sIntersectPlanes(p1, p2, p3, new_point))
  558. {
  559. // Fallback: Just push point back using the first plane
  560. new_point = pos - n1 * convex_radius;
  561. }
  562. }
  563. // Add point
  564. transformed_points.push_back(new_point);
  565. }
  566. return hull;
  567. }
  568. }
  569. JPH_ASSERT(false);
  570. return nullptr;
  571. }
  572. void ConvexHullShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  573. {
  574. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  575. Vec3 inv_scale = inScale.Reciprocal();
  576. // Need to transform the plane normals using inScale
  577. // Transforming a direction with matrix M is done through multiplying by (M^-1)^T
  578. // In this case M is a diagonal matrix with the scale vector, so we need to multiply our normal by 1 / scale and renormalize afterwards
  579. Vec3 plane0_normal = inv_scale * mPlanes[0].GetNormal();
  580. float best_dot = plane0_normal.Dot(inDirection) / plane0_normal.Length();
  581. int best_face_idx = 0;
  582. for (Array<Plane>::size_type i = 1; i < mPlanes.size(); ++i)
  583. {
  584. Vec3 plane_normal = inv_scale * mPlanes[i].GetNormal();
  585. float dot = plane_normal.Dot(inDirection) / plane_normal.Length();
  586. if (dot < best_dot)
  587. {
  588. best_dot = dot;
  589. best_face_idx = (int)i;
  590. }
  591. }
  592. // Get vertices
  593. const Face &best_face = mFaces[best_face_idx];
  594. const uint8 *first_vtx = mVertexIdx.data() + best_face.mFirstVertex;
  595. const uint8 *end_vtx = first_vtx + best_face.mNumVertices;
  596. // If we have more than 1/2 the capacity of outVertices worth of vertices, we start skipping vertices (note we can't fill the buffer completely since extra edges will be generated by clipping).
  597. // TODO: This really needs a better algorithm to determine which vertices are important!
  598. int max_vertices_to_return = outVertices.capacity() / 2;
  599. int delta_vtx = (int(best_face.mNumVertices) + max_vertices_to_return) / max_vertices_to_return;
  600. // Calculate transform with scale
  601. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  602. if (ScaleHelpers::IsInsideOut(inScale))
  603. {
  604. // Flip winding of supporting face
  605. for (const uint8 *v = end_vtx - 1; v >= first_vtx; v -= delta_vtx)
  606. outVertices.push_back(transform * mPoints[*v].mPosition);
  607. }
  608. else
  609. {
  610. // Normal winding of supporting face
  611. for (const uint8 *v = first_vtx; v < end_vtx; v += delta_vtx)
  612. outVertices.push_back(transform * mPoints[*v].mPosition);
  613. }
  614. }
  615. void ConvexHullShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  616. {
  617. // Trivially calculate total volume
  618. Vec3 abs_scale = inScale.Abs();
  619. outTotalVolume = mVolume * abs_scale.GetX() * abs_scale.GetY() * abs_scale.GetZ();
  620. // Check if shape has been scaled inside out
  621. bool is_inside_out = ScaleHelpers::IsInsideOut(inScale);
  622. // Convert the points to world space and determine the distance to the surface
  623. int num_points = int(mPoints.size());
  624. PolyhedronSubmergedVolumeCalculator::Point *buffer = (PolyhedronSubmergedVolumeCalculator::Point *)JPH_STACK_ALLOC(num_points * sizeof(PolyhedronSubmergedVolumeCalculator::Point));
  625. PolyhedronSubmergedVolumeCalculator submerged_vol_calc(inCenterOfMassTransform * Mat44::sScale(inScale), &mPoints[0].mPosition, sizeof(Point), num_points, inSurface, buffer JPH_IF_DEBUG_RENDERER(, inBaseOffset));
  626. if (submerged_vol_calc.AreAllAbove())
  627. {
  628. // We're above the water
  629. outSubmergedVolume = 0.0f;
  630. outCenterOfBuoyancy = Vec3::sZero();
  631. }
  632. else if (submerged_vol_calc.AreAllBelow())
  633. {
  634. // We're fully submerged
  635. outSubmergedVolume = outTotalVolume;
  636. outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation();
  637. }
  638. else
  639. {
  640. // Calculate submerged volume
  641. int reference_point_idx = submerged_vol_calc.GetReferencePointIdx();
  642. for (const Face &f : mFaces)
  643. {
  644. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  645. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  646. // If any of the vertices of this face are the reference point, the volume will be zero so we can skip this face
  647. bool degenerate = false;
  648. for (const uint8 *v = first_vtx; v < end_vtx; ++v)
  649. if (*v == reference_point_idx)
  650. {
  651. degenerate = true;
  652. break;
  653. }
  654. if (degenerate)
  655. continue;
  656. // Triangulate the face
  657. int i1 = *first_vtx;
  658. if (is_inside_out)
  659. {
  660. // Reverse winding
  661. for (const uint8 *v = first_vtx + 2; v < end_vtx; ++v)
  662. {
  663. int i2 = *(v - 1);
  664. int i3 = *v;
  665. submerged_vol_calc.AddFace(i1, i3, i2);
  666. }
  667. }
  668. else
  669. {
  670. // Normal winding
  671. for (const uint8 *v = first_vtx + 2; v < end_vtx; ++v)
  672. {
  673. int i2 = *(v - 1);
  674. int i3 = *v;
  675. submerged_vol_calc.AddFace(i1, i2, i3);
  676. }
  677. }
  678. }
  679. // Get the results
  680. submerged_vol_calc.GetResult(outSubmergedVolume, outCenterOfBuoyancy);
  681. }
  682. #ifdef JPH_DEBUG_RENDERER
  683. // Draw center of buoyancy
  684. if (sDrawSubmergedVolumes)
  685. DebugRenderer::sInstance->DrawWireSphere(inBaseOffset + outCenterOfBuoyancy, 0.05f, Color::sRed, 1);
  686. #endif // JPH_DEBUG_RENDERER
  687. }
  688. #ifdef JPH_DEBUG_RENDERER
  689. void ConvexHullShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  690. {
  691. if (mGeometry == nullptr)
  692. {
  693. Array<DebugRenderer::Triangle> triangles;
  694. for (const Face &f : mFaces)
  695. {
  696. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  697. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  698. // Draw first triangle of polygon
  699. Vec3 v0 = mPoints[first_vtx[0]].mPosition;
  700. Vec3 v1 = mPoints[first_vtx[1]].mPosition;
  701. Vec3 v2 = mPoints[first_vtx[2]].mPosition;
  702. Vec3 uv_direction = (v1 - v0).Normalized();
  703. triangles.push_back({ v0, v1, v2, Color::sWhite, v0, uv_direction });
  704. // Draw any other triangles in this polygon
  705. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  706. triangles.push_back({ v0, mPoints[*(v - 1)].mPosition, mPoints[*v].mPosition, Color::sWhite, v0, uv_direction });
  707. }
  708. mGeometry = new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), GetLocalBounds());
  709. }
  710. // Test if the shape is scaled inside out
  711. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  712. // Determine the draw mode
  713. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  714. // Draw the geometry
  715. Color color = inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor;
  716. RMat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  717. inRenderer->DrawGeometry(transform, color, mGeometry, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  718. // Draw the outline if requested
  719. if (sDrawFaceOutlines)
  720. for (const Face &f : mFaces)
  721. {
  722. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  723. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  724. // Draw edges of face
  725. inRenderer->DrawLine(transform * mPoints[*(end_vtx - 1)].mPosition, transform * mPoints[*first_vtx].mPosition, Color::sGrey);
  726. for (const uint8 *v = first_vtx + 1; v < end_vtx; ++v)
  727. inRenderer->DrawLine(transform * mPoints[*(v - 1)].mPosition, transform * mPoints[*v].mPosition, Color::sGrey);
  728. }
  729. }
  730. void ConvexHullShape::DrawShrunkShape(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  731. {
  732. // Get the shrunk points
  733. SupportBuffer buffer;
  734. const HullNoConvex *support = mConvexRadius > 0.0f? static_cast<const HullNoConvex *>(GetSupportFunction(ESupportMode::ExcludeConvexRadius, buffer, inScale)) : nullptr;
  735. RMat44 transform = inCenterOfMassTransform * Mat44::sScale(inScale);
  736. for (int p = 0; p < (int)mPoints.size(); ++p)
  737. {
  738. const Point &point = mPoints[p];
  739. RVec3 position = transform * point.mPosition;
  740. RVec3 shrunk_point = support != nullptr? transform * support->GetPoints()[p] : position;
  741. // Draw difference between shrunk position and position
  742. inRenderer->DrawLine(position, shrunk_point, Color::sGreen);
  743. // Draw face normals that are contributing
  744. for (int i = 0; i < point.mNumFaces; ++i)
  745. inRenderer->DrawLine(position, position + 0.1f * mPlanes[point.mFaces[i]].GetNormal(), Color::sYellow);
  746. // Draw point index
  747. inRenderer->DrawText3D(position, ConvertToString(p), Color::sWhite, 0.1f);
  748. }
  749. }
  750. #endif // JPH_DEBUG_RENDERER
  751. bool ConvexHullShape::CastRayHelper(const RayCast &inRay, float &outMinFraction, float &outMaxFraction) const
  752. {
  753. if (mFaces.size() == 2)
  754. {
  755. // If we have only 2 faces, we're a flat convex hull and we need to test edges instead of planes
  756. // Check if plane is parallel to ray
  757. const Plane &p = mPlanes.front();
  758. Vec3 plane_normal = p.GetNormal();
  759. float direction_projection = inRay.mDirection.Dot(plane_normal);
  760. if (abs(direction_projection) >= 1.0e-12f)
  761. {
  762. // Calculate intersection point
  763. float distance_to_plane = inRay.mOrigin.Dot(plane_normal) + p.GetConstant();
  764. float fraction = -distance_to_plane / direction_projection;
  765. if (fraction < 0.0f || fraction > 1.0f)
  766. {
  767. // Does not hit plane, no hit
  768. outMinFraction = 0.0f;
  769. outMaxFraction = 1.0f + FLT_EPSILON;
  770. return false;
  771. }
  772. Vec3 intersection_point = inRay.mOrigin + fraction * inRay.mDirection;
  773. // Test all edges to see if point is inside polygon
  774. const Face &f = mFaces.front();
  775. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  776. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  777. Vec3 p1 = mPoints[*end_vtx].mPosition;
  778. for (const uint8 *v = first_vtx; v < end_vtx; ++v)
  779. {
  780. Vec3 p2 = mPoints[*v].mPosition;
  781. if ((p2 - p1).Cross(intersection_point - p1).Dot(plane_normal) < 0.0f)
  782. {
  783. // Outside polygon, no hit
  784. outMinFraction = 0.0f;
  785. outMaxFraction = 1.0f + FLT_EPSILON;
  786. return false;
  787. }
  788. p1 = p2;
  789. }
  790. // Inside polygon, a hit
  791. outMinFraction = fraction;
  792. outMaxFraction = fraction;
  793. return true;
  794. }
  795. else
  796. {
  797. // Parallel ray doesn't hit
  798. outMinFraction = 0.0f;
  799. outMaxFraction = 1.0f + FLT_EPSILON;
  800. return false;
  801. }
  802. }
  803. else
  804. {
  805. // Clip ray against all planes
  806. int fractions_set = 0;
  807. bool all_inside = true;
  808. float min_fraction = 0.0f, max_fraction = 1.0f + FLT_EPSILON;
  809. for (const Plane &p : mPlanes)
  810. {
  811. // Check if the ray origin is behind this plane
  812. Vec3 plane_normal = p.GetNormal();
  813. float distance_to_plane = inRay.mOrigin.Dot(plane_normal) + p.GetConstant();
  814. bool is_outside = distance_to_plane > 0.0f;
  815. all_inside &= !is_outside;
  816. // Check if plane is parallel to ray
  817. float direction_projection = inRay.mDirection.Dot(plane_normal);
  818. if (abs(direction_projection) >= 1.0e-12f)
  819. {
  820. // Get intersection fraction between ray and plane
  821. float fraction = -distance_to_plane / direction_projection;
  822. // Update interval of ray that is inside the hull
  823. if (direction_projection < 0.0f)
  824. {
  825. min_fraction = max(fraction, min_fraction);
  826. fractions_set |= 1;
  827. }
  828. else
  829. {
  830. max_fraction = min(fraction, max_fraction);
  831. fractions_set |= 2;
  832. }
  833. }
  834. else if (is_outside)
  835. return false; // Outside the plane and parallel, no hit!
  836. }
  837. // Test if both min and max have been set
  838. if (fractions_set == 3)
  839. {
  840. // Output fractions
  841. outMinFraction = min_fraction;
  842. outMaxFraction = max_fraction;
  843. // Test if the infinite ray intersects with the hull (the length will be checked later)
  844. return min_fraction <= max_fraction && max_fraction >= 0.0f;
  845. }
  846. else
  847. {
  848. // Degenerate case, either the ray is parallel to all planes or the ray has zero length
  849. outMinFraction = 0.0f;
  850. outMaxFraction = 1.0f + FLT_EPSILON;
  851. // Return if the origin is inside the hull
  852. return all_inside;
  853. }
  854. }
  855. }
  856. bool ConvexHullShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  857. {
  858. // Determine if ray hits the shape
  859. float min_fraction, max_fraction;
  860. if (CastRayHelper(inRay, min_fraction, max_fraction)
  861. && min_fraction < ioHit.mFraction) // Check if this is a closer hit
  862. {
  863. // Better hit than the current hit
  864. ioHit.mFraction = min_fraction;
  865. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  866. return true;
  867. }
  868. return false;
  869. }
  870. void ConvexHullShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  871. {
  872. // Test shape filter
  873. if (!inShapeFilter.ShouldCollide(inSubShapeIDCreator.GetID()))
  874. return;
  875. // Determine if ray hits the shape
  876. float min_fraction, max_fraction;
  877. if (CastRayHelper(inRay, min_fraction, max_fraction)
  878. && min_fraction < ioCollector.GetEarlyOutFraction()) // Check if this is closer than the early out fraction
  879. {
  880. // Better hit than the current hit
  881. RayCastResult hit;
  882. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  883. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  884. // Check front side hit
  885. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  886. {
  887. hit.mFraction = min_fraction;
  888. ioCollector.AddHit(hit);
  889. }
  890. // Check back side hit
  891. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  892. && max_fraction < ioCollector.GetEarlyOutFraction())
  893. {
  894. hit.mFraction = max_fraction;
  895. ioCollector.AddHit(hit);
  896. }
  897. }
  898. }
  899. void ConvexHullShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  900. {
  901. // Test shape filter
  902. if (!inShapeFilter.ShouldCollide(inSubShapeIDCreator.GetID()))
  903. return;
  904. // Check if point is behind all planes
  905. for (const Plane &p : mPlanes)
  906. if (p.SignedDistance(inPoint) > 0.0f)
  907. return;
  908. // Point is inside
  909. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  910. }
  911. class ConvexHullShape::CHSGetTrianglesContext
  912. {
  913. public:
  914. CHSGetTrianglesContext(Mat44Arg inTransform, bool inIsInsideOut) : mTransform(inTransform), mIsInsideOut(inIsInsideOut) { }
  915. Mat44 mTransform;
  916. bool mIsInsideOut;
  917. size_t mCurrentFace = 0;
  918. };
  919. void ConvexHullShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  920. {
  921. static_assert(sizeof(CHSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  922. JPH_ASSERT(IsAligned(&ioContext, alignof(CHSGetTrianglesContext)));
  923. new (&ioContext) CHSGetTrianglesContext(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale), ScaleHelpers::IsInsideOut(inScale));
  924. }
  925. int ConvexHullShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  926. {
  927. static_assert(cGetTrianglesMinTrianglesRequested >= 12, "cGetTrianglesMinTrianglesRequested is too small");
  928. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  929. CHSGetTrianglesContext &context = (CHSGetTrianglesContext &)ioContext;
  930. int total_num_triangles = 0;
  931. for (; context.mCurrentFace < mFaces.size(); ++context.mCurrentFace)
  932. {
  933. const Face &f = mFaces[context.mCurrentFace];
  934. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  935. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  936. // Check if there is still room in the output buffer for this face
  937. int num_triangles = f.mNumVertices - 2;
  938. inMaxTrianglesRequested -= num_triangles;
  939. if (inMaxTrianglesRequested < 0)
  940. break;
  941. total_num_triangles += num_triangles;
  942. // Get first triangle of polygon
  943. Vec3 v0 = context.mTransform * mPoints[first_vtx[0]].mPosition;
  944. Vec3 v1 = context.mTransform * mPoints[first_vtx[1]].mPosition;
  945. Vec3 v2 = context.mTransform * mPoints[first_vtx[2]].mPosition;
  946. v0.StoreFloat3(outTriangleVertices++);
  947. if (context.mIsInsideOut)
  948. {
  949. // Store first triangle in this polygon flipped
  950. v2.StoreFloat3(outTriangleVertices++);
  951. v1.StoreFloat3(outTriangleVertices++);
  952. // Store other triangles in this polygon flipped
  953. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  954. {
  955. v0.StoreFloat3(outTriangleVertices++);
  956. (context.mTransform * mPoints[*v].mPosition).StoreFloat3(outTriangleVertices++);
  957. (context.mTransform * mPoints[*(v - 1)].mPosition).StoreFloat3(outTriangleVertices++);
  958. }
  959. }
  960. else
  961. {
  962. // Store first triangle in this polygon
  963. v1.StoreFloat3(outTriangleVertices++);
  964. v2.StoreFloat3(outTriangleVertices++);
  965. // Store other triangles in this polygon
  966. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  967. {
  968. v0.StoreFloat3(outTriangleVertices++);
  969. (context.mTransform * mPoints[*(v - 1)].mPosition).StoreFloat3(outTriangleVertices++);
  970. (context.mTransform * mPoints[*v].mPosition).StoreFloat3(outTriangleVertices++);
  971. }
  972. }
  973. }
  974. // Store materials
  975. if (outMaterials != nullptr)
  976. {
  977. const PhysicsMaterial *material = GetMaterial();
  978. for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
  979. *m = material;
  980. }
  981. return total_num_triangles;
  982. }
  983. void ConvexHullShape::SaveBinaryState(StreamOut &inStream) const
  984. {
  985. ConvexShape::SaveBinaryState(inStream);
  986. inStream.Write(mCenterOfMass);
  987. inStream.Write(mInertia);
  988. inStream.Write(mLocalBounds.mMin);
  989. inStream.Write(mLocalBounds.mMax);
  990. inStream.Write(mPoints);
  991. inStream.Write(mFaces);
  992. inStream.Write(mPlanes);
  993. inStream.Write(mVertexIdx);
  994. inStream.Write(mConvexRadius);
  995. inStream.Write(mVolume);
  996. inStream.Write(mInnerRadius);
  997. }
  998. void ConvexHullShape::RestoreBinaryState(StreamIn &inStream)
  999. {
  1000. ConvexShape::RestoreBinaryState(inStream);
  1001. inStream.Read(mCenterOfMass);
  1002. inStream.Read(mInertia);
  1003. inStream.Read(mLocalBounds.mMin);
  1004. inStream.Read(mLocalBounds.mMax);
  1005. inStream.Read(mPoints);
  1006. inStream.Read(mFaces);
  1007. inStream.Read(mPlanes);
  1008. inStream.Read(mVertexIdx);
  1009. inStream.Read(mConvexRadius);
  1010. inStream.Read(mVolume);
  1011. inStream.Read(mInnerRadius);
  1012. }
  1013. Shape::Stats ConvexHullShape::GetStats() const
  1014. {
  1015. // Count number of triangles
  1016. uint triangle_count = 0;
  1017. for (const Face &f : mFaces)
  1018. triangle_count += f.mNumVertices - 2;
  1019. return Stats(
  1020. sizeof(*this)
  1021. + mPoints.size() * sizeof(Point)
  1022. + mFaces.size() * sizeof(Face)
  1023. + mPlanes.size() * sizeof(Plane)
  1024. + mVertexIdx.size() * sizeof(uint8),
  1025. triangle_count);
  1026. }
  1027. void ConvexHullShape::sRegister()
  1028. {
  1029. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::ConvexHull);
  1030. f.mConstruct = []() -> Shape * { return new ConvexHullShape; };
  1031. f.mColor = Color::sGreen;
  1032. }
  1033. JPH_NAMESPACE_END