MeshShape.cpp 49 KB

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