TriangleShape.cpp 15 KB

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