Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/jolt_physics/Jolt/Geometry/Sphere.h
9913 views
1
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3
// SPDX-License-Identifier: MIT
4
5
#pragma once
6
7
#include <Jolt/Geometry/AABox.h>
8
9
JPH_NAMESPACE_BEGIN
10
11
class [[nodiscard]] Sphere
12
{
13
public:
14
JPH_OVERRIDE_NEW_DELETE
15
16
/// Constructor
17
inline Sphere() = default;
18
inline Sphere(const Float3 &inCenter, float inRadius) : mCenter(inCenter), mRadius(inRadius) { }
19
inline Sphere(Vec3Arg inCenter, float inRadius) : mRadius(inRadius) { inCenter.StoreFloat3(&mCenter); }
20
21
/// Calculate the support vector for this convex shape.
22
inline Vec3 GetSupport(Vec3Arg inDirection) const
23
{
24
float length = inDirection.Length();
25
return length > 0.0f ? Vec3::sLoadFloat3Unsafe(mCenter) + (mRadius/ length) * inDirection : Vec3::sLoadFloat3Unsafe(mCenter);
26
}
27
28
// Properties
29
inline Vec3 GetCenter() const { return Vec3::sLoadFloat3Unsafe(mCenter); }
30
inline float GetRadius() const { return mRadius; }
31
32
/// Test if two spheres overlap
33
inline bool Overlaps(const Sphere &inB) const
34
{
35
return (Vec3::sLoadFloat3Unsafe(mCenter) - Vec3::sLoadFloat3Unsafe(inB.mCenter)).LengthSq() <= Square(mRadius + inB.mRadius);
36
}
37
38
/// Check if this sphere overlaps with a box
39
inline bool Overlaps(const AABox &inOther) const
40
{
41
return inOther.GetSqDistanceTo(GetCenter()) <= Square(mRadius);
42
}
43
44
/// Create the minimal sphere that encapsulates this sphere and inPoint
45
inline void EncapsulatePoint(Vec3Arg inPoint)
46
{
47
// Calculate distance between point and center
48
Vec3 center = GetCenter();
49
Vec3 d_vec = inPoint - center;
50
float d_sq = d_vec.LengthSq();
51
if (d_sq > Square(mRadius))
52
{
53
// It is further away than radius, we need to widen the sphere
54
// The diameter of the new sphere is radius + d, so the new radius is half of that
55
float d = sqrt(d_sq);
56
float radius = 0.5f * (mRadius + d);
57
58
// The center needs to shift by new radius - old radius in the direction of d
59
center += (radius - mRadius) / d * d_vec;
60
61
// Store new sphere
62
center.StoreFloat3(&mCenter);
63
mRadius = radius;
64
}
65
}
66
67
private:
68
Float3 mCenter;
69
float mRadius;
70
};
71
72
JPH_NAMESPACE_END
73
74