SuperDex Physics C++ API
Loading...
Searching...
No Matches
basic_utils.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/**********************************************************************
18
19 Base Utils:
20
21 This file contains generic template functions for scalar types (or other types with similar
22 operators).
23
24 Other overloads exist for types like NdArray, Matrix, and Simd. Such overloads are declared in
25 other headers, with their corresponding types. They generally perform the same operation, but
26 they do so member-wise.
27
28**/
29
30#pragma once
31
32// PLEASE DO NOT INCLUDE ADDITIONAL MOCHI HEADERS HERE
36// PLEASE DO NOT INCLUDE ADDITIONAL MOCHI HEADERS HERE
37
38#include <cmath>
39#include <cstring>
40#include <limits>
41#include <type_traits>
42
43namespace superdex {
44
45/**********************************************************************
46 Absolute Value
47*/
48
49template <typename T>
50[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Abs(T a) {
51 return a >= T{0} ? a : -a;
52}
53
54/**********************************************************************
55 AllTrue & AnyTrue convert to bool
56*/
57
58// Return true if (a != 0). Simd overloads return true if (a[i] != 0) for all i.
59template <typename T>
60[[nodiscard]] MOCHI_FORCE_INLINE bool AllTrue(T const& a) {
61 return a != T{0};
62}
63
64// Return true if (a != 0). Simd overloads return true if (a[i] != 0) for ANY i.
65template <typename T>
66[[nodiscard]] MOCHI_FORCE_INLINE bool AnyTrue(T const& a) {
67 return a != T{0};
68}
69
70/**********************************************************************
71 Casting
72*/
73
74// StaticCast supports numeric conversions (e.g. truncate float to int)
75template <
76 typename To,
77 typename From,
78 MOCHI_CONCEPT(std::is_arithmetic_v<From>&& std::is_arithmetic_v<To>)>
79[[nodiscard]] MOCHI_FORCE_INLINE constexpr To StaticCast(From const& a) {
80 return static_cast<To>(a);
81}
82
83// Returns a pointer with the same address as the input pointer, but with a different type.
84// Equivalent to reinterpret_cast<From>(To).
85template <
86 typename To,
87 typename From,
88 MOCHI_CONCEPT(std::is_pointer_v<From>&& std::is_pointer_v<To>)>
89[[nodiscard]] MOCHI_FORCE_INLINE To ReinterpretCast(From const& a) {
90 static_assert(sizeof(To) == sizeof(From), "Invalid cast. Types must be the same size.");
91 return reinterpret_cast<To>(a);
92}
93
94// Returns an arithmetic type with the same bits as the input variable.
95// Example: auto var = ReinterpretCast<float>(-1); // var is a float with all bits set to 1
96template <
97 typename To,
98 typename From,
99 MOCHI_CONCEPT(std::is_arithmetic_v<From>&& std::is_arithmetic_v<To>)>
100[[nodiscard]] MOCHI_FORCE_INLINE To ReinterpretCast(From const& a) {
101 static_assert(sizeof(To) == sizeof(From), "Invalid cast. Types must be the same size.");
102 To b;
103 memcpy(&b, &a, sizeof(a));
104 return b;
105}
106
107/**********************************************************************
108 Fused Multiply-Add (and friends)
109
110 Like the Simd overloads, floating-point results are rounded once, so a sequence of these calls
111 rounds the same wherever it is compiled, regardless of compiler contraction. The arguments share
112 one type, so that mixed types cannot silently fall back to unfused arithmetic. Negation is exact,
113 so the variants are fused too.
114*/
115
116template <typename T>
117[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE constexpr T MulAdd(T a, T b, T c) {
118 if constexpr (std::is_floating_point_v<T>) {
119 return std::fma(a, b, c);
120 } else {
121 return (a * b) + c;
122 }
123}
124
125template <typename T>
126[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE constexpr T MulSub(T a, T b, T c) {
127 if constexpr (std::is_floating_point_v<T>) {
128 return std::fma(a, b, -c);
129 } else {
130 return (a * b) - c;
131 }
132}
133
134template <typename T>
135[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE constexpr T NegMulAdd(T a, T b, T c) {
136 if constexpr (std::is_floating_point_v<T>) {
137 return std::fma(-a, b, c);
138 } else {
139 return -(a * b) + c;
140 }
141}
142
143template <typename T>
144[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE constexpr T NegMulSub(T a, T b, T c) {
145 if constexpr (std::is_floating_point_v<T>) {
146 return std::fma(-a, b, -c);
147 } else {
148 return -(a * b) - c;
149 }
150}
151
152/**********************************************************************
153 IsFinite
154*/
155
156template <typename T, MOCHI_CONCEPT(std::is_arithmetic_v<T>)>
157[[nodiscard]] MOCHI_FORCE_INLINE bool IsFinite(T a) {
158 if constexpr (std::is_integral_v<T>) {
159 return true;
160 } else {
161 return std::isfinite(a);
162 }
163}
164
165/**********************************************************************
166 Min, Max, Clamp, Lerp
167*/
168
169template <typename T>
170[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE constexpr T const& Min(T const& a, T const& b) {
171 return (a <= b) ? a : b;
172}
173
174// For convenience, you can find the minimum of an arbitrary number of values.
175template <typename T, typename... More>
176[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Min(T a, T b, T c, More... args) {
177 return Min(a, Min(b, c, args...));
178}
179
180template <typename T>
181[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE constexpr T const& Max(T const& a, T const& b) {
182 return (a >= b) ? a : b;
183}
184
185// For convenience, you can find the maximum of an arbitrary number of values.
186template <typename T, typename... More>
187[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Max(T a, T b, T c, More... args) {
188 return Max(a, Max(b, c, args...));
189}
190
191template <typename ValT, typename MinT, typename MaxT>
192[[nodiscard]] MOCHI_FORCE_INLINE constexpr ValT Clamp(ValT value, MinT min, MaxT max) {
193 return Min(ValT(max), Max(ValT(min), value));
194}
195
196template <typename ValT, typename MinT, typename MaxT, bool kMinInclusive, bool kMaxInclusive>
197[[nodiscard]] MOCHI_FORCE_INLINE constexpr ValT Rect(
198 ValT value,
199 MinT min,
200 MaxT max,
201 std::integral_constant<bool, kMinInclusive> /*minInclusive*/ = std::true_type{},
202 std::integral_constant<bool, kMaxInclusive> /*maxInclusive*/ = std::false_type{}) {
203 bool test1 = false;
204 if constexpr (kMinInclusive) {
205 test1 = (value >= min);
206 } else {
207 test1 = (value > min);
208 }
209 bool test2 = false;
210 if constexpr (kMaxInclusive) {
211 test2 = (value <= max);
212 } else {
213 test2 = (value < max);
214 }
215 return static_cast<ValT>(test1 && test2);
216}
217
218/**********************************************************************
219 Equality
220 */
221
222// clang-format off
223template<typename T> inline constexpr T kDefaultNearEqualEpsilon{0};
224template<> inline constexpr float kDefaultNearEqualEpsilon<float>{1.0e-6f};
225template<> inline constexpr double kDefaultNearEqualEpsilon<double>{1.0e-6}; // Historical value. Could probably be much smaller.
226// clang-format on
227
228template <typename T>
229[[nodiscard]] MOCHI_FORCE_INLINE constexpr auto Equal(T const& a, T const& b) {
230 return (a == b);
231}
232
233template <typename T>
234[[nodiscard]] MOCHI_FORCE_INLINE constexpr auto NotEqual(T const& a, T const& b) {
235 return !Equal(a, b);
236}
237
238template <typename T, MOCHI_CONCEPT(std::is_arithmetic_v<T>)>
239[[nodiscard]] MOCHI_FORCE_INLINE constexpr auto
240NearEqual(T const& a, T const& b, T epsilon = kDefaultNearEqualEpsilon<T>) {
241 static_assert(!std::is_same_v<std::remove_cv_t<T>, bool>, "NearEqual not supported for bool");
242 return Abs(a - b) <= epsilon;
243}
244
245template <typename T, MOCHI_CONCEPT(std::is_arithmetic_v<T>)>
246[[nodiscard]] MOCHI_FORCE_INLINE constexpr auto
247NearEqualRel(T const& a, T const& b, T epsilon = kDefaultNearEqualEpsilon<T>) {
248 static_assert(!std::is_same_v<std::remove_cv_t<T>, bool>, "NearEqualRel not supported for bool");
249 auto scaledEpsilon = epsilon * Max(Abs(a), Abs(b));
250 auto tolerance = Max(epsilon, scaledEpsilon);
251 return NearEqual(a, b, tolerance);
252}
253
254template <typename T, MOCHI_CONCEPT(std::is_arithmetic_v<T>)>
255[[nodiscard]] MOCHI_FORCE_INLINE constexpr auto NearZero(
256 T const& a,
257 T epsilon = kDefaultNearEqualEpsilon<T>) {
258 static_assert(!std::is_same_v<std::remove_cv_t<T>, bool>, "NearZero not supported for bool");
259 return Abs(a) <= epsilon;
260}
261
262/**********************************************************************
263 isize - Return a container size as int. Inspired by std::ssize.
264 http://en.cppreference.com/w/cpp/iterator/size
265*/
266
267// Generic version uses the size() member function.
268template <typename T>
269[[nodiscard]] MOCHI_FORCE_INLINE constexpr int isize(T const& a) {
270 return static_cast<int>(a.size());
271}
272
273// Specialization for c-style arrays
274template <typename T, size_t N>
275[[nodiscard]] MOCHI_FORCE_INLINE constexpr int isize([[maybe_unused]] T const (&array)[N]) {
276 return static_cast<int>(N);
277}
278
279/**********************************************************************
280 Linear Interpolation
281*/
282
283template <typename T, typename Frac>
284[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Lerp(T a, T b, Frac t) {
285 return T(a * (Frac{1} - t) + b * t); // The faction t is not clamped
286}
287
288// Linearly remap a value from one number range to another. Does not clamp. If the value was outside
289// the input range, it will be outside the output range as well. You also remap an ascending range
290// onto a descending range or vice versa by setting (inA > inB) or (outA > outB).
291// Examples:
292// Remap(val, 0.0, 1.0, 0.0, 255.0); // As value goes from 0->1, result goes from 0->255
293// Remap(val, 1.0, 0.0, 0.0, 255.0); // As value goes from 1->0, result goes from 0->255
294template <typename T>
295[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Remap(T value, T inA, T inB, T outA, T outB) {
296 return Lerp<T>(outA, outB, (value - inA) / (inB - inA));
297}
298
299// Similar to Remap (see above), except that the result is guaranteed to be between outA and outB.
300// Note that the output range might be ascending (outA < outB) or descending (outB < outA).
301// Examples:
302// RemapAndClamp(1.1, 0.0, 1.0, 0.0, 255.0); // Returns 255.0
303// RemapAndClamp(1.1, 0.0, 1.0, 255.0, 0.0); // Returns 0.0, as if value was 1.0 (not 1.1)
304template <typename T>
305[[nodiscard]] MOCHI_FORCE_INLINE constexpr T RemapAndClamp(T value, T inA, T inB, T outA, T outB) {
306 return Lerp<T>(outA, outB, Clamp<T>((value - inA) / (inB - inA), T{0}, T{1}));
307}
308
309/**********************************************************************
310 Powers
311*/
312
313template <typename B, typename E>
314[[nodiscard]] MOCHI_FORCE_INLINE constexpr B Pow(B base, E exp) {
315 return std::pow(base, exp);
316}
317
318template <typename T>
319[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Sqr(T a) {
320 return a * a;
321}
322
323// Result as the same sign as the input
324template <typename T>
325[[nodiscard]] MOCHI_FORCE_INLINE constexpr T SignedSqr(T a) {
326 return a * Abs(a);
327}
328
329template <typename T>
330[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Sqrt(T a) {
331 return std::sqrt(a);
332}
333
334// Result as the same sign as the input
335template <typename T>
336[[nodiscard]] MOCHI_FORCE_INLINE constexpr T SignedSqrt(T a);
337
338template <typename T>
339[[nodiscard]] MOCHI_FORCE_INLINE constexpr T IntegralSqrt(T a);
340
341template <typename T>
342[[nodiscard]] MOCHI_FORCE_INLINE constexpr bool IsPowerOfTwo(T a) {
343 static_assert(
344 std::is_integral_v<T> && !std::is_same_v<std::remove_cv_t<T>, bool>,
345 "IsPowerOfTwo requires a non-bool integral type");
346 return (a > T(0)) && ((a & (a - T(1))) == T(0));
347}
348
349// Returns the smallest power of two greater than or equal to a. Non-positive inputs return 1.
350// Positive inputs must not exceed the largest representable power of two.
351template <typename T>
352[[nodiscard]] MOCHI_FORCE_INLINE constexpr T NextPowerOfTwo(T a) {
353 static_assert(
354 std::is_integral_v<T> && !std::is_same_v<std::remove_cv_t<T>, bool>,
355 "NextPowerOfTwo requires a non-bool integral type");
356 [[maybe_unused]] constexpr T kMaxPowerOfTwo = T(1) << (std::numeric_limits<T>::digits - 1);
358 a <= kMaxPowerOfTwo, "Input exceeds the largest representable power of two.");
359 if (a <= T(0)) {
360 return T(1);
361 }
362 using UnsignedT = std::make_unsigned_t<T>;
363 static_assert(
364 std::numeric_limits<UnsignedT>::digits > 4 && std::numeric_limits<UnsignedT>::digits <= 64,
365 "Unsupported integral type");
366 auto result = static_cast<UnsignedT>(a - T(1));
367 result |= result >> 1;
368 result |= result >> 2;
369 result |= result >> 4;
370 if constexpr (std::numeric_limits<UnsignedT>::digits > 8) {
371 result |= result >> 8;
372 }
373 if constexpr (std::numeric_limits<UnsignedT>::digits > 16) {
374 result |= result >> 16;
375 }
376 if constexpr (std::numeric_limits<UnsignedT>::digits > 32) {
377 result |= result >> 32;
378 }
379 return static_cast<T>(result + UnsignedT(1));
380}
381
382/**********************************************************************
383 Reciprocal
384*/
385
387MOCHI_WARNING_IGNORE_MSVC(4723) // warning C4723: potential divide by 0
388
389template <typename T>
390[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Rcp(T a) {
391 return T(1) / a;
392}
393
394// SIMD overloads of RcpApprox may have less precision. Use with caution.
395template <typename T>
396[[nodiscard]] MOCHI_FORCE_INLINE constexpr T RcpApprox(T a) {
397 return T(1) / a;
398}
399
401
402/**********************************************************************
403 Rounding
404*/
405
406template <typename T>
407[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Floor(T a) {
408 return std::floor(a);
409}
410
411template <typename T>
412[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Ceil(T a) {
413 return std::ceil(a);
414}
415
416template <typename T>
417[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Round(T a) {
418 return std::round(a);
419}
420
421template <typename T>
422[[nodiscard]] MOCHI_FORCE_INLINE constexpr T RoundUp(T numToRound, T multiple) {
423 static_assert(
424 std::is_integral_v<T> && !std::is_same_v<std::remove_cv_t<T>, bool>, "Unsupported type");
425 return ((numToRound + multiple - 1) / multiple) * multiple;
426}
427
428template <typename T>
429[[nodiscard]] MOCHI_FORCE_INLINE constexpr T RoundDown(T numToRound, T multiple) {
430 static_assert(
431 std::is_integral_v<T> && !std::is_same_v<std::remove_cv_t<T>, bool>, "Unsupported type");
432 return (numToRound / multiple) * multiple;
433}
434
435/**********************************************************************
436 Select
437*/
438
439// Return (condition ? a : b).
440// Only supported for arithmetic types to prevent misuse. For other types, callers should explicitly
441// use a ternary expression if that's what they want. Other overloads do this per-member (e.g. for a
442// Matrix or Simd type).
443template <typename T>
444[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Select(bool condition, T a, T b) {
445 static_assert(std::is_arithmetic_v<T>, "Unsupported type");
446 return condition ? a : b;
447}
448
449/**********************************************************************
450 Sign
451*/
452
453// Return +1 or -1 matching the sign of the given value.
454template <typename T>
455[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Sign(T x) {
456 return Select(x >= T{}, T{1}, T{-1});
457}
458
459/**********************************************************************
460 Trigonometry
461*/
462
463template <typename T>
464[[nodiscard]] MOCHI_FORCE_INLINE constexpr T ASin(T a) {
465 return std::asin(a);
466}
467
468template <typename T>
469[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Sin(T a) {
470 return std::sin(a);
471}
472
473template <typename T>
474[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Sinc(T a);
475
476template <typename T>
477[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Cos(T a) {
478 return std::cos(a);
479}
480
481template <typename T>
482[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Tan(T a) {
483 return std::tan(a);
484}
485
486template <typename T>
487[[nodiscard]] MOCHI_FORCE_INLINE constexpr T ACos(T a) {
488 return std::acos(a);
489}
490
491template <typename T>
492[[nodiscard]] MOCHI_FORCE_INLINE constexpr T ATan(T a) {
493 return std::atan(a);
494}
495
496template <typename T>
497[[nodiscard]] MOCHI_FORCE_INLINE constexpr T ATan2(T y, T x) {
498 return std::atan2(y, x);
499}
500
501/**********************************************************************
502 Exponential-based
503*/
504
505template <typename T>
506[[nodiscard]] MOCHI_FORCE_INLINE constexpr T Exp(T a) {
507 return std::exp(a);
508}
509
510} // namespace superdex
511
512#include "basic_utils_inl.h"
#define MOCHI_ASSERT_VERBOSE(condition_without_side_effects,...)
Definition debug.h:102
#define MOCHI_CONCEPT(a)
#define MOCHI_WARNING_POP()
#define MOCHI_WARNING_IGNORE_MSVC(X)
#define MOCHI_WARNING_PUSH()
#define MOCHI_FORCE_INLINE
#define MOCHI_ANY
constexpr T ACos(T a)
constexpr T NegMulAdd(T a, T b, T c)
constexpr bool IsPowerOfTwo(T a)
constexpr T const & Min(T const &a, T const &b)
constexpr T RoundDown(T numToRound, T multiple)
constexpr auto Equal(T const &a, T const &b)
constexpr T NextPowerOfTwo(T a)
constexpr T Sin(T a)
constexpr To StaticCast(From const &a)
Definition basic_utils.h:79
constexpr T kDefaultNearEqualEpsilon
constexpr ValT Rect(ValT value, MinT min, MaxT max, std::integral_constant< bool, kMinInclusive >=std::true_type{}, std::integral_constant< bool, kMaxInclusive >=std::false_type{})
bool AllTrue(T const &a)
Definition basic_utils.h:60
constexpr T NegMulSub(T a, T b, T c)
constexpr T ATan2(T y, T x)
constexpr T RoundUp(T numToRound, T multiple)
constexpr auto NotEqual(T const &a, T const &b)
constexpr T Exp(T a)
constexpr T Cos(T a)
constexpr T Abs(T a)
Definition basic_utils.h:50
constexpr T MulSub(T a, T b, T c)
constexpr T Tan(T a)
bool AnyTrue(T const &a)
Definition basic_utils.h:66
constexpr T Select(bool condition, T a, T b)
constexpr T Sqr(T a)
constexpr T SignedSqrt(T a)
constexpr T Sqrt(T a)
constexpr T ATan(T a)
constexpr T Sign(T x)
constexpr T Floor(T a)
constexpr T ASin(T a)
constexpr T Ceil(T a)
constexpr T IntegralSqrt(T a)
constexpr ValT Clamp(ValT value, MinT min, MaxT max)
constexpr T SignedSqr(T a)
constexpr T RemapAndClamp(T value, T inA, T inB, T outA, T outB)
constexpr int isize(T const &a)
constexpr T Lerp(T a, T b, Frac t)
constexpr T const & Max(T const &a, T const &b)
constexpr T RcpApprox(T a)
constexpr T MulAdd(T a, T b, T c)
bool NearEqual(TransformRT const &a, TransformRT const &b, real epsilon=kDefaultNearEqualEpsilon< real >)
constexpr B Pow(B base, E exp)
constexpr auto NearEqualRel(T const &a, T const &b, T epsilon=kDefaultNearEqualEpsilon< T >)
constexpr T Rcp(T a)
constexpr T Sinc(T a)
bool IsFinite(TransformRT const &a)
constexpr T Remap(T value, T inA, T inB, T outA, T outB)
constexpr auto NearZero(T const &a, T epsilon=kDefaultNearEqualEpsilon< T >)
constexpr T Round(T a)