TriangleShape.cpp 12 KB

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