TriangleShape.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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/TriangleShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  7. #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
  8. #include <Jolt/Physics/Collision/RayCast.h>
  9. #include <Jolt/Physics/Collision/ShapeCast.h>
  10. #include <Jolt/Physics/Collision/CastResult.h>
  11. #include <Jolt/Physics/Collision/CollidePointResult.h>
  12. #include <Jolt/Physics/Collision/TransformedShape.h>
  13. #include <Jolt/Physics/Collision/CastConvexVsTriangles.h>
  14. #include <Jolt/Physics/Collision/CastSphereVsTriangles.h>
  15. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  16. #include <Jolt/Physics/Collision/CollideSphereVsTriangles.h>
  17. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  18. #include <Jolt/Physics/Collision/CollideSoftBodyVerticesVsTriangles.h>
  19. #include <Jolt/Geometry/ConvexSupport.h>
  20. #include <Jolt/Geometry/RayTriangle.h>
  21. #include <Jolt/Geometry/ClosestPoint.h>
  22. #include <Jolt/ObjectStream/TypeDeclarations.h>
  23. #include <Jolt/Core/StreamIn.h>
  24. #include <Jolt/Core/StreamOut.h>
  25. #ifdef JPH_DEBUG_RENDERER
  26. #include <Jolt/Renderer/DebugRenderer.h>
  27. #endif // JPH_DEBUG_RENDERER
  28. JPH_NAMESPACE_BEGIN
  29. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TriangleShapeSettings)
  30. {
  31. JPH_ADD_BASE_CLASS(TriangleShapeSettings, ConvexShapeSettings)
  32. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV1)
  33. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV2)
  34. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV3)
  35. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mConvexRadius)
  36. }
  37. ShapeSettings::ShapeResult TriangleShapeSettings::Create() const
  38. {
  39. if (mCachedResult.IsEmpty())
  40. Ref<Shape> shape = new TriangleShape(*this, mCachedResult);
  41. return mCachedResult;
  42. }
  43. TriangleShape::TriangleShape(const TriangleShapeSettings &inSettings, ShapeResult &outResult) :
  44. ConvexShape(EShapeSubType::Triangle, inSettings, outResult),
  45. mV1(inSettings.mV1),
  46. mV2(inSettings.mV2),
  47. mV3(inSettings.mV3),
  48. mConvexRadius(inSettings.mConvexRadius)
  49. {
  50. if (inSettings.mConvexRadius < 0.0f)
  51. {
  52. outResult.SetError("Invalid convex radius");
  53. return;
  54. }
  55. outResult.Set(this);
  56. }
  57. AABox TriangleShape::GetLocalBounds() const
  58. {
  59. AABox bounds(mV1, mV1);
  60. bounds.Encapsulate(mV2);
  61. bounds.Encapsulate(mV3);
  62. bounds.ExpandBy(Vec3::sReplicate(mConvexRadius));
  63. return bounds;
  64. }
  65. AABox TriangleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  66. {
  67. JPH_ASSERT(IsValidScale(inScale));
  68. Vec3 v1 = inCenterOfMassTransform * (inScale * mV1);
  69. Vec3 v2 = inCenterOfMassTransform * (inScale * mV2);
  70. Vec3 v3 = inCenterOfMassTransform * (inScale * mV3);
  71. AABox bounds(v1, v1);
  72. bounds.Encapsulate(v2);
  73. bounds.Encapsulate(v3);
  74. bounds.ExpandBy(inScale * mConvexRadius);
  75. return bounds;
  76. }
  77. class TriangleShape::TriangleNoConvex final : public Support
  78. {
  79. public:
  80. TriangleNoConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) :
  81. mTriangleSuport(inV1, inV2, inV3)
  82. {
  83. static_assert(sizeof(TriangleNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  84. JPH_ASSERT(IsAligned(this, alignof(TriangleNoConvex)));
  85. }
  86. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  87. {
  88. return mTriangleSuport.GetSupport(inDirection);
  89. }
  90. virtual float GetConvexRadius() const override
  91. {
  92. return 0.0f;
  93. }
  94. private:
  95. TriangleConvexSupport mTriangleSuport;
  96. };
  97. class TriangleShape::TriangleWithConvex final : public Support
  98. {
  99. public:
  100. TriangleWithConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, float inConvexRadius) :
  101. mConvexRadius(inConvexRadius),
  102. mTriangleSuport(inV1, inV2, inV3)
  103. {
  104. static_assert(sizeof(TriangleWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  105. JPH_ASSERT(IsAligned(this, alignof(TriangleWithConvex)));
  106. }
  107. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  108. {
  109. Vec3 support = mTriangleSuport.GetSupport(inDirection);
  110. float len = inDirection.Length();
  111. if (len > 0.0f)
  112. support += (mConvexRadius / len) * inDirection;
  113. return support;
  114. }
  115. virtual float GetConvexRadius() const override
  116. {
  117. return mConvexRadius;
  118. }
  119. private:
  120. float mConvexRadius;
  121. TriangleConvexSupport mTriangleSuport;
  122. };
  123. const ConvexShape::Support *TriangleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  124. {
  125. switch (inMode)
  126. {
  127. case ESupportMode::IncludeConvexRadius:
  128. case ESupportMode::Default:
  129. if (mConvexRadius > 0.0f)
  130. return new (&inBuffer) TriangleWithConvex(inScale * mV1, inScale * mV2, inScale * mV3, mConvexRadius);
  131. [[fallthrough]];
  132. case ESupportMode::ExcludeConvexRadius:
  133. return new (&inBuffer) TriangleNoConvex(inScale * mV1, inScale * mV2, inScale * mV3);
  134. }
  135. JPH_ASSERT(false);
  136. return nullptr;
  137. }
  138. void TriangleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  139. {
  140. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  141. // Calculate transform with scale
  142. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  143. // Flip triangle if scaled inside out
  144. if (ScaleHelpers::IsInsideOut(inScale))
  145. {
  146. outVertices.push_back(transform * mV1);
  147. outVertices.push_back(transform * mV3);
  148. outVertices.push_back(transform * mV2);
  149. }
  150. else
  151. {
  152. outVertices.push_back(transform * mV1);
  153. outVertices.push_back(transform * mV2);
  154. outVertices.push_back(transform * mV3);
  155. }
  156. }
  157. MassProperties TriangleShape::GetMassProperties() const
  158. {
  159. // Object should always be static, return default mass properties
  160. return MassProperties();
  161. }
  162. Vec3 TriangleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  163. {
  164. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  165. Vec3 cross = (mV2 - mV1).Cross(mV3 - mV1);
  166. float len = cross.Length();
  167. return len != 0.0f? cross / len : Vec3::sAxisY();
  168. }
  169. void TriangleShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  170. {
  171. // A triangle has no volume
  172. outTotalVolume = outSubmergedVolume = 0.0f;
  173. outCenterOfBuoyancy = Vec3::sZero();
  174. }
  175. #ifdef JPH_DEBUG_RENDERER
  176. void TriangleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  177. {
  178. RVec3 v1 = inCenterOfMassTransform * (inScale * mV1);
  179. RVec3 v2 = inCenterOfMassTransform * (inScale * mV2);
  180. RVec3 v3 = inCenterOfMassTransform * (inScale * mV3);
  181. if (ScaleHelpers::IsInsideOut(inScale))
  182. swap(v1, v2);
  183. if (inDrawWireframe)
  184. inRenderer->DrawWireTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  185. else
  186. inRenderer->DrawTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  187. }
  188. #endif // JPH_DEBUG_RENDERER
  189. bool TriangleShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  190. {
  191. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  192. if (fraction < ioHit.mFraction)
  193. {
  194. ioHit.mFraction = fraction;
  195. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  196. return true;
  197. }
  198. return false;
  199. }
  200. void TriangleShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  201. {
  202. // Test shape filter
  203. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  204. return;
  205. // Back facing check
  206. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (mV2 - mV1).Cross(mV3 - mV1).Dot(inRay.mDirection) > 0.0f)
  207. return;
  208. // Test ray against triangle
  209. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  210. if (fraction < ioCollector.GetEarlyOutFraction())
  211. {
  212. // Better hit than the current hit
  213. RayCastResult hit;
  214. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  215. hit.mFraction = fraction;
  216. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  217. ioCollector.AddHit(hit);
  218. }
  219. }
  220. void TriangleShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  221. {
  222. // Can't be inside a triangle
  223. }
  224. void TriangleShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, [[maybe_unused]] float inDeltaTime, [[maybe_unused]] Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  225. {
  226. CollideSoftBodyVerticesVsTriangles collider(inCenterOfMassTransform, inScale);
  227. for (SoftBodyVertex *v = ioVertices, *sbv_end = ioVertices + inNumVertices; v < sbv_end; ++v)
  228. if (v->mInvMass > 0.0f)
  229. {
  230. collider.StartVertex(*v);
  231. collider.ProcessTriangle(mV1, mV2, mV3);
  232. collider.FinishVertex(*v, inCollidingShapeIndex);
  233. }
  234. }
  235. void TriangleShape::sCollideConvexVsTriangle(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)
  236. {
  237. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  238. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  239. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  240. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  241. CollideConvexVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  242. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  243. }
  244. void TriangleShape::sCollideSphereVsTriangle(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)
  245. {
  246. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  247. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  248. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  249. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  250. CollideSphereVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  251. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  252. }
  253. void TriangleShape::sCastConvexVsTriangle(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)
  254. {
  255. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  256. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  257. CastConvexVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  258. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  259. }
  260. void TriangleShape::sCastSphereVsTriangle(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)
  261. {
  262. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  263. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  264. CastSphereVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  265. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  266. }
  267. void TriangleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  268. {
  269. Vec3 scale;
  270. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  271. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  272. ts.SetShapeScale(mConvexRadius == 0.0f? scale : scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs()));
  273. ioCollector.AddHit(ts);
  274. }
  275. class TriangleShape::TSGetTrianglesContext
  276. {
  277. public:
  278. TSGetTrianglesContext(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) : mV1(inV1), mV2(inV2), mV3(inV3) { }
  279. Vec3 mV1;
  280. Vec3 mV2;
  281. Vec3 mV3;
  282. bool mIsDone = false;
  283. };
  284. void TriangleShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  285. {
  286. static_assert(sizeof(TSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  287. JPH_ASSERT(IsAligned(&ioContext, alignof(TSGetTrianglesContext)));
  288. Mat44 m = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale);
  289. new (&ioContext) TSGetTrianglesContext(m * mV1, m * mV2, m * mV3);
  290. }
  291. int TriangleShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  292. {
  293. static_assert(cGetTrianglesMinTrianglesRequested >= 3, "cGetTrianglesMinTrianglesRequested is too small");
  294. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  295. TSGetTrianglesContext &context = (TSGetTrianglesContext &)ioContext;
  296. // Only return the triangle the 1st time
  297. if (context.mIsDone)
  298. return 0;
  299. context.mIsDone = true;
  300. // Store triangle
  301. context.mV1.StoreFloat3(outTriangleVertices);
  302. context.mV2.StoreFloat3(outTriangleVertices + 1);
  303. context.mV3.StoreFloat3(outTriangleVertices + 2);
  304. // Store material
  305. if (outMaterials != nullptr)
  306. *outMaterials = GetMaterial();
  307. return 1;
  308. }
  309. void TriangleShape::SaveBinaryState(StreamOut &inStream) const
  310. {
  311. ConvexShape::SaveBinaryState(inStream);
  312. inStream.Write(mV1);
  313. inStream.Write(mV2);
  314. inStream.Write(mV3);
  315. inStream.Write(mConvexRadius);
  316. }
  317. void TriangleShape::RestoreBinaryState(StreamIn &inStream)
  318. {
  319. ConvexShape::RestoreBinaryState(inStream);
  320. inStream.Read(mV1);
  321. inStream.Read(mV2);
  322. inStream.Read(mV3);
  323. inStream.Read(mConvexRadius);
  324. }
  325. bool TriangleShape::IsValidScale(Vec3Arg inScale) const
  326. {
  327. return ConvexShape::IsValidScale(inScale) && (mConvexRadius == 0.0f || ScaleHelpers::IsUniformScale(inScale.Abs()));
  328. }
  329. void TriangleShape::sRegister()
  330. {
  331. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Triangle);
  332. f.mConstruct = []() -> Shape * { return new TriangleShape; };
  333. f.mColor = Color::sGreen;
  334. for (EShapeSubType s : sConvexSubShapeTypes)
  335. {
  336. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::Triangle, sCollideConvexVsTriangle);
  337. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::Triangle, sCastConvexVsTriangle);
  338. }
  339. // Specialized collision functions
  340. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCollideSphereVsTriangle);
  341. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCastSphereVsTriangle);
  342. }
  343. JPH_NAMESPACE_END