TriangleShape.cpp 15 KB

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