MeshShape.cpp 46 KB

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