BoxShape.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt.h>
  4. #include <Physics/Collision/Shape/BoxShape.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/CastResult.h>
  9. #include <Physics/Collision/CollidePointResult.h>
  10. #include <Physics/Collision/TransformedShape.h>
  11. #include <Geometry/RayAABox.h>
  12. #include <ObjectStream/TypeDeclarations.h>
  13. #include <Core/StreamIn.h>
  14. #include <Core/StreamOut.h>
  15. #ifdef JPH_DEBUG_RENDERER
  16. #include <Renderer/DebugRenderer.h>
  17. #endif // JPH_DEBUG_RENDERER
  18. namespace JPH {
  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(Vec3Arg inDirection, Vec3Arg inScale, SupportingFace &outVertices) const
  110. {
  111. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  112. AABox box(-scaled_half_extent, scaled_half_extent);
  113. box.GetSupportingFace(inDirection, outVertices);
  114. }
  115. MassProperties BoxShape::GetMassProperties() const
  116. {
  117. MassProperties p;
  118. p.SetMassAndInertiaOfSolidBox(2.0f * mHalfExtent, GetDensity());
  119. return p;
  120. }
  121. Vec3 BoxShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  122. {
  123. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  124. // Get component that is closest to the surface of the box
  125. int index = (inLocalSurfacePosition.Abs() - mHalfExtent).Abs().GetLowestComponentIndex();
  126. // Calculate normal
  127. Vec3 normal = Vec3::sZero();
  128. normal.SetComponent(index, inLocalSurfacePosition[index] > 0.0f? 1.0f : -1.0f);
  129. return normal;
  130. }
  131. #ifdef JPH_DEBUG_RENDERER
  132. void BoxShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  133. {
  134. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  135. inRenderer->DrawBox(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), GetLocalBounds(), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  136. }
  137. #endif // JPH_DEBUG_RENDERER
  138. bool BoxShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  139. {
  140. // Test hit against box
  141. float fraction = max(RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent), 0.0f);
  142. if (fraction < ioHit.mFraction)
  143. {
  144. ioHit.mFraction = fraction;
  145. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  146. return true;
  147. }
  148. return false;
  149. }
  150. void BoxShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const
  151. {
  152. float min_fraction, max_fraction;
  153. RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent, min_fraction, max_fraction);
  154. if (min_fraction <= max_fraction // Ray should intersect
  155. && max_fraction >= 0.0f // End of ray should be inside box
  156. && min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction
  157. {
  158. // Better hit than the current hit
  159. RayCastResult hit;
  160. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  161. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  162. // Check front side
  163. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  164. {
  165. hit.mFraction = max(0.0f, min_fraction);
  166. ioCollector.AddHit(hit);
  167. }
  168. // Check back side hit
  169. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  170. && max_fraction < ioCollector.GetEarlyOutFraction())
  171. {
  172. hit.mFraction = max_fraction;
  173. ioCollector.AddHit(hit);
  174. }
  175. }
  176. }
  177. void BoxShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const
  178. {
  179. if (Vec3::sLessOrEqual(inPoint.Abs(), mHalfExtent).TestAllXYZTrue())
  180. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  181. }
  182. void BoxShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  183. {
  184. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, Mat44::sScale(mHalfExtent), sUnitBoxTriangles, sizeof(sUnitBoxTriangles) / sizeof(Vec3), GetMaterial());
  185. }
  186. int BoxShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  187. {
  188. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  189. }
  190. void BoxShape::SaveBinaryState(StreamOut &inStream) const
  191. {
  192. ConvexShape::SaveBinaryState(inStream);
  193. inStream.Write(mHalfExtent);
  194. inStream.Write(mConvexRadius);
  195. }
  196. void BoxShape::RestoreBinaryState(StreamIn &inStream)
  197. {
  198. ConvexShape::RestoreBinaryState(inStream);
  199. inStream.Read(mHalfExtent);
  200. inStream.Read(mConvexRadius);
  201. }
  202. void BoxShape::sRegister()
  203. {
  204. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Box);
  205. f.mConstruct = []() -> Shape * { return new BoxShape; };
  206. f.mColor = Color::sGreen;
  207. }
  208. } // JPH