MeshShape.cpp 45 KB

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