SuperDex Physics C++ API
Loading...
Searching...
No Matches
nd_array.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#pragma once
18
24
25#include <algorithm>
26#include <array>
27#include <type_traits>
28
29namespace superdex {
30
31/**************************************************************************************************
32 MultiplyConstexpr - Return the product of all arguments as a constexpr. Used in later
33 declarations.
34*/
35template <typename A>
37 return a;
38}
39template <typename A, typename... ARGS>
40MOCHI_FORCE_INLINE constexpr A MultiplyConstexpr(A a, ARGS... args) {
41 return a * MultiplyConstexpr(args...);
42}
43
44/**************************************************************************************************
45 NdArray<T, D0, DIMS...>
46
47 Template for fixed-sized N-dimensional arrays like Int2, Real3, Matrix3x3r, etc...
48 Most methods can be used in constant (compile-time) expressions. NdArray currently has no
49 special alignment requirements and does not use SIMD explicitly.
50*/
51template <typename T, size_t D0 = 1, size_t... DIMS>
52class NdArray final {
53 public:
54 // Size of each dimension
55 constexpr static size_t num_dims = 1 + sizeof...(DIMS);
56 constexpr static size_t dims[num_dims] = {D0, DIMS...};
57 constexpr static size_t flattened_size = MultiplyConstexpr(D0, DIMS...);
58
59 // If this NdArray is 1D, then "value_type" is just "T". Else, it is an array of dimension (N-1)
60 using value_type = typename std::conditional_t<num_dims == 1, T, NdArray<T, DIMS...>>;
61
62 // Indicates the element type "T" in the last dimension of the array.
63 using element_type = T;
64
65 // Construct default
66 MOCHI_ANY MOCHI_FORCE_INLINE constexpr NdArray() = default;
67
68 // Construct from exactly D0 parameters (array elements that are convertible to T).
69 // NOLINTNEXTLINE(hicpp-explicit-conversions)
70 template <
71 typename... U,
72 std::enable_if_t<
73 (sizeof...(U) == D0) && std::conjunction_v<std::is_convertible<value_type, U>...>,
74 void*> = nullptr>
75 MOCHI_ANY MOCHI_FORCE_INLINE constexpr NdArray(U const&... p) : _data{p...} {}
76
77 // clang-format off
78 // These member names are lower case in keeping with the std library conventions.
79 MOCHI_ANY MOCHI_FORCE_INLINE constexpr static int size() { return D0; } // size of 1st dimension
80 MOCHI_ANY MOCHI_FORCE_INLINE constexpr value_type* data() { return _data; }
81 MOCHI_ANY MOCHI_FORCE_INLINE constexpr value_type const* data() const { return _data; }
82 MOCHI_ANY MOCHI_FORCE_INLINE constexpr auto begin() { return _data; }
83 MOCHI_ANY MOCHI_FORCE_INLINE constexpr auto begin() const { return _data; }
84 MOCHI_ANY MOCHI_FORCE_INLINE constexpr auto end() { return _data + D0; }
85 MOCHI_ANY MOCHI_FORCE_INLINE constexpr auto end() const { return _data + D0; }
86 // clang-format on
87
88 // Index operator. Defined in the class: some compilers (e.g. MSVC) do not instantiate
89 // out-of-class members of the extern templates below, so translation units would call
90 // them out of line.
91 MOCHI_ANY MOCHI_FORCE_INLINE constexpr value_type const& operator[](size_t i) const {
92 MOCHI_ASSERT_VERBOSE(i < D0, "Index out-of-range");
93 return _data[i];
94 }
96 MOCHI_ASSERT_VERBOSE(i < D0, "Index out-of-range");
97 return _data[i];
98 }
99
100 private:
101 value_type _data[D0];
102};
103
104// Type-trait to detect NdArray types
105template <typename T>
106struct IsNdArray : std::false_type {};
107template <typename T, size_t D0, size_t... DIMS>
108struct IsNdArray<NdArray<T, D0, DIMS...>> : std::true_type {};
109template <typename T>
110static constexpr bool kIsNdArray = IsNdArray<std::decay_t<T>>::value;
111
112// Common 1D floating-point arrays types
119
120// For cases that always need 32-bit floats
124
125// For cases that always need 64-bit floats
129
130// Common 2D floating point array types
137
144
145// Common 1D integral array types
149
150// Common 4d floating point tensors
153
156
157/**************************************************************************************************
158 Loop unrolling macro
159*/
160
161// Unroll a statement BODY over i = 0, ..., D0-1 (manually unrolled when D0 <= 4). `D0` must be in
162// scope. BODY may reference `i` as an index and must not introduce its own `i`. BODY is expanded as
163// a single statement, so unguarded commas (outside parentheses) must be avoided.
164#define MOCHI_DETAILS_UNROLL_D0(BODY) \
165 if constexpr (D0 <= 4) { \
166 if constexpr (D0 > 0) { \
167 constexpr size_t i = 0; \
168 BODY; \
169 } \
170 if constexpr (D0 > 1) { \
171 constexpr size_t i = 1; \
172 BODY; \
173 } \
174 if constexpr (D0 > 2) { \
175 constexpr size_t i = 2; \
176 BODY; \
177 } \
178 if constexpr (D0 > 3) { \
179 constexpr size_t i = 3; \
180 BODY; \
181 } \
182 } else { \
183 for (size_t i = 0; i < D0; ++i) { \
184 BODY; \
185 } \
186 }
187
188/**************************************************************************************************
189 NdArray Operators
190*/
191
192template <typename T, size_t D0, size_t... DIMS>
193MOCHI_FORCE_INLINE constexpr NdArray<T, D0, DIMS...> operator-(NdArray<T, D0, DIMS...> const& a) {
194 NdArray<T, D0, DIMS...> result
195 MOCHI_CONSTEXPR_NO_INIT; // Required to avoid memset calls (e.g. on MSVC).
196 MOCHI_DETAILS_UNROLL_D0(result[i] = -a[i]);
197 return result;
198}
199
200template <typename T, size_t D0, size_t... DIMS>
202 NdArray<T, D0, DIMS...> const& lhs,
203 NdArray<T, D0, DIMS...> const& rhs) {
204 bool isEqual = (lhs[0] == rhs[0]);
205 if constexpr (D0 > 1) {
206 isEqual &= (lhs[1] == rhs[1]);
207 }
208 if constexpr (D0 > 2) {
209 isEqual &= (lhs[2] == rhs[2]);
210 }
211 if constexpr (D0 > 3) {
212 isEqual &= (lhs[3] == rhs[3]);
213 }
214 if constexpr (D0 > 4) {
215 for (size_t i = 4; i < D0; ++i) {
216 isEqual &= (lhs[i] == rhs[i]);
217 }
218 }
219 return isEqual;
220}
221
222template <typename T, size_t D0, size_t... DIMS>
224 NdArray<T, D0, DIMS...> const& lhs,
225 NdArray<T, D0, DIMS...> const& rhs) {
226 return !(lhs == rhs);
227}
228
229// NdArray memberwise math operators (+=, -=, *=, /=, +, -, *, /)
230//
231// In-place OP_EQ variants (NdArray += NdArray, NdArray += scalar) avoid creating a temporary. For
232// large or nested NdArrays, the temporary may otherwise spill out of the register file. The other
233// variants declare their results MOCHI_CONSTEXPR_NO_INIT, to avoid memset calls with some
234// compilers (e.g. MSVC).
235#define MOCHI_DETAILS_NDARRAY_MEMBERWISE_OP(OP_EQ, OP) \
236 \
237 template <typename T, size_t D0, size_t... DIMS> \
238 MOCHI_FORCE_INLINE constexpr NdArray<T, D0, DIMS...>& operator OP_EQ( \
239 NdArray<T, D0, DIMS...>& lhs, NdArray<T, D0, DIMS...> const& rhs) { \
240 MOCHI_DETAILS_UNROLL_D0(lhs[i] OP_EQ rhs[i]); \
241 return lhs; \
242 } \
243 \
244 template <typename T, size_t D0, size_t... DIMS> \
245 MOCHI_FORCE_INLINE constexpr NdArray<T, D0, DIMS...>& operator OP_EQ( \
246 NdArray<T, D0, DIMS...>& lhs, T rhs) { \
247 MOCHI_DETAILS_UNROLL_D0(lhs[i] OP_EQ rhs); \
248 return lhs; \
249 } \
250 \
251 template <typename T, size_t D0, size_t... DIMS, typename AnyRHS> \
252 MOCHI_FORCE_INLINE constexpr NdArray<T, D0, DIMS...>& operator OP_EQ( \
253 NdArray<T, D0, DIMS...>& lhs, AnyRHS const& rhs) { \
254 MOCHI_DETAILS_UNROLL_D0(lhs[i] OP_EQ rhs); \
255 return lhs; \
256 } \
257 \
258 template <typename T, size_t D0, size_t... DIMS> \
259 MOCHI_FORCE_INLINE constexpr NdArray<T, D0, DIMS...> operator OP( \
260 NdArray<T, D0, DIMS...> const& lhs, NdArray<T, D0, DIMS...> const& rhs) { \
261 NdArray<T, D0, DIMS...> result MOCHI_CONSTEXPR_NO_INIT; \
262 MOCHI_DETAILS_UNROLL_D0(result[i] = lhs[i] OP rhs[i]); \
263 return result; \
264 } \
265 \
266 template <typename T, size_t D0, size_t... DIMS> \
267 MOCHI_FORCE_INLINE constexpr NdArray<T, D0, DIMS...> operator OP( \
268 NdArray<T, D0, DIMS...> const& lhs, T rhs) { \
269 NdArray<T, D0, DIMS...> result MOCHI_CONSTEXPR_NO_INIT; \
270 MOCHI_DETAILS_UNROLL_D0(result[i] = lhs[i] OP rhs); \
271 return result; \
272 } \
273 \
274 template <typename T, size_t D0, size_t... DIMS> \
275 MOCHI_FORCE_INLINE constexpr NdArray<T, D0, DIMS...> operator OP( \
276 T lhs, NdArray<T, D0, DIMS...> const& rhs) { \
277 NdArray<T, D0, DIMS...> result MOCHI_CONSTEXPR_NO_INIT; \
278 MOCHI_DETAILS_UNROLL_D0(result[i] = lhs OP rhs[i]); \
279 return result; \
280 }
281
286
287#undef MOCHI_DETAILS_NDARRAY_MEMBERWISE_OP
288#undef MOCHI_DETAILS_UNROLL_D0
289
290// Support for associative containers of small int arrays:
291struct Int2Hash {
292 MOCHI_FORCE_INLINE size_t operator()(Int2 const& x) const {
293 return std::hash<uint64_t>()(static_cast<uint64_t>(x[0]) | (static_cast<uint64_t>(x[1]) << 32));
294 }
295};
296struct Int2Less {
297 MOCHI_FORCE_INLINE bool operator()(Int2 const& a, Int2 const& b) const {
298 return (a[0] < b[0]) || (a[0] == b[0] && a[1] < b[1]);
299 };
300};
302 MOCHI_FORCE_INLINE size_t operator()(Int3 const& xUnsorted) const {
303 Int3 xSorted = xUnsorted;
304 std::sort(xSorted.begin(), xSorted.end());
305 return Int2Hash{}({xSorted[0], xSorted[1]}) ^ std::hash<uint64_t>()(xSorted[2]);
306 }
307};
309 MOCHI_FORCE_INLINE bool operator()(Int3 const& aUnsorted, Int3 const& bUnsorted) const {
310 Int3 aSorted = aUnsorted;
311 std::sort(aSorted.begin(), aSorted.end());
312 Int3 bSorted = bUnsorted;
313 std::sort(bSorted.begin(), bSorted.end());
314 return aSorted == bSorted;
315 }
316};
317
318/************************************************************************************
319 By declaring explicit instantiations for common types, we can reduce code bloat
320 especially in debug builds where the template functions are not inlined.
321*/
322#if MOCHI_USE_EXTERN_TEMPLATE
323extern template class NdArray<int, 2>;
324extern template class NdArray<int, 3>;
325extern template class NdArray<int, 4>;
326extern template class NdArray<real, 2>;
327extern template class NdArray<real, 3>;
328extern template class NdArray<real, 4>;
329extern template class NdArray<real, 2, 2>;
330extern template class NdArray<real, 2, 3>;
331extern template class NdArray<real, 3, 2>;
332extern template class NdArray<real, 3, 3>;
333extern template class NdArray<real, 4, 3>;
334#endif // MOCHI_USE_EXTERN_TEMPLATE
335
336// ScalarType specialization: recursively unwrap element type.
337namespace details {
338template <class T, size_t D0, size_t... DIMS>
339struct ScalarTypeDef<NdArray<T, D0, DIMS...>, void> {
340 using type = ScalarType<T>;
341};
342} // namespace details
343
344} // namespace superdex
345
346/************************************************************************************
347 Reflection support for NdArray using SReflect::ArrayTypeInfo
348 NdArray<T, D0> will be treated as a fixed-size array of type T, similar to std::array<T, D0>.
349 NdArray<T, D0, D1> will be treated an array of arrays like std::array<std::array<T, D1>, D0>.
350 etc...
351*/
352#if MOCHI_USE_REFLECTION
353template <typename T, size_t D0, size_t... DIMS>
354struct SReflectTypeTraits<superdex::NdArray<T, D0, DIMS...>> {
355 static constexpr SReflect::CoreType coreType = SReflect::CoreType::CT_array;
356 static SReflect::ArrayTypeInfo const& GetTypeInfo() {
357 static auto const* s_typeInfo = []() {
358 using MyType = superdex::NdArray<T, D0, DIMS...>;
359 using InnerType = typename MyType::value_type;
360 // Format the name like, "NdArray<int, 2>", "NdArray<real, 3, 3>", etc...
361 char dimsStr[128];
362 for (size_t i = 0, offset = 0; i < MyType::num_dims; ++i) {
363 offset += snprintf(dimsStr + offset, sizeof(dimsStr) - offset, ",%zu", MyType::dims[i]);
364 }
365 char const* tName = SReflect::GetTypeInfo<T>()._nameWithNamespace;
366 char const* myName = SReflect::detail::MakeTypeName("superdex::NdArray<", tName, dimsStr, ">");
367 static constexpr bool kFormatAsTemplate = false; // No. Use our formatted name.
368 return SReflect::MakeFixedArrayTypeInfo<MyType, InnerType, D0>(myName, kFormatAsTemplate);
369 }();
370 return *s_typeInfo;
371 }
372};
373#endif // MOCHI_USE_REFLECTION
constexpr value_type * data()
Definition nd_array.h:80
constexpr auto begin() const
Definition nd_array.h:83
constexpr NdArray()=default
constexpr auto end()
Definition nd_array.h:84
constexpr value_type const * data() const
Definition nd_array.h:81
static constexpr size_t num_dims
Definition nd_array.h:55
constexpr value_type & operator[](size_t i)
Definition nd_array.h:95
constexpr auto begin()
Definition nd_array.h:82
typename std::conditional_t< num_dims==1, T, NdArray< T, DIMS... > > value_type
Definition nd_array.h:60
static constexpr size_t dims[num_dims]
Definition nd_array.h:56
static constexpr int size()
Definition nd_array.h:79
constexpr NdArray(U const &... p)
Definition nd_array.h:75
constexpr auto end() const
Definition nd_array.h:85
constexpr value_type const & operator[](size_t i) const
Definition nd_array.h:91
static constexpr size_t flattened_size
Definition nd_array.h:57
#define MOCHI_ASSERT_VERBOSE(condition_without_side_effects,...)
Definition debug.h:102
#define MOCHI_CONSTEXPR_NO_INIT
#define MOCHI_FORCE_INLINE
#define MOCHI_ANY
constexpr bool operator==(NdArray< T, D0, DIMS... > const &lhs, NdArray< T, D0, DIMS... > const &rhs)
Definition nd_array.h:201
NdArray< real, 2, 3 > Matrix2x3r
Definition nd_array.h:132
NdArray< float, 3, 2 > Matrix3x2f
Definition nd_array.h:140
NdArray< float, 4, 4 > Matrix4x4f
Definition nd_array.h:143
NdArray< real, 3, 2 > Matrix3x2r
Definition nd_array.h:133
NdArray< float, 4 > Float4
Definition nd_array.h:123
NdArray< real, 4, 3 > Matrix4x3r
Definition nd_array.h:135
NdArray< float, 3, 3, 3 > Tensor3x3x3f
Definition nd_array.h:155
NdArray< float, 4, 3 > Matrix4x3f
Definition nd_array.h:142
NdArray< real, 3, 3, 3, 3 > Tensor3x3x3x3r
Definition nd_array.h:151
constexpr A MultiplyConstexpr(A a)
Definition nd_array.h:36
NdArray< int, 4 > Int4
Definition nd_array.h:148
NdArray< real, 5 > Real5
Definition nd_array.h:117
NdArray< real, 2, 2 > Matrix2x2r
Definition nd_array.h:131
NdArray< int, 3 > Int3
Definition nd_array.h:147
NdArray< real, 4, 4 > Matrix4x4r
Definition nd_array.h:136
NdArray< float, 2, 3 > Matrix2x3f
Definition nd_array.h:139
NdArray< real, 3 > Real3
Definition nd_array.h:115
NdArray< float, 2, 2 > Matrix2x2f
Definition nd_array.h:138
NdArray< double, 2 > Double2
Definition nd_array.h:126
NdArray< float, 3, 3 > Matrix3x3f
Definition nd_array.h:141
NdArray< real, 4 > Real4
Definition nd_array.h:116
NdArray< double, 3 > Double3
Definition nd_array.h:127
NdArray< double, 4 > Double4
Definition nd_array.h:128
NdArray< real, 3, 3, 3 > Tensor3x3x3r
Definition nd_array.h:152
NdArray< real, 3, 3 > Matrix3x3r
Definition nd_array.h:134
NdArray< int, 2 > Int2
Definition nd_array.h:146
constexpr bool operator!=(NdArray< T, D0, DIMS... > const &lhs, NdArray< T, D0, DIMS... > const &rhs)
Definition nd_array.h:223
NdArray< real, 6 > Real6
Definition nd_array.h:118
constexpr NdArray< T, D0, DIMS... > operator-(NdArray< T, D0, DIMS... > const &a)
Definition nd_array.h:193
static constexpr bool kIsNdArray
Definition nd_array.h:110
NdArray< float, 3 > Float3
Definition nd_array.h:122
NdArray< real, 2 > Real2
Definition nd_array.h:114
NdArray< float, 3, 3, 3, 3 > Tensor3x3x3x3f
Definition nd_array.h:154
NdArray< real, 1 > Real1
Definition nd_array.h:113
NdArray< float, 2 > Float2
Definition nd_array.h:121
#define MOCHI_DETAILS_NDARRAY_MEMBERWISE_OP(OP_EQ, OP)
Definition nd_array.h:235
#define MOCHI_DETAILS_UNROLL_D0(BODY)
Definition nd_array.h:164
size_t operator()(Int2 const &x) const
Definition nd_array.h:292
bool operator()(Int2 const &a, Int2 const &b) const
Definition nd_array.h:297
bool operator()(Int3 const &aUnsorted, Int3 const &bUnsorted) const
Definition nd_array.h:309
size_t operator()(Int3 const &xUnsorted) const
Definition nd_array.h:302