improved angle class

This commit is contained in:
2026-07-19 23:44:50 +03:00
parent 5591eb6f88
commit ecc9852cd8
6 changed files with 99 additions and 66 deletions
+12 -10
View File
@@ -3,8 +3,8 @@
> Header: `omath/trigonometry/angle.hpp`
> Namespace: `omath`
> Template: `Angle<Type = float, min = 0, max = 360, flags = AngleFlags::Normalized>`
> Requires: `std::is_arithmetic_v<Type>`
> Formatters: `std::formatter` for `char`, `wchar_t`, `char8_t` → `"{}deg"`
> Requires: `std::is_floating_point_v<Type>`
> Formatters: `std::formatter` for `char` and `wchar_t` → `"{}deg"`
---
@@ -14,7 +14,7 @@
Two behaviors via `AngleFlags`:
* `AngleFlags::Normalized` (default): values are wrapped into `[min, max]` using `angles::wrap_angle`.
* `AngleFlags::Normalized` (default): values are wrapped into `[min, max)` using `angles::wrap_angle`.
* `AngleFlags::Clamped`: values are clamped to `[min, max]` using `std::clamp`.
---
@@ -28,12 +28,16 @@ enum class AngleFlags { Normalized = 0, Clamped = 1 };
template<class Type = float, Type min = Type(0), Type max = Type(360),
AngleFlags flags = AngleFlags::Normalized>
requires std::is_arithmetic_v<Type>
requires std::is_floating_point_v<Type>
class Angle {
public:
// Construction
static constexpr Angle from_degrees(const Type& deg) noexcept;
static constexpr Angle from_radians(const Type& rad) noexcept;
static constexpr Angle from_asin(const Type& value) noexcept;
static constexpr Angle from_acos(const Type& value) noexcept;
static constexpr Angle from_atan(const Type& value) noexcept;
static constexpr Angle from_atan2(const Type& y, const Type& x) noexcept;
constexpr Angle() noexcept; // 0 deg, adjusted by flags/range
// Accessors / conversions (degrees stored internally)
@@ -45,10 +49,9 @@ public:
Type sin() const noexcept;
Type cos() const noexcept;
Type tan() const noexcept;
Type atan() const noexcept; // atan(as_radians()) (rarely used)
Type cot() const noexcept; // cos()/sin() (watch sin≈0)
// Arithmetic (wraps or clamps per flags and [min,max])
// Arithmetic (wraps or clamps per flags and configured range)
constexpr Angle& operator+=(const Angle&) noexcept;
constexpr Angle& operator-=(const Angle&) noexcept;
constexpr Angle operator+(const Angle&) noexcept;
@@ -68,7 +71,7 @@ public:
std::format("{}", Angle<float>::from_degrees(45)); // "45deg"
```
Formatters exist for `char`, `wchar_t`, and `char8_t`.
Formatters exist for `char` and `wchar_t`.
---
@@ -116,10 +119,9 @@ float deg = *yaw; // same as yaw.as_degrees()
## Semantics & notes
* **Storage & units:** Internally stores **degrees** (`Type m_angle`). `as_radians()`/`from_radians()` use the project helpers in `omath::angles`.
* **Arithmetic honors policy:** `operator+=`/`-=` and the binary `+`/`-` apply **wrap** or **clamp** in `[min,max]`, mirroring construction behavior.
* **`atan()`**: returns `std::atan(as_radians())` (the arctangent of the *radian value*). This is mathematically unusual for an angle type and is rarely useful; prefer `tan()`/`atan2` in client code when solving geometry problems.
* **Arithmetic honors policy:** `operator+=`/`-=` and the binary `+`/`-` apply **wrap** or **clamp**, mirroring construction behavior.
* **`cot()` / `tan()` singularities:** Near multiples where `sin() ≈ 0` or `cos() ≈ 0`, results blow up. Guard in your usage if inputs can approach these points.
* **Comparison:** `operator<=>` is defaulted. With normalization, distinct representatives can compare as expected (e.g., `-180` vs `180` in signed ranges are distinct endpoints).
* **Comparison:** `operator<=>` is defaulted. Normalization canonicalizes the maximum endpoint to the minimum endpoint.
* **No implicit numeric conversion:** Theres **no `operator Type()`**. Use `as_degrees()`/`as_radians()` (or `*angle`) explicitly—this intentional friction avoids unit mistakes.
---
+8 -8
View File
@@ -4,7 +4,7 @@
> Namespace: `omath::angles`
> All functions are `[[nodiscard]]` and `noexcept` where applicable.
A small set of constexpr-friendly utilities for converting between degrees/radians, converting horizontal/vertical field of view, and wrapping angles into a closed interval.
A small set of constexpr-friendly utilities for converting between degrees/radians, converting horizontal/vertical field of view, and wrapping angles into a half-open interval.
---
@@ -29,9 +29,9 @@ template<class Type>
requires std::is_floating_point_v<Type>
Type vertical_fov_to_horizontal(const Type& vertical_fov, const Type& aspect) noexcept;
// Wrap angle into [min, max] (any arithmetic type)
// Wrap angle into [min, max) (floating-point types)
template<class Type>
requires std::is_arithmetic_v<Type>
requires std::is_floating_point_v<Type>
Type wrap_angle(const Type& angle, const Type& min, const Type& max) noexcept;
```
@@ -66,10 +66,10 @@ Formulas (in radians):
### Wrapping angles (or any periodic value)
Wrap any numeric `angle` into `[min, max]`:
Wrap any floating-point `angle` into `[min, max)`:
```cpp
// Wrap degrees into [0, 360]
// Wrap degrees into [0, 360)
float a = omath::angles::wrap_angle( 370.0f, 0.0f, 360.0f); // 10
float b = omath::angles::wrap_angle( -15.0f, 0.0f, 360.0f); // 345
// Signed range [-180,180]
@@ -83,10 +83,10 @@ float c = omath::angles::wrap_angle( 200.0f, -180.0f, 180.0f); // -160
* **Type requirements**
* Converters & FOV helpers require **floating-point** `Type`.
* `wrap_angle` accepts any arithmetic `Type` (floats or integers).
* `wrap_angle` accepts floating-point types.
* **Aspect ratio** must be **positive** and finite. For `aspect == 0` the FOV helpers are undefined.
* **Units**: FOV functions accept/return **degrees** but compute internally in radians.
* **Wrapping interval**: Behavior assumes `max > min`. The result lies in the **closed interval** `[min, max]` with modulo arithmetic; if you need half-open behavior (e.g., `[min,max)`), adjust your range or post-process endpoint cases.
* **Wrapping interval**: Behavior assumes `max > min`. The result lies in the half-open interval `[min, max)`.
* **constexpr**: Converters are `constexpr`; FOV helpers are runtime constexpr-compatible except for `std::atan/std::tan` constraints on some standard libraries.
---
@@ -103,5 +103,5 @@ float v = horizontal_fov_to_vertical(90.0f, 16.0f/9.0f);
float h = vertical_fov_to_horizontal(v, 16.0f/9.0f);
assert(std::abs(h - 90.0f) < 1e-5f);
assert(wrap_angle(360.0f, 0.0f, 360.0f) == 0.0f || wrap_angle(360.0f, 0.0f, 360.0f) == 360.0f);
assert(wrap_angle(360.0f, 0.0f, 360.0f) == 0.0f);
```
+31 -32
View File
@@ -6,7 +6,9 @@
#include "omath/internal/constexpr_math.hpp"
#include "omath/trigonometry/angles.hpp"
#include <algorithm>
#include <compare>
#include <format>
#include <type_traits>
#include <utility>
namespace omath
@@ -18,7 +20,7 @@ namespace omath
};
template<class Type = float, Type min = Type(0), Type max = Type(360), AngleFlags flags = AngleFlags::Normalized>
requires std::is_arithmetic_v<Type>
requires std::is_floating_point_v<Type>
class Angle
{
Type m_angle;
@@ -43,7 +45,7 @@ namespace omath
{
return Angle{degrees};
}
constexpr Angle() noexcept: m_angle(0)
constexpr Angle() noexcept: Angle(Type{0})
{
}
[[nodiscard]]
@@ -52,6 +54,30 @@ namespace omath
return Angle{angles::radians_to_degrees<Type>(degrees)};
}
[[nodiscard]]
constexpr static Angle from_asin(const Type& value) noexcept
{
return from_radians(internal::asin(value));
}
[[nodiscard]]
constexpr static Angle from_acos(const Type& value) noexcept
{
return from_radians(internal::acos(value));
}
[[nodiscard]]
constexpr static Angle from_atan(const Type& value) noexcept
{
return from_radians(internal::atan(value));
}
[[nodiscard]]
constexpr static Angle from_atan2(const Type& y, const Type& x) noexcept
{
return from_radians(internal::atan2(y, x));
}
[[nodiscard]]
constexpr const Type& operator*() const noexcept
{
@@ -88,12 +114,6 @@ namespace omath
return internal::tan(as_radians());
}
[[nodiscard]]
constexpr Type atan() const noexcept
{
return internal::atan(as_radians());
}
[[nodiscard]]
constexpr Type cot() const noexcept
{
@@ -121,7 +141,8 @@ namespace omath
constexpr Angle& operator-=(const Angle& other) noexcept
{
return operator+=(-other);
*this = Angle{m_angle - other.m_angle};
return *this;
}
[[nodiscard]]
@@ -142,7 +163,7 @@ namespace omath
[[nodiscard]]
constexpr Angle operator-(const Angle& other) const noexcept
{
return operator+(-other);
return Angle{m_angle - other.m_angle};
}
[[nodiscard]]
@@ -172,7 +193,6 @@ struct std::formatter<omath::Angle<T, MinV, MaxV, F>, char> final // NOLINT(*-dc
return std::format_to(ctx.out(), "{}deg", a.as_degrees());
}
};
// wchar_t formatter
template<class T, T MinV, T MaxV, omath::AngleFlags F>
struct std::formatter<omath::Angle<T, MinV, MaxV, F>, wchar_t> final // NOLINT(*-dcl58-cpp)
@@ -193,24 +213,3 @@ struct std::formatter<omath::Angle<T, MinV, MaxV, F>, wchar_t> final // NOLINT(*
return std::format_to(ctx.out(), L"{}deg", a.as_degrees());
}
};
// wchar_t formatter
template<class T, T MinV, T MaxV, omath::AngleFlags F>
struct std::formatter<omath::Angle<T, MinV, MaxV, F>, char8_t> final // NOLINT(*-dcl58-cpp)
{
using AngleT = omath::Angle<T, MinV, MaxV, F>;
[[nodiscard]]
static constexpr auto parse(std::wformat_parse_context& ctx)
{
return ctx.begin();
}
template<class FormatContext>
[[nodiscard]]
auto format(const AngleT& a, FormatContext& ctx) const
{
static_assert(std::is_same_v<typename FormatContext::char_type, char8_t>);
return std::format_to(ctx.out(), u8"{}deg", a.as_degrees());
}
};
+2 -2
View File
@@ -48,10 +48,10 @@ namespace omath::angles
}
template<class Type>
requires std::is_arithmetic_v<Type>
requires std::is_floating_point_v<Type>
[[nodiscard]] constexpr Type wrap_angle(const Type& angle, const Type& min, const Type& max) noexcept
{
if (angle <= max && angle >= min)
if (angle < max && angle >= min)
return angle;
const Type range = max - min;
+38 -13
View File
@@ -14,9 +14,14 @@ namespace
// Handy aliases (defaults: Type=float, [0,360], Normalized)
using Deg = Angle<float, static_cast<float>(0), static_cast<float>(360), AngleFlags::Normalized>;
using Fov = Angle<float, static_cast<float>(0), static_cast<float>(180), AngleFlags::Clamped>;
using Offset = Angle<float, static_cast<float>(10), static_cast<float>(20), AngleFlags::Clamped>;
using Pitch = Angle<float, static_cast<float>(-90), static_cast<float>(90), AngleFlags::Clamped>;
using Turn = Angle<float, static_cast<float>(-180), static_cast<float>(180), AngleFlags::Normalized>;
template<class Type>
concept SupportedAngleType = requires { typename Angle<Type>; };
constexpr float k_eps = 1e-5f;
constexpr bool close_to(const float actual, const float expected, const float epsilon)
@@ -36,6 +41,12 @@ TEST(UnitTestAngle, DefaultConstructor_IsZeroDegrees)
EXPECT_FLOAT_EQ(a.as_degrees(), 0.0f);
}
TEST(UnitTestAngle, DefaultConstructor_AppliesRangePolicy)
{
constexpr Offset a;
EXPECT_FLOAT_EQ(a.as_degrees(), 10.0f);
}
TEST(UnitTestAngle, FromDegrees_Normalized_WrapsAboveMax)
{
const Deg a = Deg::from_degrees(370.0f);
@@ -66,6 +77,14 @@ TEST(UnitTestAngle, FromRadians_And_AsRadians)
EXPECT_NEAR(b.as_radians(), std::numbers::pi_v<float>, 1e-6f);
}
TEST(UnitTestAngle, FromInverseTrigonometricFunctions)
{
EXPECT_NEAR(Pitch::from_asin(0.5f).as_degrees(), 30.0f, k_eps);
EXPECT_NEAR(Pitch::from_acos(0.5f).as_degrees(), 60.0f, k_eps);
EXPECT_NEAR(Pitch::from_atan(1.0f).as_degrees(), 45.0f, k_eps);
EXPECT_NEAR(Turn::from_atan2(-1.0f, -1.0f).as_degrees(), -135.0f, k_eps);
}
// ---------- Unary minus & deref ----------
TEST(UnitTestAngle, UnaryMinus_Normalized)
@@ -101,17 +120,6 @@ TEST(UnitTestAngle, SinCosTanCot_BasicCases)
EXPECT_NEAR(a90.cos(), 0.0f, 1e-4f);
}
TEST(UnitTestAngle, Atan_IsAtanOfRadians)
{
// atan(as_radians). For 0° -> atan(0)=0.
const Deg a0 = Deg::from_degrees(0.0f);
EXPECT_NEAR(a0.atan(), 0.0f, k_eps);
const Deg a45 = Deg::from_degrees(45.0f);
// atan(pi/4) ≈ 0.665773...
EXPECT_NEAR(a45.atan(), 0.66577375f, 1e-6f);
}
// ---------- Compound arithmetic ----------
TEST(UnitTestAngle, PlusEquals_Normalized_Wraps)
@@ -142,6 +150,16 @@ TEST(UnitTestAngle, MinusEquals_Clamped_Clamps)
EXPECT_FLOAT_EQ(p.as_degrees(), -90.0f);
}
TEST(UnitTestAngle, Subtraction_ClampedNonSymmetricRange)
{
Fov compound = Fov::from_degrees(90.0f);
compound -= Fov::from_degrees(10.0f);
EXPECT_FLOAT_EQ(compound.as_degrees(), 80.0f);
const Fov binary = Fov::from_degrees(90.0f) - Fov::from_degrees(10.0f);
EXPECT_FLOAT_EQ(binary.as_degrees(), 80.0f);
}
// ---------- Alternative ranges ----------
TEST(UnitTestAngle, NormalizedRange_Neg180To180)
@@ -205,5 +223,12 @@ static_assert(close_to(Pitch::from_degrees(45.0f).tan(), 1.0f, 1e-4f),
"Tan should be constexpr with embedded constexpr math");
static_assert(close_to(Pitch::from_degrees(45.0f).cot(), 1.0f, 1e-4f),
"Cot should be constexpr with embedded constexpr math");
static_assert(close_to(Pitch::from_degrees(45.0f).atan(), 0.66577375f, 1e-6f),
"Atan should be constexpr with embedded constexpr math");
static_assert(close_to(Pitch::from_asin(0.5f).as_degrees(), 30.0f, k_eps),
"From asin should be constexpr with embedded constexpr math");
static_assert(close_to(Pitch::from_acos(0.5f).as_degrees(), 60.0f, k_eps),
"From acos should be constexpr with embedded constexpr math");
static_assert(close_to(Pitch::from_atan(1.0f).as_degrees(), 45.0f, k_eps),
"From atan should be constexpr with embedded constexpr math");
static_assert(close_to(Turn::from_atan2(-1.0f, -1.0f).as_degrees(), -135.0f, k_eps),
"From atan2 should be constexpr with embedded constexpr math");
static_assert(!SupportedAngleType<int>, "Angle should only accept floating-point types");
+8 -1
View File
@@ -46,4 +46,11 @@ TEST(unit_test_angles, wrap_angle_negative_range)
const float wrapped = omath::angles::wrap_angle(-90.f, 0.f, 360.f);
EXPECT_NEAR(wrapped, 270.f, 0.01f);
}
}
TEST(unit_test_angles, wrap_angle_maximum_maps_to_minimum)
{
const float wrapped = omath::angles::wrap_angle(360.f, 0.f, 360.f);
EXPECT_FLOAT_EQ(wrapped, 0.f);
}