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