BoxShape.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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/BoxShape.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/CastResult.h>
  10. #include <Jolt/Physics/Collision/CollidePointResult.h>
  11. #include <Jolt/Physics/Collision/TransformedShape.h>
  12. #include <Jolt/Physics/Collision/CollideSoftBodyVertexIterator.h>
  13. #include <Jolt/Geometry/RayAABox.h>
  14. #include <Jolt/ObjectStream/TypeDeclarations.h>
  15. #include <Jolt/Core/StreamIn.h>
  16. #include <Jolt/Core/StreamOut.h>
  17. #ifdef JPH_DEBUG_RENDERER
  18. #include <Jolt/Renderer/DebugRenderer.h>
  19. #endif // JPH_DEBUG_RENDERER
  20. JPH_NAMESPACE_BEGIN
  21. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(BoxShapeSettings)
  22. {
  23. JPH_ADD_BASE_CLASS(BoxShapeSettings, ConvexShapeSettings)
  24. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mHalfExtent)
  25. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mConvexRadius)
  26. }
  27. static const Vec3 sUnitBoxTriangles[] = {
  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. Vec3(-1, 1, -1), Vec3(1, 1, -1), Vec3(1, -1, -1),
  39. Vec3(-1, 1, -1), Vec3(1, -1, -1), Vec3(-1, -1, -1)
  40. };
  41. ShapeSettings::ShapeResult BoxShapeSettings::Create() const
  42. {
  43. if (mCachedResult.IsEmpty())
  44. Ref<Shape> shape = new BoxShape(*this, mCachedResult);
  45. return mCachedResult;
  46. }
  47. BoxShape::BoxShape(const BoxShapeSettings &inSettings, ShapeResult &outResult) :
  48. ConvexShape(EShapeSubType::Box, inSettings, outResult),
  49. mHalfExtent(inSettings.mHalfExtent),
  50. mConvexRadius(min(inSettings.mConvexRadius, inSettings.mHalfExtent.ReduceMin()))
  51. {
  52. // Check half extents
  53. if (inSettings.mHalfExtent.ReduceMin() < 0.0f)
  54. {
  55. outResult.SetError("Invalid half extent");
  56. return;
  57. }
  58. // Check convex radius
  59. if (inSettings.mConvexRadius < 0.0f)
  60. {
  61. outResult.SetError("Invalid convex radius");
  62. return;
  63. }
  64. // Result is valid
  65. outResult.Set(this);
  66. }
  67. class BoxShape::Box final : public Support
  68. {
  69. public:
  70. Box(const AABox &inBox, float inConvexRadius) :
  71. mBox(inBox),
  72. mConvexRadius(inConvexRadius)
  73. {
  74. static_assert(sizeof(Box) <= sizeof(SupportBuffer), "Buffer size too small");
  75. JPH_ASSERT(IsAligned(this, alignof(Box)));
  76. }
  77. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  78. {
  79. return mBox.GetSupport(inDirection);
  80. }
  81. virtual float GetConvexRadius() const override
  82. {
  83. return mConvexRadius;
  84. }
  85. private:
  86. AABox mBox;
  87. float mConvexRadius;
  88. };
  89. const ConvexShape::Support *BoxShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  90. {
  91. // Scale our half extents
  92. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  93. switch (inMode)
  94. {
  95. case ESupportMode::IncludeConvexRadius:
  96. case ESupportMode::Default:
  97. {
  98. // Make box out of our half extents
  99. AABox box = AABox(-scaled_half_extent, scaled_half_extent);
  100. JPH_ASSERT(box.IsValid());
  101. return new (&inBuffer) Box(box, 0.0f);
  102. }
  103. case ESupportMode::ExcludeConvexRadius:
  104. {
  105. // Reduce the box by our convex radius
  106. float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  107. Vec3 convex_radius3 = Vec3::sReplicate(convex_radius);
  108. Vec3 reduced_half_extent = scaled_half_extent - convex_radius3;
  109. AABox box = AABox(-reduced_half_extent, reduced_half_extent);
  110. JPH_ASSERT(box.IsValid());
  111. return new (&inBuffer) Box(box, convex_radius);
  112. }
  113. }
  114. JPH_ASSERT(false);
  115. return nullptr;
  116. }
  117. void BoxShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  118. {
  119. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  120. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  121. AABox box(-scaled_half_extent, scaled_half_extent);
  122. box.GetSupportingFace(inDirection, outVertices);
  123. // Transform to world space
  124. for (Vec3 &v : outVertices)
  125. v = inCenterOfMassTransform * v;
  126. }
  127. MassProperties BoxShape::GetMassProperties() const
  128. {
  129. MassProperties p;
  130. p.SetMassAndInertiaOfSolidBox(2.0f * mHalfExtent, GetDensity());
  131. return p;
  132. }
  133. Vec3 BoxShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  134. {
  135. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  136. // Get component that is closest to the surface of the box
  137. int index = (inLocalSurfacePosition.Abs() - mHalfExtent).Abs().GetLowestComponentIndex();
  138. // Calculate normal
  139. Vec3 normal = Vec3::sZero();
  140. normal.SetComponent(index, inLocalSurfacePosition[index] > 0.0f? 1.0f : -1.0f);
  141. return normal;
  142. }
  143. #ifdef JPH_DEBUG_RENDERER
  144. void BoxShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  145. {
  146. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  147. inRenderer->DrawBox(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), GetLocalBounds(), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  148. }
  149. #endif // JPH_DEBUG_RENDERER
  150. bool BoxShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  151. {
  152. // Test hit against box
  153. float fraction = max(RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent), 0.0f);
  154. if (fraction < ioHit.mFraction)
  155. {
  156. ioHit.mFraction = fraction;
  157. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  158. return true;
  159. }
  160. return false;
  161. }
  162. void BoxShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  163. {
  164. // Test shape filter
  165. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  166. return;
  167. float min_fraction, max_fraction;
  168. RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent, min_fraction, max_fraction);
  169. if (min_fraction <= max_fraction // Ray should intersect
  170. && max_fraction >= 0.0f // End of ray should be inside box
  171. && min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction
  172. {
  173. // Better hit than the current hit
  174. RayCastResult hit;
  175. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  176. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  177. // Check front side
  178. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  179. {
  180. hit.mFraction = max(0.0f, min_fraction);
  181. ioCollector.AddHit(hit);
  182. }
  183. // Check back side hit
  184. if (inRayCastSettings.mBackFaceModeConvex == EBackFaceMode::CollideWithBackFaces
  185. && max_fraction < ioCollector.GetEarlyOutFraction())
  186. {
  187. hit.mFraction = max_fraction;
  188. ioCollector.AddHit(hit);
  189. }
  190. }
  191. }
  192. void BoxShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  193. {
  194. // Test shape filter
  195. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  196. return;
  197. if (Vec3::sLessOrEqual(inPoint.Abs(), mHalfExtent).TestAllXYZTrue())
  198. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  199. }
  200. void BoxShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
  201. {
  202. Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();
  203. Vec3 half_extent = inScale.Abs() * mHalfExtent;
  204. for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)
  205. if (v.GetInvMass() > 0.0f)
  206. {
  207. // Convert to local space
  208. Vec3 local_pos = inverse_transform * v.GetPosition();
  209. // Clamp point to inside box
  210. Vec3 clamped_point = Vec3::sMax(Vec3::sMin(local_pos, half_extent), -half_extent);
  211. // Test if point was inside
  212. if (clamped_point == local_pos)
  213. {
  214. // Calculate closest distance to surface
  215. Vec3 delta = half_extent - local_pos.Abs();
  216. int index = delta.GetLowestComponentIndex();
  217. float penetration = delta[index];
  218. if (v.UpdatePenetration(penetration))
  219. {
  220. // Calculate contact point and normal
  221. Vec3 possible_normals[] = { Vec3::sAxisX(), Vec3::sAxisY(), Vec3::sAxisZ() };
  222. Vec3 normal = local_pos.GetSign() * possible_normals[index];
  223. Vec3 point = normal * half_extent;
  224. // Store collision
  225. v.SetCollision(Plane::sFromPointAndNormal(point, normal).GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);
  226. }
  227. }
  228. else
  229. {
  230. // Calculate normal
  231. Vec3 normal = local_pos - clamped_point;
  232. float normal_length = normal.Length();
  233. // Penetration will be negative since we're not penetrating
  234. float penetration = -normal_length;
  235. if (v.UpdatePenetration(penetration))
  236. {
  237. normal /= normal_length;
  238. // Store collision
  239. v.SetCollision(Plane::sFromPointAndNormal(clamped_point, normal).GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);
  240. }
  241. }
  242. }
  243. }
  244. void BoxShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  245. {
  246. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, Mat44::sScale(mHalfExtent), sUnitBoxTriangles, std::size(sUnitBoxTriangles), GetMaterial());
  247. }
  248. int BoxShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  249. {
  250. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  251. }
  252. void BoxShape::SaveBinaryState(StreamOut &inStream) const
  253. {
  254. ConvexShape::SaveBinaryState(inStream);
  255. inStream.Write(mHalfExtent);
  256. inStream.Write(mConvexRadius);
  257. }
  258. void BoxShape::RestoreBinaryState(StreamIn &inStream)
  259. {
  260. ConvexShape::RestoreBinaryState(inStream);
  261. inStream.Read(mHalfExtent);
  262. inStream.Read(mConvexRadius);
  263. }
  264. void BoxShape::sRegister()
  265. {
  266. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Box);
  267. f.mConstruct = []() -> Shape * { return new BoxShape; };
  268. f.mColor = Color::sGreen;
  269. }
  270. JPH_NAMESPACE_END