BoxShape.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/Collision/Shape/BoxShape.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/CastResult.h>
  9. #include <Jolt/Physics/Collision/CollidePointResult.h>
  10. #include <Jolt/Physics/Collision/TransformedShape.h>
  11. #include <Jolt/Geometry/RayAABox.h>
  12. #include <Jolt/ObjectStream/TypeDeclarations.h>
  13. #include <Jolt/Core/StreamIn.h>
  14. #include <Jolt/Core/StreamOut.h>
  15. #ifdef JPH_DEBUG_RENDERER
  16. #include <Jolt/Renderer/DebugRenderer.h>
  17. #endif // JPH_DEBUG_RENDERER
  18. JPH_NAMESPACE_BEGIN
  19. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(BoxShapeSettings)
  20. {
  21. JPH_ADD_BASE_CLASS(BoxShapeSettings, ConvexShapeSettings)
  22. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mHalfExtent)
  23. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mConvexRadius)
  24. }
  25. static const Vec3 sUnitBoxTriangles[] = {
  26. Vec3(-1, 1, -1), Vec3(-1, 1, 1), Vec3(1, 1, 1),
  27. Vec3(-1, 1, -1), Vec3(1, 1, 1), Vec3(1, 1, -1),
  28. Vec3(-1, -1, -1), Vec3(1, -1, -1), Vec3(1, -1, 1),
  29. Vec3(-1, -1, -1), Vec3(1, -1, 1), Vec3(-1, -1, 1),
  30. Vec3(-1, 1, -1), Vec3(-1, -1, -1), Vec3(-1, -1, 1),
  31. Vec3(-1, 1, -1), Vec3(-1, -1, 1), Vec3(-1, 1, 1),
  32. Vec3(1, 1, 1), Vec3(1, -1, 1), Vec3(1, -1, -1),
  33. Vec3(1, 1, 1), Vec3(1, -1, -1), Vec3(1, 1, -1),
  34. Vec3(-1, 1, 1), Vec3(-1, -1, 1), Vec3(1, -1, 1),
  35. Vec3(-1, 1, 1), Vec3(1, -1, 1), Vec3(1, 1, 1),
  36. Vec3(-1, 1, -1), Vec3(1, 1, -1), Vec3(1, -1, -1),
  37. Vec3(-1, 1, -1), Vec3(1, -1, -1), Vec3(-1, -1, -1)
  38. };
  39. ShapeSettings::ShapeResult BoxShapeSettings::Create() const
  40. {
  41. if (mCachedResult.IsEmpty())
  42. Ref<Shape> shape = new BoxShape(*this, mCachedResult);
  43. return mCachedResult;
  44. }
  45. BoxShape::BoxShape(const BoxShapeSettings &inSettings, ShapeResult &outResult) :
  46. ConvexShape(EShapeSubType::Box, inSettings, outResult),
  47. mHalfExtent(inSettings.mHalfExtent),
  48. mConvexRadius(inSettings.mConvexRadius)
  49. {
  50. // Check convex radius
  51. if (inSettings.mConvexRadius < 0.0f
  52. || inSettings.mHalfExtent.ReduceMin() <= inSettings.mConvexRadius)
  53. {
  54. outResult.SetError("Invalid convex radius");
  55. return;
  56. }
  57. // Result is valid
  58. outResult.Set(this);
  59. }
  60. class BoxShape::Box final : public Support
  61. {
  62. public:
  63. Box(const AABox &inBox, float inConvexRadius) :
  64. mBox(inBox),
  65. mConvexRadius(inConvexRadius)
  66. {
  67. static_assert(sizeof(Box) <= sizeof(SupportBuffer), "Buffer size too small");
  68. JPH_ASSERT(IsAligned(this, alignof(Box)));
  69. }
  70. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  71. {
  72. return mBox.GetSupport(inDirection);
  73. }
  74. virtual float GetConvexRadius() const override
  75. {
  76. return mConvexRadius;
  77. }
  78. private:
  79. AABox mBox;
  80. float mConvexRadius;
  81. };
  82. const ConvexShape::Support *BoxShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  83. {
  84. // Scale our half extents
  85. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  86. switch (inMode)
  87. {
  88. case ESupportMode::IncludeConvexRadius:
  89. {
  90. // Make box out of our half extents
  91. AABox box = AABox(-scaled_half_extent, scaled_half_extent);
  92. JPH_ASSERT(box.IsValid());
  93. return new (&inBuffer) Box(box, 0.0f);
  94. }
  95. case ESupportMode::ExcludeConvexRadius:
  96. {
  97. // Reduce the box by our convex radius
  98. float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  99. Vec3 convex_radius3 = Vec3::sReplicate(convex_radius);
  100. Vec3 reduced_half_extent = scaled_half_extent - convex_radius3;
  101. AABox box = AABox(-reduced_half_extent, reduced_half_extent);
  102. JPH_ASSERT(box.IsValid());
  103. return new (&inBuffer) Box(box, convex_radius);
  104. }
  105. }
  106. JPH_ASSERT(false);
  107. return nullptr;
  108. }
  109. void BoxShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  110. {
  111. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  112. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  113. AABox box(-scaled_half_extent, scaled_half_extent);
  114. box.GetSupportingFace(inDirection, outVertices);
  115. // Transform to world space
  116. for (Vec3 &v : outVertices)
  117. v = inCenterOfMassTransform * v;
  118. }
  119. MassProperties BoxShape::GetMassProperties() const
  120. {
  121. MassProperties p;
  122. p.SetMassAndInertiaOfSolidBox(2.0f * mHalfExtent, GetDensity());
  123. return p;
  124. }
  125. Vec3 BoxShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  126. {
  127. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  128. // Get component that is closest to the surface of the box
  129. int index = (inLocalSurfacePosition.Abs() - mHalfExtent).Abs().GetLowestComponentIndex();
  130. // Calculate normal
  131. Vec3 normal = Vec3::sZero();
  132. normal.SetComponent(index, inLocalSurfacePosition[index] > 0.0f? 1.0f : -1.0f);
  133. return normal;
  134. }
  135. #ifdef JPH_DEBUG_RENDERER
  136. void BoxShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  137. {
  138. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  139. inRenderer->DrawBox(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), GetLocalBounds(), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  140. }
  141. #endif // JPH_DEBUG_RENDERER
  142. bool BoxShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  143. {
  144. // Test hit against box
  145. float fraction = max(RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent), 0.0f);
  146. if (fraction < ioHit.mFraction)
  147. {
  148. ioHit.mFraction = fraction;
  149. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  150. return true;
  151. }
  152. return false;
  153. }
  154. void BoxShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  155. {
  156. // Test shape filter
  157. if (!inShapeFilter.ShouldCollide(inSubShapeIDCreator.GetID()))
  158. return;
  159. float min_fraction, max_fraction;
  160. RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent, min_fraction, max_fraction);
  161. if (min_fraction <= max_fraction // Ray should intersect
  162. && max_fraction >= 0.0f // End of ray should be inside box
  163. && min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction
  164. {
  165. // Better hit than the current hit
  166. RayCastResult hit;
  167. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  168. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  169. // Check front side
  170. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  171. {
  172. hit.mFraction = max(0.0f, min_fraction);
  173. ioCollector.AddHit(hit);
  174. }
  175. // Check back side hit
  176. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  177. && max_fraction < ioCollector.GetEarlyOutFraction())
  178. {
  179. hit.mFraction = max_fraction;
  180. ioCollector.AddHit(hit);
  181. }
  182. }
  183. }
  184. void BoxShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  185. {
  186. // Test shape filter
  187. if (!inShapeFilter.ShouldCollide(inSubShapeIDCreator.GetID()))
  188. return;
  189. if (Vec3::sLessOrEqual(inPoint.Abs(), mHalfExtent).TestAllXYZTrue())
  190. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  191. }
  192. void BoxShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  193. {
  194. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, Mat44::sScale(mHalfExtent), sUnitBoxTriangles, sizeof(sUnitBoxTriangles) / sizeof(Vec3), GetMaterial());
  195. }
  196. int BoxShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  197. {
  198. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  199. }
  200. void BoxShape::SaveBinaryState(StreamOut &inStream) const
  201. {
  202. ConvexShape::SaveBinaryState(inStream);
  203. inStream.Write(mHalfExtent);
  204. inStream.Write(mConvexRadius);
  205. }
  206. void BoxShape::RestoreBinaryState(StreamIn &inStream)
  207. {
  208. ConvexShape::RestoreBinaryState(inStream);
  209. inStream.Read(mHalfExtent);
  210. inStream.Read(mConvexRadius);
  211. }
  212. void BoxShape::sRegister()
  213. {
  214. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Box);
  215. f.mConstruct = []() -> Shape * { return new BoxShape; };
  216. f.mColor = Color::sGreen;
  217. }
  218. JPH_NAMESPACE_END