MeshShape.cpp 44 KB

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