ConvexHullShape.cpp 38 KB

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