MeshShape.cpp 43 KB

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