Move Vectormath main
C++20 game and graphics mathematics
Loading...
Searching...
No Matches
Sphere3.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cmath>
4#include <optional>
5#include <type_traits>
6
7#include <mv/math/Vec4.hpp>
9
10namespace mv::math
11{
12 // Move-owned sphere contract; operations cross-checked against DirectXMath
13 // DirectXCollision.inl (MIT).
14 template <typename T>
15 requires std::is_floating_point_v<T>
16 class Sphere3
17 {
18 public:
19 using Component = T;
20
22
25 {
26 if (!std::isfinite(center.X()) || !std::isfinite(center.Y()) ||
27 !std::isfinite(center.Z()) || !(radius >= T(0)) ||
28 !std::isfinite(radius))
29 {
30 return std::nullopt;
31 }
32 return Sphere3(center, radius, UncheckedTag{});
33 }
34
36 {
37 return Point3<T>(Value_.X(), Value_.Y(), Value_.Z());
38 }
39
41 {
42 return Value_.W();
43 }
44
46 {
47 return Radius() * T(2);
48 }
49
50 [[nodiscard]] bool Contains(const Point3<T>& point) const noexcept
51 {
52 using Calculation =
53 std::conditional_t<(sizeof(T) < sizeof(double)), double, T>;
54 const Calculation x = static_cast<Calculation>(point.X()) -
55 static_cast<Calculation>(Value_.X());
56 const Calculation y = static_cast<Calculation>(point.Y()) -
57 static_cast<Calculation>(Value_.Y());
58 const Calculation z = static_cast<Calculation>(point.Z()) -
59 static_cast<Calculation>(Value_.Z());
60 const Calculation radius = static_cast<Calculation>(Radius());
61 return x * x + y * y + z * z <= radius * radius;
62 }
63
64 [[nodiscard]] friend bool operator==(const Sphere3& left,
65 const Sphere3& right) noexcept
66 {
67 return left.Value_ == right.Value_;
68 }
69
70 private:
71 struct UncheckedTag
72 {
73 };
74
75 Sphere3(const Point3<T>& center, T radius, UncheckedTag) noexcept :
76 Value_(center.X(), center.Y(), center.Z(), radius)
77 {
78 }
79
80 Vec4<T> Value_{};
81 };
82
85} // namespace mv::math
86
87static_assert(sizeof(mv::math::Sphere3f) == 16);
88static_assert(alignof(mv::math::Sphere3f) == 16);
89static_assert(std::is_trivially_copyable_v<mv::math::Sphere3f>);
90static_assert(std::is_standard_layout_v<mv::math::Sphere3f>);
91static_assert(sizeof(mv::math::Sphere3d) == 32);
92static_assert(alignof(mv::math::Sphere3d) == 32);
93static_assert(std::is_trivially_copyable_v<mv::math::Sphere3d>);
94static_assert(std::is_standard_layout_v<mv::math::Sphere3d>);
T Radius() const noexcept
Definition Sphere3.hpp:40
Point3< T > Center() const noexcept
Definition Sphere3.hpp:35
static std::optional< Sphere3 > TryFromCenterRadius(const Point3< T > &center, T radius) noexcept
Definition Sphere3.hpp:23
Sphere3() noexcept=default
friend bool operator==(const Sphere3 &left, const Sphere3 &right) noexcept
Definition Sphere3.hpp:64
T Diameter() const noexcept
Definition Sphere3.hpp:45
bool Contains(const Point3< T > &point) const noexcept
Definition Sphere3.hpp:50
Sphere3< float > Sphere3f
Definition Sphere3.hpp:83
Sphere3< double > Sphere3d
Definition Sphere3.hpp:84