| 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/SphereShape.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/RaySphere.h> |
| 16 | #include <Jolt/Geometry/Plane.h> |
| 17 | #include <Jolt/Core/StreamIn.h> |
| 18 | #include <Jolt/Core/StreamOut.h> |
| 19 | #include <Jolt/ObjectStream/TypeDeclarations.h> |
| 20 | #ifdef JPH_DEBUG_RENDERER |
| 21 | #include <Jolt/Renderer/DebugRenderer.h> |
| 22 | #endif // JPH_DEBUG_RENDERER |
| 23 | |
| 24 | JPH_NAMESPACE_BEGIN |
| 25 | |
| 26 | JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(SphereShapeSettings) |
| 27 | { |
| 28 | JPH_ADD_BASE_CLASS(SphereShapeSettings, ConvexShapeSettings) |
| 29 | |
| 30 | JPH_ADD_ATTRIBUTE(SphereShapeSettings, mRadius) |
| 31 | } |
| 32 | |
| 33 | ShapeSettings::ShapeResult SphereShapeSettings::Create() const |
| 34 | { |
| 35 | if (mCachedResult.IsEmpty()) |
| 36 | Ref<Shape> shape = new SphereShape(*this, mCachedResult); |
| 37 | return mCachedResult; |
| 38 | } |
| 39 | |
| 40 | SphereShape::SphereShape(const SphereShapeSettings &inSettings, ShapeResult &outResult) : |
| 41 | ConvexShape(EShapeSubType::Sphere, inSettings, outResult), |
| 42 | mRadius(inSettings.mRadius) |
| 43 | { |
| 44 | if (inSettings.mRadius <= 0.0f) |
| 45 | { |
| 46 | outResult.SetError("Invalid radius"); |
| 47 | return; |
| 48 | } |
| 49 | |
| 50 | outResult.Set(this); |
| 51 | } |
| 52 | |
| 53 | float SphereShape::GetScaledRadius(Vec3Arg inScale) const |
| 54 | { |
| 55 | JPH_ASSERT(IsValidScale(inScale)); |
| 56 | |
| 57 | Vec3 abs_scale = inScale.Abs(); |
| 58 | return abs_scale.GetX() * mRadius; |
| 59 | } |
| 60 | |
| 61 | AABox SphereShape::GetLocalBounds() const |
| 62 | { |
| 63 | Vec3 half_extent = Vec3::sReplicate(mRadius); |
| 64 | return AABox(-half_extent, half_extent); |
| 65 | } |
| 66 | |
| 67 | AABox SphereShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const |
| 68 | { |
| 69 | float scaled_radius = GetScaledRadius(inScale); |
| 70 | Vec3 half_extent = Vec3::sReplicate(scaled_radius); |
| 71 | AABox bounds(-half_extent, half_extent); |
| 72 | bounds.Translate(inCenterOfMassTransform.GetTranslation()); |
| 73 | return bounds; |
| 74 | } |
| 75 | |
| 76 | class SphereShape::SphereNoConvex final : public Support |
| 77 | { |
| 78 | public: |
| 79 | explicit SphereNoConvex(float inRadius) : |
| 80 | mRadius(inRadius) |
| 81 | { |
| 82 | static_assert(sizeof(SphereNoConvex) <= sizeof(SupportBuffer), "Buffer size too small"); |
| 83 | JPH_ASSERT(IsAligned(this, alignof(SphereNoConvex))); |
| 84 | } |
| 85 | |
| 86 | virtual Vec3 GetSupport(Vec3Arg inDirection) const override |
| 87 | { |
| 88 | return Vec3::sZero(); |
| 89 | } |
| 90 | |
| 91 | virtual float GetConvexRadius() const override |
| 92 | { |
| 93 | return mRadius; |
| 94 | } |
| 95 | |
| 96 | private: |
| 97 | float mRadius; |
| 98 | }; |
| 99 | |
| 100 | class SphereShape::SphereWithConvex final : public Support |
| 101 | { |
| 102 | public: |
| 103 | explicit SphereWithConvex(float inRadius) : |
| 104 | mRadius(inRadius) |
| 105 | { |
| 106 | static_assert(sizeof(SphereWithConvex) <= sizeof(SupportBuffer), "Buffer size too small"); |
| 107 | JPH_ASSERT(IsAligned(this, alignof(SphereWithConvex))); |
| 108 | } |
| 109 | |
| 110 | virtual Vec3 GetSupport(Vec3Arg inDirection) const override |
| 111 | { |
| 112 | float len = inDirection.Length(); |
| 113 | return len > 0.0f? (mRadius / len) * inDirection : Vec3::sZero(); |
| 114 | } |
| 115 | |
| 116 | virtual float GetConvexRadius() const override |
| 117 | { |
| 118 | return 0.0f; |
| 119 | } |
| 120 | |
| 121 | private: |
| 122 | float mRadius; |
| 123 | }; |
| 124 | |
| 125 | const ConvexShape::Support *SphereShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const |
| 126 | { |
| 127 | float scaled_radius = GetScaledRadius(inScale); |
| 128 | |
| 129 | switch (inMode) |
| 130 | { |
| 131 | case ESupportMode::IncludeConvexRadius: |
| 132 | return new (&inBuffer) SphereWithConvex(scaled_radius); |
| 133 | |
| 134 | case ESupportMode::ExcludeConvexRadius: |
| 135 | case ESupportMode::Default: |
| 136 | return new (&inBuffer) SphereNoConvex(scaled_radius); |
| 137 | } |
| 138 | |
| 139 | JPH_ASSERT(false); |
| 140 | return nullptr; |
| 141 | } |
| 142 | |
| 143 | MassProperties SphereShape::GetMassProperties() const |
| 144 | { |
| 145 | MassProperties p; |
| 146 | |
| 147 | // Calculate mass |
| 148 | float r2 = mRadius * mRadius; |
| 149 | p.mMass = (4.0f / 3.0f * JPH_PI) * mRadius * r2 * GetDensity(); |
| 150 | |
| 151 | // Calculate inertia |
| 152 | float inertia = (2.0f / 5.0f) * p.mMass * r2; |
| 153 | p.mInertia = Mat44::sScale(inertia); |
| 154 | |
| 155 | return p; |
| 156 | } |
| 157 | |
| 158 | Vec3 SphereShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const |
| 159 | { |
| 160 | JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID"); |
| 161 | |
| 162 | float len = inLocalSurfacePosition.Length(); |
| 163 | return len != 0.0f? inLocalSurfacePosition / len : Vec3::sAxisY(); |
| 164 | } |
| 165 | |
| 166 | void SphereShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const |
| 167 | { |
| 168 | float scaled_radius = GetScaledRadius(inScale); |
| 169 | outTotalVolume = (4.0f / 3.0f * JPH_PI) * Cubed(scaled_radius); |
| 170 | |
| 171 | float distance_to_surface = inSurface.SignedDistance(inCenterOfMassTransform.GetTranslation()); |
| 172 | if (distance_to_surface >= scaled_radius) |
| 173 | { |
| 174 | // Above surface |
| 175 | outSubmergedVolume = 0.0f; |
| 176 | outCenterOfBuoyancy = Vec3::sZero(); |
| 177 | } |
| 178 | else if (distance_to_surface <= -scaled_radius) |
| 179 | { |
| 180 | // Under surface |
| 181 | outSubmergedVolume = outTotalVolume; |
| 182 | outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation(); |
| 183 | } |
| 184 | else |
| 185 | { |
| 186 | // Intersecting surface |
| 187 | |
| 188 | // Calculate submerged volume, see: https://en.wikipedia.org/wiki/Spherical_cap |
| 189 | float h = scaled_radius - distance_to_surface; |
| 190 | outSubmergedVolume = (JPH_PI / 3.0f) * Square(h) * (3.0f * scaled_radius - h); |
| 191 | |
| 192 | // Calculate center of buoyancy, see: http://mathworld.wolfram.com/SphericalCap.html (eq 10) |
| 193 | float z = (3.0f / 4.0f) * Square(2.0f * scaled_radius - h) / (3.0f * scaled_radius - h); |
| 194 | outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation() - z * inSurface.GetNormal(); // Negative normal since we want the portion under the water |
| 195 | |
| 196 | #ifdef JPH_DEBUG_RENDERER |
| 197 | // Draw intersection between sphere and water plane |
| 198 | if (sDrawSubmergedVolumes) |
| 199 | { |
| 200 | Vec3 circle_center = inCenterOfMassTransform.GetTranslation() - distance_to_surface * inSurface.GetNormal(); |
| 201 | float circle_radius = sqrt(Square(scaled_radius) - Square(distance_to_surface)); |
| 202 | DebugRenderer::sInstance->DrawPie(inBaseOffset + circle_center, circle_radius, inSurface.GetNormal(), inSurface.GetNormal().GetNormalizedPerpendicular(), -JPH_PI, JPH_PI, Color::sGreen, DebugRenderer::ECastShadow::Off); |
| 203 | } |
| 204 | #endif // JPH_DEBUG_RENDERER |
| 205 | } |
| 206 | |
| 207 | #ifdef JPH_DEBUG_RENDERER |
| 208 | // Draw center of buoyancy |
| 209 | if (sDrawSubmergedVolumes) |
| 210 | DebugRenderer::sInstance->DrawWireSphere(inBaseOffset + outCenterOfBuoyancy, 0.05f, Color::sRed, 1); |
| 211 | #endif // JPH_DEBUG_RENDERER |
| 212 | } |
| 213 | |
| 214 | #ifdef JPH_DEBUG_RENDERER |
| 215 | void SphereShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const |
| 216 | { |
| 217 | DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid; |
| 218 | inRenderer->DrawUnitSphere(inCenterOfMassTransform * Mat44::sScale(mRadius * inScale.Abs().GetX()), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode); |
| 219 | } |
| 220 | #endif // JPH_DEBUG_RENDERER |
| 221 | |
| 222 | bool SphereShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const |
| 223 | { |
| 224 | float fraction = RaySphere(inRay.mOrigin, inRay.mDirection, Vec3::sZero(), mRadius); |
| 225 | if (fraction < ioHit.mFraction) |
| 226 | { |
| 227 | ioHit.mFraction = fraction; |
| 228 | ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID(); |
| 229 | return true; |
| 230 | } |
| 231 | return false; |
| 232 | } |
| 233 | |
| 234 | void SphereShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const |
| 235 | { |
| 236 | // Test shape filter |
| 237 | if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID())) |
| 238 | return; |
| 239 | |
| 240 | float min_fraction, max_fraction; |
| 241 | int num_results = RaySphere(inRay.mOrigin, inRay.mDirection, Vec3::sZero(), mRadius, min_fraction, max_fraction); |
| 242 | if (num_results > 0 // Ray should intersect |
| 243 | && max_fraction >= 0.0f // End of ray should be inside sphere |
| 244 | && min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction |
| 245 | { |
| 246 | // Better hit than the current hit |
| 247 | RayCastResult hit; |
| 248 | hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext()); |
| 249 | hit.mSubShapeID2 = inSubShapeIDCreator.GetID(); |
| 250 | |
| 251 | // Check front side hit |
| 252 | if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f) |
| 253 | { |
| 254 | hit.mFraction = max(0.0f, min_fraction); |
| 255 | ioCollector.AddHit(hit); |
| 256 | } |
| 257 | |
| 258 | // Check back side hit |
| 259 | if (inRayCastSettings.mBackFaceModeConvex == EBackFaceMode::CollideWithBackFaces |
| 260 | && num_results > 1 // Ray should have 2 intersections |
| 261 | && max_fraction < ioCollector.GetEarlyOutFraction()) // End of ray should be before early out fraction |
| 262 | { |
| 263 | hit.mFraction = max_fraction; |
| 264 | ioCollector.AddHit(hit); |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | void SphereShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const |
| 270 | { |
| 271 | // Test shape filter |
| 272 | if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID())) |
| 273 | return; |
| 274 | |
| 275 | if (inPoint.LengthSq() <= Square(mRadius)) |
| 276 | ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() }); |
| 277 | } |
| 278 | |
| 279 | void SphereShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const |
| 280 | { |
| 281 | Vec3 center = inCenterOfMassTransform.GetTranslation(); |
| 282 | float radius = GetScaledRadius(inScale); |
| 283 | |
| 284 | for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v) |
| 285 | if (v.GetInvMass() > 0.0f) |
| 286 | { |
| 287 | // Calculate penetration |
| 288 | Vec3 delta = v.GetPosition() - center; |
| 289 | float distance = delta.Length(); |
| 290 | float penetration = radius - distance; |
| 291 | if (v.UpdatePenetration(penetration)) |
| 292 | { |
| 293 | // Calculate contact point and normal |
| 294 | Vec3 normal = distance > 0.0f? delta / distance : Vec3::sAxisY(); |
| 295 | Vec3 point = center + radius * normal; |
| 296 | |
| 297 | // Store collision |
| 298 | v.SetCollision(Plane::sFromPointAndNormal(point, normal), inCollidingShapeIndex); |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | void SphereShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const |
| 304 | { |
| 305 | float scaled_radius = GetScaledRadius(inScale); |
| 306 | new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, Vec3::sOne(), Mat44::sScale(scaled_radius), sUnitSphereTriangles.data(), sUnitSphereTriangles.size(), GetMaterial()); |
| 307 | } |
| 308 | |
| 309 | int SphereShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const |
| 310 | { |
| 311 | return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials); |
| 312 | } |
| 313 | |
| 314 | void SphereShape::SaveBinaryState(StreamOut &inStream) const |
| 315 | { |
| 316 | ConvexShape::SaveBinaryState(inStream); |
| 317 | |
| 318 | inStream.Write(mRadius); |
| 319 | } |
| 320 | |
| 321 | void SphereShape::RestoreBinaryState(StreamIn &inStream) |
| 322 | { |
| 323 | ConvexShape::RestoreBinaryState(inStream); |
| 324 | |
| 325 | inStream.Read(mRadius); |
| 326 | } |
| 327 | |
| 328 | bool SphereShape::IsValidScale(Vec3Arg inScale) const |
| 329 | { |
| 330 | return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScale(inScale.Abs()); |
| 331 | } |
| 332 | |
| 333 | Vec3 SphereShape::MakeScaleValid(Vec3Arg inScale) const |
| 334 | { |
| 335 | Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale); |
| 336 | |
| 337 | return scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs()); |
| 338 | } |
| 339 | |
| 340 | void SphereShape::sRegister() |
| 341 | { |
| 342 | ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Sphere); |
| 343 | f.mConstruct = []() -> Shape * { return new SphereShape; }; |
| 344 | f.mColor = Color::sGreen; |
| 345 | } |
| 346 | |
| 347 | JPH_NAMESPACE_END |