MeshShape.cpp 47 KB

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