MeshShape.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ConvexShape.h>
  7. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  8. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  9. #include <Jolt/Physics/Collision/RayCast.h>
  10. #include <Jolt/Physics/Collision/ShapeCast.h>
  11. #include <Jolt/Physics/Collision/ShapeFilter.h>
  12. #include <Jolt/Physics/Collision/CastResult.h>
  13. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  14. #include <Jolt/Physics/Collision/CollideSphereVsTriangles.h>
  15. #include <Jolt/Physics/Collision/CastConvexVsTriangles.h>
  16. #include <Jolt/Physics/Collision/CastSphereVsTriangles.h>
  17. #include <Jolt/Physics/Collision/TransformedShape.h>
  18. #include <Jolt/Physics/Collision/ActiveEdges.h>
  19. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  20. #include <Jolt/Physics/Collision/SortReverseAndStore.h>
  21. #include <Jolt/Physics/Collision/CollideSoftBodyVerticesVsTriangles.h>
  22. #include <Jolt/Core/StringTools.h>
  23. #include <Jolt/Core/StreamIn.h>
  24. #include <Jolt/Core/StreamOut.h>
  25. #include <Jolt/Core/Profiler.h>
  26. #include <Jolt/Core/UnorderedMap.h>
  27. #include <Jolt/Geometry/AABox4.h>
  28. #include <Jolt/Geometry/RayAABox.h>
  29. #include <Jolt/Geometry/Indexify.h>
  30. #include <Jolt/Geometry/Plane.h>
  31. #include <Jolt/Geometry/OrientedBox.h>
  32. #include <Jolt/TriangleSplitter/TriangleSplitterBinning.h>
  33. #include <Jolt/AABBTree/AABBTreeBuilder.h>
  34. #include <Jolt/AABBTree/AABBTreeToBuffer.h>
  35. #include <Jolt/AABBTree/TriangleCodec/TriangleCodecIndexed8BitPackSOA4Flags.h>
  36. #include <Jolt/AABBTree/NodeCodec/NodeCodecQuadTreeHalfFloat.h>
  37. #include <Jolt/ObjectStream/TypeDeclarations.h>
  38. JPH_NAMESPACE_BEGIN
  39. #ifdef JPH_DEBUG_RENDERER
  40. bool MeshShape::sDrawTriangleGroups = false;
  41. bool MeshShape::sDrawTriangleOutlines = false;
  42. #endif // JPH_DEBUG_RENDERER
  43. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(MeshShapeSettings)
  44. {
  45. JPH_ADD_BASE_CLASS(MeshShapeSettings, ShapeSettings)
  46. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mTriangleVertices)
  47. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mIndexedTriangles)
  48. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mMaterials)
  49. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mMaxTrianglesPerLeaf)
  50. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mActiveEdgeCosThresholdAngle)
  51. }
  52. // Codecs this mesh shape is using
  53. using TriangleCodec = TriangleCodecIndexed8BitPackSOA4Flags;
  54. using NodeCodec = NodeCodecQuadTreeHalfFloat<1>;
  55. // Get header for tree
  56. static JPH_INLINE const NodeCodec::Header *sGetNodeHeader(const ByteBuffer &inTree)
  57. {
  58. return inTree.Get<NodeCodec::Header>(0);
  59. }
  60. // Get header for triangles
  61. static JPH_INLINE const TriangleCodec::TriangleHeader *sGetTriangleHeader(const ByteBuffer &inTree)
  62. {
  63. return inTree.Get<TriangleCodec::TriangleHeader>(NodeCodec::HeaderSize);
  64. }
  65. MeshShapeSettings::MeshShapeSettings(const TriangleList &inTriangles, PhysicsMaterialList inMaterials) :
  66. mMaterials(std::move(inMaterials))
  67. {
  68. Indexify(inTriangles, mTriangleVertices, mIndexedTriangles);
  69. Sanitize();
  70. }
  71. MeshShapeSettings::MeshShapeSettings(VertexList inVertices, IndexedTriangleList inTriangles, PhysicsMaterialList inMaterials) :
  72. mTriangleVertices(std::move(inVertices)),
  73. mIndexedTriangles(std::move(inTriangles)),
  74. mMaterials(std::move(inMaterials))
  75. {
  76. Sanitize();
  77. }
  78. void MeshShapeSettings::Sanitize()
  79. {
  80. // Remove degenerate and duplicate triangles
  81. UnorderedSet<IndexedTriangle> triangles;
  82. triangles.reserve(mIndexedTriangles.size());
  83. TriangleCodec::ValidationContext validation_ctx(mIndexedTriangles, mTriangleVertices);
  84. for (int t = (int)mIndexedTriangles.size() - 1; t >= 0; --t)
  85. {
  86. const IndexedTriangle &tri = mIndexedTriangles[t];
  87. if (tri.IsDegenerate(mTriangleVertices) // Degenerate triangle
  88. || validation_ctx.IsDegenerate(tri) // Triangle is degenerate in the quantized space
  89. || !triangles.insert(tri.GetLowestIndexFirst()).second) // Duplicate triangle
  90. {
  91. // The order of triangles doesn't matter (gets reordered while building the tree), so we can just swap the last triangle into this slot
  92. mIndexedTriangles[t] = mIndexedTriangles.back();
  93. mIndexedTriangles.pop_back();
  94. }
  95. }
  96. }
  97. ShapeSettings::ShapeResult MeshShapeSettings::Create() const
  98. {
  99. if (mCachedResult.IsEmpty())
  100. Ref<Shape> shape = new MeshShape(*this, mCachedResult);
  101. return mCachedResult;
  102. }
  103. MeshShape::MeshShape(const MeshShapeSettings &inSettings, ShapeResult &outResult) :
  104. Shape(EShapeType::Mesh, EShapeSubType::Mesh, inSettings, outResult)
  105. {
  106. // Check if there are any triangles
  107. if (inSettings.mIndexedTriangles.empty())
  108. {
  109. outResult.SetError("Need triangles to create a mesh shape!");
  110. return;
  111. }
  112. // Check triangles
  113. TriangleCodec::ValidationContext validation_ctx(inSettings.mIndexedTriangles, inSettings.mTriangleVertices);
  114. for (int t = (int)inSettings.mIndexedTriangles.size() - 1; t >= 0; --t)
  115. {
  116. const IndexedTriangle &triangle = inSettings.mIndexedTriangles[t];
  117. if (triangle.IsDegenerate(inSettings.mTriangleVertices)
  118. || validation_ctx.IsDegenerate(triangle))
  119. {
  120. outResult.SetError(StringFormat("Triangle %d is degenerate!", t));
  121. return;
  122. }
  123. else
  124. {
  125. // Check vertex indices
  126. for (uint32 idx : triangle.mIdx)
  127. if (idx >= inSettings.mTriangleVertices.size())
  128. {
  129. outResult.SetError(StringFormat("Vertex index %u is beyond vertex list (size: %u)", idx, (uint)inSettings.mTriangleVertices.size()));
  130. return;
  131. }
  132. }
  133. }
  134. // Copy materials
  135. mMaterials = inSettings.mMaterials;
  136. if (!mMaterials.empty())
  137. {
  138. // Validate materials
  139. if (mMaterials.size() > (1 << FLAGS_MATERIAL_BITS))
  140. {
  141. outResult.SetError(StringFormat("Supporting max %d materials per mesh", 1 << FLAGS_MATERIAL_BITS));
  142. return;
  143. }
  144. for (const IndexedTriangle &t : inSettings.mIndexedTriangles)
  145. if (t.mMaterialIndex >= mMaterials.size())
  146. {
  147. outResult.SetError(StringFormat("Triangle material %u is beyond material list (size: %u)", t.mMaterialIndex, (uint)mMaterials.size()));
  148. return;
  149. }
  150. }
  151. else
  152. {
  153. // No materials assigned, validate that all triangles use material index 0
  154. for (const IndexedTriangle &t : inSettings.mIndexedTriangles)
  155. if (t.mMaterialIndex != 0)
  156. {
  157. outResult.SetError("No materials present, all triangles should have material index 0");
  158. return;
  159. }
  160. }
  161. // Check max triangles
  162. if (inSettings.mMaxTrianglesPerLeaf < 1 || inSettings.mMaxTrianglesPerLeaf > MaxTrianglesPerLeaf)
  163. {
  164. outResult.SetError("Invalid max triangles per leaf");
  165. return;
  166. }
  167. // Fill in active edge bits
  168. IndexedTriangleList indexed_triangles = inSettings.mIndexedTriangles; // Copy indices since we're adding the 'active edge' flag
  169. sFindActiveEdges(inSettings, indexed_triangles);
  170. // Create triangle splitter
  171. TriangleSplitterBinning splitter(inSettings.mTriangleVertices, indexed_triangles);
  172. // Build tree
  173. AABBTreeBuilder builder(splitter, inSettings.mMaxTrianglesPerLeaf);
  174. AABBTreeBuilderStats builder_stats;
  175. AABBTreeBuilder::Node *root = builder.Build(builder_stats);
  176. // Convert to buffer
  177. AABBTreeToBuffer<TriangleCodec, NodeCodec> buffer;
  178. const char *error = nullptr;
  179. if (!buffer.Convert(inSettings.mTriangleVertices, root, error))
  180. {
  181. outResult.SetError(error);
  182. delete root;
  183. return;
  184. }
  185. // Kill tree
  186. delete root;
  187. // Move data to this class
  188. mTree.swap(buffer.GetBuffer());
  189. // Check if we're not exceeding the amount of sub shape id bits
  190. if (GetSubShapeIDBitsRecursive() > SubShapeID::MaxBits)
  191. {
  192. outResult.SetError("Mesh is too big and exceeds the amount of available sub shape ID bits");
  193. return;
  194. }
  195. outResult.Set(this);
  196. }
  197. void MeshShape::sFindActiveEdges(const MeshShapeSettings &inSettings, IndexedTriangleList &ioIndices)
  198. {
  199. // A struct to hold the two vertex indices of an edge
  200. struct Edge
  201. {
  202. Edge(int inIdx1, int inIdx2) : mIdx1(min(inIdx1, inIdx2)), mIdx2(max(inIdx1, inIdx2)) { }
  203. uint GetIndexInTriangle(const IndexedTriangle &inTriangle) const
  204. {
  205. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  206. {
  207. Edge edge(inTriangle.mIdx[edge_idx], inTriangle.mIdx[(edge_idx + 1) % 3]);
  208. if (*this == edge)
  209. return edge_idx;
  210. }
  211. JPH_ASSERT(false);
  212. return ~uint(0);
  213. }
  214. bool operator == (const Edge &inRHS) const
  215. {
  216. return mIdx1 == inRHS.mIdx1 && mIdx2 == inRHS.mIdx2;
  217. }
  218. int mIdx1;
  219. int mIdx2;
  220. };
  221. JPH_MAKE_HASH_STRUCT(Edge, EdgeHash, t.mIdx1, t.mIdx2)
  222. // A struct to hold the triangles that are connected to an edge
  223. struct TriangleIndices
  224. {
  225. uint mNumTriangles = 0;
  226. uint mTriangleIndices[2];
  227. };
  228. // Build a list of edge to triangles
  229. using EdgeToTriangle = UnorderedMap<Edge, TriangleIndices, EdgeHash>;
  230. EdgeToTriangle edge_to_triangle;
  231. edge_to_triangle.reserve(ioIndices.size() * 3);
  232. for (uint triangle_idx = 0; triangle_idx < ioIndices.size(); ++triangle_idx)
  233. {
  234. IndexedTriangle &triangle = ioIndices[triangle_idx];
  235. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  236. {
  237. Edge edge(triangle.mIdx[edge_idx], triangle.mIdx[(edge_idx + 1) % 3]);
  238. TriangleIndices &indices = edge_to_triangle[edge];
  239. if (indices.mNumTriangles < 2)
  240. {
  241. // Store index of triangle that connects to this edge
  242. indices.mTriangleIndices[indices.mNumTriangles] = triangle_idx;
  243. indices.mNumTriangles++;
  244. }
  245. else
  246. {
  247. // 3 or more triangles share an edge, mark this edge as active
  248. uint32 mask = 1 << (edge_idx + FLAGS_ACTIVE_EGDE_SHIFT);
  249. JPH_ASSERT((triangle.mMaterialIndex & mask) == 0);
  250. triangle.mMaterialIndex |= mask;
  251. }
  252. }
  253. }
  254. // Walk over all edges and determine which ones are active
  255. for (const EdgeToTriangle::value_type &edge : edge_to_triangle)
  256. {
  257. uint num_active = 0;
  258. if (edge.second.mNumTriangles == 1)
  259. {
  260. // Edge is not shared, it is an active edge
  261. num_active = 1;
  262. }
  263. else if (edge.second.mNumTriangles == 2)
  264. {
  265. // Simple shared edge, determine if edge is active based on the two adjacent triangles
  266. const IndexedTriangle &triangle1 = ioIndices[edge.second.mTriangleIndices[0]];
  267. const IndexedTriangle &triangle2 = ioIndices[edge.second.mTriangleIndices[1]];
  268. // Find which edge this is for both triangles
  269. uint edge_idx1 = edge.first.GetIndexInTriangle(triangle1);
  270. uint edge_idx2 = edge.first.GetIndexInTriangle(triangle2);
  271. // Construct a plane for triangle 1 (e1 = edge vertex 1, e2 = edge vertex 2, op = opposing vertex)
  272. Vec3 triangle1_e1 = Vec3(inSettings.mTriangleVertices[triangle1.mIdx[edge_idx1]]);
  273. Vec3 triangle1_e2 = Vec3(inSettings.mTriangleVertices[triangle1.mIdx[(edge_idx1 + 1) % 3]]);
  274. Vec3 triangle1_op = Vec3(inSettings.mTriangleVertices[triangle1.mIdx[(edge_idx1 + 2) % 3]]);
  275. Plane triangle1_plane = Plane::sFromPointsCCW(triangle1_e1, triangle1_e2, triangle1_op);
  276. // Construct a plane for triangle 2
  277. Vec3 triangle2_e1 = Vec3(inSettings.mTriangleVertices[triangle2.mIdx[edge_idx2]]);
  278. Vec3 triangle2_e2 = Vec3(inSettings.mTriangleVertices[triangle2.mIdx[(edge_idx2 + 1) % 3]]);
  279. Vec3 triangle2_op = Vec3(inSettings.mTriangleVertices[triangle2.mIdx[(edge_idx2 + 2) % 3]]);
  280. Plane triangle2_plane = Plane::sFromPointsCCW(triangle2_e1, triangle2_e2, triangle2_op);
  281. // Determine if the edge is active
  282. num_active = ActiveEdges::IsEdgeActive(triangle1_plane.GetNormal(), triangle2_plane.GetNormal(), triangle1_e2 - triangle1_e1, inSettings.mActiveEdgeCosThresholdAngle)? 2 : 0;
  283. }
  284. else
  285. {
  286. // More edges incoming, we've already marked all edges beyond the 2nd as active
  287. num_active = 2;
  288. }
  289. // Mark edges of all original triangles active
  290. for (uint i = 0; i < num_active; ++i)
  291. {
  292. uint triangle_idx = edge.second.mTriangleIndices[i];
  293. IndexedTriangle &triangle = ioIndices[triangle_idx];
  294. uint edge_idx = edge.first.GetIndexInTriangle(triangle);
  295. uint32 mask = 1 << (edge_idx + FLAGS_ACTIVE_EGDE_SHIFT);
  296. JPH_ASSERT((triangle.mMaterialIndex & mask) == 0);
  297. triangle.mMaterialIndex |= mask;
  298. }
  299. }
  300. }
  301. MassProperties MeshShape::GetMassProperties() const
  302. {
  303. // Object should always be static, return default mass properties
  304. return MassProperties();
  305. }
  306. void MeshShape::DecodeSubShapeID(const SubShapeID &inSubShapeID, const void *&outTriangleBlock, uint32 &outTriangleIndex) const
  307. {
  308. // Get block
  309. SubShapeID triangle_idx_subshape_id;
  310. uint32 block_id = inSubShapeID.PopID(NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree), triangle_idx_subshape_id);
  311. outTriangleBlock = NodeCodec::DecodingContext::sGetTriangleBlockStart(&mTree[0], block_id);
  312. // Fetch the triangle index
  313. SubShapeID remainder;
  314. outTriangleIndex = triangle_idx_subshape_id.PopID(NumTriangleBits, remainder);
  315. JPH_ASSERT(remainder.IsEmpty(), "Invalid subshape ID");
  316. }
  317. uint MeshShape::GetMaterialIndex(const SubShapeID &inSubShapeID) const
  318. {
  319. // Decode ID
  320. const void *block_start;
  321. uint32 triangle_idx;
  322. DecodeSubShapeID(inSubShapeID, block_start, triangle_idx);
  323. // Fetch the flags
  324. uint8 flags = TriangleCodec::DecodingContext::sGetFlags(block_start, triangle_idx);
  325. return flags & FLAGS_MATERIAL_MASK;
  326. }
  327. const PhysicsMaterial *MeshShape::GetMaterial(const SubShapeID &inSubShapeID) const
  328. {
  329. // Return the default material if there are no materials on this shape
  330. if (mMaterials.empty())
  331. return PhysicsMaterial::sDefault;
  332. return mMaterials[GetMaterialIndex(inSubShapeID)];
  333. }
  334. Vec3 MeshShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  335. {
  336. // Decode ID
  337. const void *block_start;
  338. uint32 triangle_idx;
  339. DecodeSubShapeID(inSubShapeID, block_start, triangle_idx);
  340. // Decode triangle
  341. Vec3 v1, v2, v3;
  342. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  343. triangle_ctx.GetTriangle(block_start, triangle_idx, v1, v2, v3);
  344. // Calculate normal
  345. return (v3 - v2).Cross(v1 - v2).Normalized();
  346. }
  347. void MeshShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  348. {
  349. // Decode ID
  350. const void *block_start;
  351. uint32 triangle_idx;
  352. DecodeSubShapeID(inSubShapeID, block_start, triangle_idx);
  353. // Decode triangle
  354. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  355. outVertices.resize(3);
  356. triangle_ctx.GetTriangle(block_start, triangle_idx, outVertices[0], outVertices[1], outVertices[2]);
  357. // Flip triangle if scaled inside out
  358. if (ScaleHelpers::IsInsideOut(inScale))
  359. swap(outVertices[1], outVertices[2]);
  360. // Calculate transform with scale
  361. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  362. // Transform to world space
  363. for (Vec3 &v : outVertices)
  364. v = transform * v;
  365. }
  366. AABox MeshShape::GetLocalBounds() const
  367. {
  368. const NodeCodec::Header *header = sGetNodeHeader(mTree);
  369. return AABox(Vec3::sLoadFloat3Unsafe(header->mRootBoundsMin), Vec3::sLoadFloat3Unsafe(header->mRootBoundsMax));
  370. }
  371. uint MeshShape::GetSubShapeIDBitsRecursive() const
  372. {
  373. return NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree) + NumTriangleBits;
  374. }
  375. template <class Visitor>
  376. JPH_INLINE void MeshShape::WalkTree(Visitor &ioVisitor) const
  377. {
  378. const NodeCodec::Header *header = sGetNodeHeader(mTree);
  379. NodeCodec::DecodingContext node_ctx(header);
  380. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  381. const uint8 *buffer_start = &mTree[0];
  382. node_ctx.WalkTree(buffer_start, triangle_ctx, ioVisitor);
  383. }
  384. template <class Visitor>
  385. JPH_INLINE void MeshShape::WalkTreePerTriangle(const SubShapeIDCreator &inSubShapeIDCreator2, Visitor &ioVisitor) const
  386. {
  387. struct ChainedVisitor
  388. {
  389. JPH_INLINE ChainedVisitor(Visitor &ioVisitor, const SubShapeIDCreator &inSubShapeIDCreator2, uint inTriangleBlockIDBits) :
  390. mVisitor(ioVisitor),
  391. mSubShapeIDCreator2(inSubShapeIDCreator2),
  392. mTriangleBlockIDBits(inTriangleBlockIDBits)
  393. {
  394. }
  395. JPH_INLINE bool ShouldAbort() const
  396. {
  397. return mVisitor.ShouldAbort();
  398. }
  399. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  400. {
  401. return mVisitor.ShouldVisitNode(inStackTop);
  402. }
  403. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  404. {
  405. return mVisitor.VisitNodes(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, ioProperties, inStackTop);
  406. }
  407. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, uint32 inTriangleBlockID)
  408. {
  409. // Create ID for triangle block
  410. SubShapeIDCreator block_sub_shape_id = mSubShapeIDCreator2.PushID(inTriangleBlockID, mTriangleBlockIDBits);
  411. // Decode vertices and flags
  412. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  413. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  414. uint8 flags[MaxTrianglesPerLeaf];
  415. ioContext.Unpack(inTriangles, inNumTriangles, vertices, flags);
  416. int triangle_idx = 0;
  417. for (const Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3, triangle_idx++)
  418. {
  419. // Determine active edges
  420. uint8 active_edges = (flags[triangle_idx] >> FLAGS_ACTIVE_EGDE_SHIFT) & FLAGS_ACTIVE_EDGE_MASK;
  421. // Create ID for triangle
  422. SubShapeIDCreator triangle_sub_shape_id = block_sub_shape_id.PushID(triangle_idx, NumTriangleBits);
  423. mVisitor.VisitTriangle(v[0], v[1], v[2], active_edges, triangle_sub_shape_id.GetID());
  424. // Check if we should early out now
  425. if (mVisitor.ShouldAbort())
  426. break;
  427. }
  428. }
  429. Visitor & mVisitor;
  430. SubShapeIDCreator mSubShapeIDCreator2;
  431. uint mTriangleBlockIDBits;
  432. };
  433. ChainedVisitor visitor(ioVisitor, inSubShapeIDCreator2, NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree));
  434. WalkTree(visitor);
  435. }
  436. #ifdef JPH_DEBUG_RENDERER
  437. void MeshShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  438. {
  439. // Reset the batch if we switch coloring mode
  440. if (mCachedTrianglesColoredPerGroup != sDrawTriangleGroups || mCachedUseMaterialColors != inUseMaterialColors)
  441. {
  442. mGeometry = nullptr;
  443. mCachedTrianglesColoredPerGroup = sDrawTriangleGroups;
  444. mCachedUseMaterialColors = inUseMaterialColors;
  445. }
  446. if (mGeometry == nullptr)
  447. {
  448. struct Visitor
  449. {
  450. JPH_INLINE bool ShouldAbort() const
  451. {
  452. return false;
  453. }
  454. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  455. {
  456. return true;
  457. }
  458. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  459. {
  460. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  461. return CountAndSortTrues(valid, ioProperties);
  462. }
  463. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, [[maybe_unused]] uint32 inTriangleBlockID)
  464. {
  465. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  466. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  467. ioContext.Unpack(inTriangles, inNumTriangles, vertices);
  468. if (mDrawTriangleGroups || !mUseMaterialColors || mMaterials.empty())
  469. {
  470. // Single color for mesh
  471. Color color = mDrawTriangleGroups? Color::sGetDistinctColor(mColorIdx++) : (mUseMaterialColors? PhysicsMaterial::sDefault->GetDebugColor() : Color::sWhite);
  472. for (const Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3)
  473. mTriangles.push_back({ v[0], v[1], v[2], color });
  474. }
  475. else
  476. {
  477. // Per triangle color
  478. uint8 flags[MaxTrianglesPerLeaf];
  479. TriangleCodec::DecodingContext::sGetFlags(inTriangles, inNumTriangles, flags);
  480. const uint8 *f = flags;
  481. for (const Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3, f++)
  482. mTriangles.push_back({ v[0], v[1], v[2], mMaterials[*f & FLAGS_MATERIAL_MASK]->GetDebugColor() });
  483. }
  484. }
  485. Array<DebugRenderer::Triangle> & mTriangles;
  486. const PhysicsMaterialList & mMaterials;
  487. bool mUseMaterialColors;
  488. bool mDrawTriangleGroups;
  489. int mColorIdx = 0;
  490. };
  491. Array<DebugRenderer::Triangle> triangles;
  492. Visitor visitor { triangles, mMaterials, mCachedUseMaterialColors, mCachedTrianglesColoredPerGroup };
  493. WalkTree(visitor);
  494. mGeometry = new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), GetLocalBounds());
  495. }
  496. // Test if the shape is scaled inside out
  497. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  498. // Determine the draw mode
  499. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  500. // Draw the geometry
  501. inRenderer->DrawGeometry(inCenterOfMassTransform * Mat44::sScale(inScale), inColor, mGeometry, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  502. if (sDrawTriangleOutlines)
  503. {
  504. struct Visitor
  505. {
  506. JPH_INLINE Visitor(DebugRenderer *inRenderer, RMat44Arg inTransform) :
  507. mRenderer(inRenderer),
  508. mTransform(inTransform)
  509. {
  510. }
  511. JPH_INLINE bool ShouldAbort() const
  512. {
  513. return false;
  514. }
  515. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  516. {
  517. return true;
  518. }
  519. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  520. {
  521. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  522. return CountAndSortTrues(valid, ioProperties);
  523. }
  524. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, uint32 inTriangleBlockID)
  525. {
  526. // Decode vertices and flags
  527. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  528. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  529. uint8 flags[MaxTrianglesPerLeaf];
  530. ioContext.Unpack(inTriangles, inNumTriangles, vertices, flags);
  531. // Loop through triangles
  532. const uint8 *f = flags;
  533. for (Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3, ++f)
  534. {
  535. // Loop through edges
  536. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  537. {
  538. RVec3 v1 = mTransform * v[edge_idx];
  539. RVec3 v2 = mTransform * v[(edge_idx + 1) % 3];
  540. // Draw active edge as a green arrow, other edges as grey
  541. if (*f & (1 << (edge_idx + FLAGS_ACTIVE_EGDE_SHIFT)))
  542. mRenderer->DrawArrow(v1, v2, Color::sGreen, 0.01f);
  543. else
  544. mRenderer->DrawLine(v1, v2, Color::sGrey);
  545. }
  546. }
  547. }
  548. DebugRenderer * mRenderer;
  549. RMat44 mTransform;
  550. };
  551. Visitor visitor { inRenderer, inCenterOfMassTransform.PreScaled(inScale) };
  552. WalkTree(visitor);
  553. }
  554. }
  555. #endif // JPH_DEBUG_RENDERER
  556. bool MeshShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  557. {
  558. JPH_PROFILE_FUNCTION();
  559. struct Visitor
  560. {
  561. JPH_INLINE explicit Visitor(RayCastResult &ioHit) :
  562. mHit(ioHit)
  563. {
  564. }
  565. JPH_INLINE bool ShouldAbort() const
  566. {
  567. return mHit.mFraction <= 0.0f;
  568. }
  569. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  570. {
  571. return mDistanceStack[inStackTop] < mHit.mFraction;
  572. }
  573. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  574. {
  575. // Test bounds of 4 children
  576. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  577. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  578. return SortReverseAndStore(distance, mHit.mFraction, ioProperties, &mDistanceStack[inStackTop]);
  579. }
  580. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, uint32 inTriangleBlockID)
  581. {
  582. // Test against triangles
  583. uint32 triangle_idx;
  584. float fraction = ioContext.TestRay(mRayOrigin, mRayDirection, inTriangles, inNumTriangles, mHit.mFraction, triangle_idx);
  585. if (fraction < mHit.mFraction)
  586. {
  587. mHit.mFraction = fraction;
  588. mHit.mSubShapeID2 = mSubShapeIDCreator.PushID(inTriangleBlockID, mTriangleBlockIDBits).PushID(triangle_idx, NumTriangleBits).GetID();
  589. mReturnValue = true;
  590. }
  591. }
  592. RayCastResult & mHit;
  593. Vec3 mRayOrigin;
  594. Vec3 mRayDirection;
  595. RayInvDirection mRayInvDirection;
  596. uint mTriangleBlockIDBits;
  597. SubShapeIDCreator mSubShapeIDCreator;
  598. bool mReturnValue = false;
  599. float mDistanceStack[NodeCodec::StackSize];
  600. };
  601. Visitor visitor(ioHit);
  602. visitor.mRayOrigin = inRay.mOrigin;
  603. visitor.mRayDirection = inRay.mDirection;
  604. visitor.mRayInvDirection.Set(inRay.mDirection);
  605. visitor.mTriangleBlockIDBits = NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree);
  606. visitor.mSubShapeIDCreator = inSubShapeIDCreator;
  607. WalkTree(visitor);
  608. return visitor.mReturnValue;
  609. }
  610. void MeshShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  611. {
  612. JPH_PROFILE_FUNCTION();
  613. // Test shape filter
  614. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  615. return;
  616. struct Visitor
  617. {
  618. JPH_INLINE explicit Visitor(CastRayCollector &ioCollector) :
  619. mCollector(ioCollector)
  620. {
  621. }
  622. JPH_INLINE bool ShouldAbort() const
  623. {
  624. return mCollector.ShouldEarlyOut();
  625. }
  626. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  627. {
  628. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  629. }
  630. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  631. {
  632. // Test bounds of 4 children
  633. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  634. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  635. return SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  636. }
  637. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, [[maybe_unused]] uint8 inActiveEdges, SubShapeID inSubShapeID2)
  638. {
  639. // Back facing check
  640. if (mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (inV2 - inV0).Cross(inV1 - inV0).Dot(mRayDirection) < 0)
  641. return;
  642. // Check the triangle
  643. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  644. if (fraction < mCollector.GetEarlyOutFraction())
  645. {
  646. RayCastResult hit;
  647. hit.mBodyID = TransformedShape::sGetBodyID(mCollector.GetContext());
  648. hit.mFraction = fraction;
  649. hit.mSubShapeID2 = inSubShapeID2;
  650. mCollector.AddHit(hit);
  651. }
  652. }
  653. CastRayCollector & mCollector;
  654. Vec3 mRayOrigin;
  655. Vec3 mRayDirection;
  656. RayInvDirection mRayInvDirection;
  657. EBackFaceMode mBackFaceMode;
  658. float mDistanceStack[NodeCodec::StackSize];
  659. };
  660. Visitor visitor(ioCollector);
  661. visitor.mBackFaceMode = inRayCastSettings.mBackFaceMode;
  662. visitor.mRayOrigin = inRay.mOrigin;
  663. visitor.mRayDirection = inRay.mDirection;
  664. visitor.mRayInvDirection.Set(inRay.mDirection);
  665. WalkTreePerTriangle(inSubShapeIDCreator, visitor);
  666. }
  667. void MeshShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  668. {
  669. sCollidePointUsingRayCast(*this, inPoint, inSubShapeIDCreator, ioCollector, inShapeFilter);
  670. }
  671. void MeshShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, [[maybe_unused]] float inDeltaTime, [[maybe_unused]] Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  672. {
  673. JPH_PROFILE_FUNCTION();
  674. struct Visitor : public CollideSoftBodyVerticesVsTriangles
  675. {
  676. using CollideSoftBodyVerticesVsTriangles::CollideSoftBodyVerticesVsTriangles;
  677. JPH_INLINE bool ShouldAbort() const
  678. {
  679. return false;
  680. }
  681. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  682. {
  683. return mDistanceStack[inStackTop] < mClosestDistanceSq;
  684. }
  685. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  686. {
  687. // Get distance to vertex
  688. Vec4 dist_sq = AABox4DistanceSqToPoint(mLocalPosition, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  689. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  690. return SortReverseAndStore(dist_sq, mClosestDistanceSq, ioProperties, &mDistanceStack[inStackTop]);
  691. }
  692. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, [[maybe_unused]] uint8 inActiveEdges, [[maybe_unused]] SubShapeID inSubShapeID2)
  693. {
  694. ProcessTriangle(inV0, inV1, inV2);
  695. }
  696. float mDistanceStack[NodeCodec::StackSize];
  697. };
  698. Visitor visitor(inCenterOfMassTransform, inScale);
  699. for (SoftBodyVertex *v = ioVertices, *sbv_end = ioVertices + inNumVertices; v < sbv_end; ++v)
  700. if (v->mInvMass > 0.0f)
  701. {
  702. visitor.StartVertex(*v);
  703. WalkTreePerTriangle(SubShapeIDCreator(), visitor);
  704. visitor.FinishVertex(*v, inCollidingShapeIndex);
  705. }
  706. }
  707. void MeshShape::sCastConvexVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  708. {
  709. JPH_PROFILE_FUNCTION();
  710. struct Visitor : public CastConvexVsTriangles
  711. {
  712. using CastConvexVsTriangles::CastConvexVsTriangles;
  713. JPH_INLINE bool ShouldAbort() const
  714. {
  715. return mCollector.ShouldEarlyOut();
  716. }
  717. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  718. {
  719. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  720. }
  721. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  722. {
  723. // Scale the bounding boxes of this node
  724. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  725. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  726. // Enlarge them by the casted shape's box extents
  727. AABox4EnlargeWithExtent(mBoxExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  728. // Test bounds of 4 children
  729. Vec4 distance = RayAABox4(mBoxCenter, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  730. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  731. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  732. }
  733. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  734. {
  735. Cast(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  736. }
  737. RayInvDirection mInvDirection;
  738. Vec3 mBoxCenter;
  739. Vec3 mBoxExtent;
  740. float mDistanceStack[NodeCodec::StackSize];
  741. };
  742. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Mesh);
  743. const MeshShape *shape = static_cast<const MeshShape *>(inShape);
  744. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  745. visitor.mInvDirection.Set(inShapeCast.mDirection);
  746. visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();
  747. visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();
  748. shape->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  749. }
  750. void MeshShape::sCastSphereVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  751. {
  752. JPH_PROFILE_FUNCTION();
  753. struct Visitor : public CastSphereVsTriangles
  754. {
  755. using CastSphereVsTriangles::CastSphereVsTriangles;
  756. JPH_INLINE bool ShouldAbort() const
  757. {
  758. return mCollector.ShouldEarlyOut();
  759. }
  760. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  761. {
  762. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  763. }
  764. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  765. {
  766. // Scale the bounding boxes of this node
  767. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  768. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  769. // Enlarge them by the radius of the sphere
  770. AABox4EnlargeWithExtent(Vec3::sReplicate(mRadius), bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  771. // Test bounds of 4 children
  772. Vec4 distance = RayAABox4(mStart, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  773. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  774. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  775. }
  776. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  777. {
  778. Cast(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  779. }
  780. RayInvDirection mInvDirection;
  781. float mDistanceStack[NodeCodec::StackSize];
  782. };
  783. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Mesh);
  784. const MeshShape *shape = static_cast<const MeshShape *>(inShape);
  785. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  786. visitor.mInvDirection.Set(inShapeCast.mDirection);
  787. shape->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  788. }
  789. struct MeshShape::MSGetTrianglesContext
  790. {
  791. JPH_INLINE MSGetTrianglesContext(const MeshShape *inShape, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) :
  792. mDecodeCtx(sGetNodeHeader(inShape->mTree)),
  793. mShape(inShape),
  794. mLocalBox(Mat44::sInverseRotationTranslation(inRotation, inPositionCOM), inBox),
  795. mMeshScale(inScale),
  796. mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),
  797. mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
  798. {
  799. }
  800. JPH_INLINE bool ShouldAbort() const
  801. {
  802. return mShouldAbort;
  803. }
  804. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  805. {
  806. return true;
  807. }
  808. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  809. {
  810. // Scale the bounding boxes of this node
  811. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  812. AABox4Scale(mMeshScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  813. // Test which nodes collide
  814. UVec4 collides = AABox4VsBox(mLocalBox, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  815. return CountAndSortTrues(collides, ioProperties);
  816. }
  817. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, [[maybe_unused]] uint32 inTriangleBlockID)
  818. {
  819. // When the buffer is full and we cannot process the triangles, abort the tree walk. The next time GetTrianglesNext is called we will continue here.
  820. if (mNumTrianglesFound + inNumTriangles > mMaxTrianglesRequested)
  821. {
  822. mShouldAbort = true;
  823. return;
  824. }
  825. // Decode vertices
  826. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  827. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  828. ioContext.Unpack(inTriangles, inNumTriangles, vertices);
  829. // Store vertices as Float3
  830. if (mIsInsideOut)
  831. {
  832. // Scaled inside out, flip the triangles
  833. for (const Vec3 *v = vertices, *v_end = v + 3 * inNumTriangles; v < v_end; v += 3)
  834. {
  835. (mLocalToWorld * v[0]).StoreFloat3(mTriangleVertices++);
  836. (mLocalToWorld * v[2]).StoreFloat3(mTriangleVertices++);
  837. (mLocalToWorld * v[1]).StoreFloat3(mTriangleVertices++);
  838. }
  839. }
  840. else
  841. {
  842. // Normal scale
  843. for (const Vec3 *v = vertices, *v_end = v + 3 * inNumTriangles; v < v_end; ++v)
  844. (mLocalToWorld * *v).StoreFloat3(mTriangleVertices++);
  845. }
  846. if (mMaterials != nullptr)
  847. {
  848. if (mShape->mMaterials.empty())
  849. {
  850. // No materials, output default
  851. const PhysicsMaterial *default_material = PhysicsMaterial::sDefault;
  852. for (int m = 0; m < inNumTriangles; ++m)
  853. *mMaterials++ = default_material;
  854. }
  855. else
  856. {
  857. // Decode triangle flags
  858. uint8 flags[MaxTrianglesPerLeaf];
  859. TriangleCodec::DecodingContext::sGetFlags(inTriangles, inNumTriangles, flags);
  860. // Store materials
  861. for (const uint8 *f = flags, *f_end = f + inNumTriangles; f < f_end; ++f)
  862. *mMaterials++ = mShape->mMaterials[*f & FLAGS_MATERIAL_MASK].GetPtr();
  863. }
  864. }
  865. // Accumulate triangles found
  866. mNumTrianglesFound += inNumTriangles;
  867. }
  868. NodeCodec::DecodingContext mDecodeCtx;
  869. const MeshShape * mShape;
  870. OrientedBox mLocalBox;
  871. Vec3 mMeshScale;
  872. Mat44 mLocalToWorld;
  873. int mMaxTrianglesRequested;
  874. Float3 * mTriangleVertices;
  875. int mNumTrianglesFound;
  876. const PhysicsMaterial ** mMaterials;
  877. bool mShouldAbort;
  878. bool mIsInsideOut;
  879. };
  880. void MeshShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  881. {
  882. static_assert(sizeof(MSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  883. JPH_ASSERT(IsAligned(&ioContext, alignof(MSGetTrianglesContext)));
  884. new (&ioContext) MSGetTrianglesContext(this, inBox, inPositionCOM, inRotation, inScale);
  885. }
  886. int MeshShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  887. {
  888. static_assert(cGetTrianglesMinTrianglesRequested >= MaxTrianglesPerLeaf, "cGetTrianglesMinTrianglesRequested is too small");
  889. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  890. // Check if we're done
  891. MSGetTrianglesContext &context = (MSGetTrianglesContext &)ioContext;
  892. if (context.mDecodeCtx.IsDoneWalking())
  893. return 0;
  894. // Store parameters on context
  895. context.mMaxTrianglesRequested = inMaxTrianglesRequested;
  896. context.mTriangleVertices = outTriangleVertices;
  897. context.mMaterials = outMaterials;
  898. context.mShouldAbort = false; // Reset the abort flag
  899. context.mNumTrianglesFound = 0;
  900. // Continue (or start) walking the tree
  901. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  902. const uint8 *buffer_start = &mTree[0];
  903. context.mDecodeCtx.WalkTree(buffer_start, triangle_ctx, context);
  904. return context.mNumTrianglesFound;
  905. }
  906. void MeshShape::sCollideConvexVsMesh(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
  907. {
  908. JPH_PROFILE_FUNCTION();
  909. // Get the shapes
  910. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  911. JPH_ASSERT(inShape2->GetType() == EShapeType::Mesh);
  912. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  913. const MeshShape *shape2 = static_cast<const MeshShape *>(inShape2);
  914. struct Visitor : public CollideConvexVsTriangles
  915. {
  916. using CollideConvexVsTriangles::CollideConvexVsTriangles;
  917. JPH_INLINE bool ShouldAbort() const
  918. {
  919. return mCollector.ShouldEarlyOut();
  920. }
  921. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  922. {
  923. return true;
  924. }
  925. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  926. {
  927. // Scale the bounding boxes of this node
  928. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  929. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  930. // Test which nodes collide
  931. UVec4 collides = AABox4VsBox(mBoundsOf1InSpaceOf2, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  932. return CountAndSortTrues(collides, ioProperties);
  933. }
  934. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  935. {
  936. Collide(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  937. }
  938. };
  939. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  940. shape2->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  941. }
  942. void MeshShape::sCollideSphereVsMesh(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
  943. {
  944. JPH_PROFILE_FUNCTION();
  945. // Get the shapes
  946. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  947. JPH_ASSERT(inShape2->GetType() == EShapeType::Mesh);
  948. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  949. const MeshShape *shape2 = static_cast<const MeshShape *>(inShape2);
  950. struct Visitor : public CollideSphereVsTriangles
  951. {
  952. using CollideSphereVsTriangles::CollideSphereVsTriangles;
  953. JPH_INLINE bool ShouldAbort() const
  954. {
  955. return mCollector.ShouldEarlyOut();
  956. }
  957. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  958. {
  959. return true;
  960. }
  961. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  962. {
  963. // Scale the bounding boxes of this node
  964. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  965. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  966. // Test which nodes collide
  967. UVec4 collides = AABox4VsSphere(mSphereCenterIn2, mRadiusPlusMaxSeparationSq, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  968. return CountAndSortTrues(collides, ioProperties);
  969. }
  970. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  971. {
  972. Collide(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  973. }
  974. };
  975. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  976. shape2->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  977. }
  978. void MeshShape::SaveBinaryState(StreamOut &inStream) const
  979. {
  980. Shape::SaveBinaryState(inStream);
  981. inStream.Write(static_cast<const ByteBufferVector &>(mTree)); // Make sure we use the Array<> overload
  982. }
  983. void MeshShape::RestoreBinaryState(StreamIn &inStream)
  984. {
  985. Shape::RestoreBinaryState(inStream);
  986. inStream.Read(static_cast<ByteBufferVector &>(mTree)); // Make sure we use the Array<> overload
  987. }
  988. void MeshShape::SaveMaterialState(PhysicsMaterialList &outMaterials) const
  989. {
  990. outMaterials = mMaterials;
  991. }
  992. void MeshShape::RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
  993. {
  994. mMaterials.assign(inMaterials, inMaterials + inNumMaterials);
  995. }
  996. Shape::Stats MeshShape::GetStats() const
  997. {
  998. // Walk the tree to count the triangles
  999. struct Visitor
  1000. {
  1001. JPH_INLINE bool ShouldAbort() const
  1002. {
  1003. return false;
  1004. }
  1005. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  1006. {
  1007. return true;
  1008. }
  1009. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1010. {
  1011. // Visit all valid children
  1012. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  1013. return CountAndSortTrues(valid, ioProperties);
  1014. }
  1015. JPH_INLINE void VisitTriangles([[maybe_unused]] const TriangleCodec::DecodingContext &ioContext, [[maybe_unused]] const void *inTriangles, int inNumTriangles, [[maybe_unused]] uint32 inTriangleBlockID)
  1016. {
  1017. mNumTriangles += inNumTriangles;
  1018. }
  1019. uint mNumTriangles = 0;
  1020. };
  1021. Visitor visitor;
  1022. WalkTree(visitor);
  1023. return Stats(sizeof(*this) + mMaterials.size() * sizeof(Ref<PhysicsMaterial>) + mTree.size() * sizeof(uint8), visitor.mNumTriangles);
  1024. }
  1025. void MeshShape::sRegister()
  1026. {
  1027. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Mesh);
  1028. f.mConstruct = []() -> Shape * { return new MeshShape; };
  1029. f.mColor = Color::sRed;
  1030. for (EShapeSubType s : sConvexSubShapeTypes)
  1031. {
  1032. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::Mesh, sCollideConvexVsMesh);
  1033. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::Mesh, sCastConvexVsMesh);
  1034. CollisionDispatch::sRegisterCastShape(EShapeSubType::Mesh, s, CollisionDispatch::sReversedCastShape);
  1035. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Mesh, s, CollisionDispatch::sReversedCollideShape);
  1036. }
  1037. // Specialized collision functions
  1038. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::Mesh, sCollideSphereVsMesh);
  1039. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::Mesh, sCastSphereVsMesh);
  1040. }
  1041. JPH_NAMESPACE_END