Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #ifndef INCLUDED_FIXED
19 : #define INCLUDED_FIXED
20 :
21 : #include "lib/debug.h"
22 : #include "lib/sysdep/compiler.h"
23 : #include "maths/Sqrt.h"
24 :
25 : #include <algorithm>
26 : #include <cmath>
27 : #include <limits>
28 :
29 : class CStr8;
30 : class CStrW;
31 :
32 : #ifndef NDEBUG
33 : #define USE_FIXED_OVERFLOW_CHECKS
34 : #endif
35 :
36 : #if MSC_VERSION
37 : // std::int32_t * std::int32_t -> std::int64_t multiply: MSVC x86 doesn't optimise std::int64_t multiplies
38 : // automatically, so use the intrinsic
39 : #include <intrin.h>
40 : #define MUL_I64_I32_I32(a, b)\
41 : (__emul((a), (b)))
42 : #define SQUARE_U64_FIXED(a)\
43 : static_cast<std::uint64_t>(__emul((a).GetInternalValue(), (a).GetInternalValue()))
44 : #else
45 : #define MUL_I64_I32_I32(a, b)\
46 : static_cast<std::int64_t>(a) * static_cast<std::int64_t>(b)
47 : #define SQUARE_U64_FIXED(a)\
48 : static_cast<std::uint64_t>(static_cast<std::int64_t>((a).GetInternalValue()) * \
49 : static_cast<std::int64_t>((a).GetInternalValue()))
50 : #endif
51 :
52 : //define overflow macros
53 : #ifndef USE_FIXED_OVERFLOW_CHECKS
54 :
55 : #define CheckSignedSubtractionOverflow(type, left, right, overflowWarning, underflowWarning)
56 : #define CheckSignedAdditionOverflow(type, left, right, overflowWarning, underflowWarning)
57 : #define CheckCastOverflow(var, targetType, overflowWarning, underflowWarning)
58 : #define CheckU32CastOverflow(var, targetType, overflowWarning)
59 : #define CheckUnsignedAdditionOverflow(result, operand, overflowWarning)
60 : #define CheckUnsignedSubtractionOverflow(result, operand, overflowWarning)
61 : #define CheckNegationOverflow(var, type, overflowWarning)
62 : #define CheckMultiplicationOverflow(type, left, right, overflowWarning, underflowWarning)
63 : #define CheckDivisionOverflow(type, left, right, overflowWarning)
64 :
65 : #else // USE_FIXED_OVERFLOW_CHECKS
66 :
67 : #define CheckSignedSubtractionOverflow(type, left, right, overflowWarning, underflowWarning) \
68 : if(left > 0 && right < 0 && left > std::numeric_limits<type>::max() + right) \
69 : debug_warn(overflowWarning); \
70 : else if(left < 0 && right > 0 && left < std::numeric_limits<type>::min() + right) \
71 : debug_warn(underflowWarning);
72 :
73 : #define CheckSignedAdditionOverflow(type, left, right, overflowWarning, underflowWarning) \
74 : if(left > 0 && right > 0 && std::numeric_limits<type>::max() - left < right) \
75 : debug_warn(overflowWarning); \
76 : else if(left < 0 && right < 0 && std::numeric_limits<type>::min() - left > right) \
77 : debug_warn(underflowWarning);
78 :
79 : #define CheckCastOverflow(var, targetType, overflowWarning, underflowWarning) \
80 : if(var > std::numeric_limits<targetType>::max()) \
81 : debug_warn(overflowWarning); \
82 : else if(var < std::numeric_limits<targetType>::min()) \
83 : debug_warn(underflowWarning);
84 :
85 : #define CheckU32CastOverflow(var, targetType, overflowWarning) \
86 : if(var > static_cast<std::uint32_t>(std::numeric_limits<targetType>::max())) \
87 : debug_warn(overflowWarning);
88 :
89 : #define CheckUnsignedAdditionOverflow(result, operand, overflowWarning) \
90 : if(result < operand) \
91 : debug_warn(overflowWarning);
92 :
93 : #define CheckUnsignedSubtractionOverflow(result, left, overflowWarning) \
94 : if(result > left) \
95 : debug_warn(overflowWarning);
96 :
97 : #define CheckNegationOverflow(var, type, overflowWarning) \
98 : if(value == std::numeric_limits<type>::min()) \
99 : debug_warn(overflowWarning);
100 :
101 : #define CheckMultiplicationOverflow(type, left, right, overflowWarning, underflowWarning) \
102 : std::int64_t res##left = static_cast<std::int64_t>(left) * static_cast<std::int64_t>(right); \
103 : CheckCastOverflow(res##left, type, overflowWarning, underflowWarning)
104 :
105 : #define CheckDivisionOverflow(type, left, right, overflowWarning) \
106 : if(right == -1) { CheckNegationOverflow(left, type, overflowWarning) }
107 :
108 : #endif // USE_FIXED_OVERFLOW_CHECKS
109 :
110 : template <typename T>
111 130050 : inline T round_away_from_zero(float value)
112 : {
113 130050 : return (T)(value >= 0 ? value + 0.5f : value - 0.5f);
114 : }
115 :
116 : template <typename T>
117 94901 : inline T round_away_from_zero(double value)
118 : {
119 94901 : return (T)(value >= 0 ? value + 0.5 : value - 0.5);
120 : }
121 :
122 : /**
123 : * A simple fixed-point number class.
124 : *
125 : * Use 'fixed' rather than using this class directly.
126 : */
127 : template<typename T, T max_t, int total_bits, int int_bits, int fract_bits_, int fract_pow2>
128 : class CFixed
129 : {
130 : private:
131 : T value;
132 :
133 52142623 : constexpr explicit CFixed(T v) : value(v) { }
134 :
135 : public:
136 : enum { fract_bits = fract_bits_ };
137 :
138 6347985 : CFixed() : value(0) { }
139 :
140 5778043 : static CFixed Zero() { return CFixed(0); }
141 3291 : static CFixed Epsilon() { return CFixed(1); }
142 : static CFixed Pi();
143 :
144 794681 : T GetInternalValue() const { return value; }
145 440088 : void SetInternalValue(T n) { value = n; }
146 :
147 : // Conversion to/from primitive types:
148 :
149 27077340 : static constexpr CFixed FromInt(int n)
150 : {
151 11996152 : return CFixed(n << fract_bits);
152 : }
153 :
154 : // TODO C++20: this won't be necessary when operator/(int) can be made constexpr.
155 : static constexpr CFixed FromFraction(int n, int d)
156 : {
157 : return CFixed(static_cast<int>(static_cast<unsigned int>(n) << fract_bits) / d);
158 : }
159 :
160 156162 : static constexpr CFixed FromFloat(float n)
161 : {
162 156162 : if (!std::isfinite(n))
163 : return CFixed(0);
164 156162 : float scaled = n * fract_pow2;
165 151578 : return CFixed(round_away_from_zero<T>(scaled));
166 : }
167 :
168 94910 : static constexpr CFixed FromDouble(double n)
169 : {
170 94910 : if (!std::isfinite(n))
171 : return CFixed(0);
172 95111 : double scaled = n * fract_pow2;
173 94941 : return CFixed(round_away_from_zero<T>(scaled));
174 : }
175 :
176 : static CFixed FromString(const CStr8& s);
177 : static CFixed FromString(const CStrW& s);
178 :
179 : /// Convert to float. May be lossy - float can't represent all values.
180 30144 : float ToFloat() const
181 : {
182 30104 : return (float)value / (float)fract_pow2;
183 : }
184 :
185 : /// Convert to double. Won't be lossy - double can precisely represent all values.
186 125232 : double ToDouble() const
187 : {
188 112656 : return value / (double)fract_pow2;
189 : }
190 :
191 11536802 : constexpr int ToInt_RoundToZero() const
192 : {
193 11487218 : if (value > 0)
194 11528051 : return value >> fract_bits;
195 : else
196 8751 : return (value + fract_pow2 - 1) >> fract_bits;
197 : }
198 :
199 110448 : constexpr int ToInt_RoundToInfinity() const
200 : {
201 89052 : return (value + fract_pow2 - 1) >> fract_bits;
202 : }
203 :
204 325020 : constexpr int ToInt_RoundToNegInfinity() const
205 : {
206 306792 : return value >> fract_bits;
207 : }
208 :
209 116236 : constexpr int ToInt_RoundToNearest() const // (ties to infinity)
210 : {
211 116236 : return (value + fract_pow2/2) >> fract_bits;
212 : }
213 :
214 : /// Returns the shortest string such that FromString will parse to the correct value.
215 : CStr8 ToString() const;
216 :
217 : /// Returns true if the number is precisely 0.
218 45536 : constexpr bool IsZero() const { return value == 0; }
219 :
220 : /// Equality.
221 113221 : constexpr bool operator==(CFixed n) const { return (value == n.value); }
222 :
223 : /// Inequality.
224 68686 : constexpr bool operator!=(CFixed n) const { return (value != n.value); }
225 :
226 : /// Numeric comparison.
227 80184509 : constexpr bool operator<=(CFixed n) const { return (value <= n.value); }
228 :
229 : /// Numeric comparison.
230 31871460 : constexpr bool operator<(CFixed n) const { return (value < n.value); }
231 :
232 : /// Numeric comparison.
233 13673 : constexpr bool operator>=(CFixed n) const { return (value >= n.value); }
234 :
235 : /// Numeric comparison.
236 370760 : constexpr bool operator>(CFixed n) const { return (value > n.value); }
237 :
238 : // Basic arithmetic:
239 :
240 : /// Add a CFixed. Might overflow.
241 10622985 : CFixed operator+(CFixed n) const
242 : {
243 : CheckSignedAdditionOverflow(T, value, n.value, L"Overflow in CFixed::operator+(CFixed n)", L"Underflow in CFixed::operator+(CFixed n)")
244 927315 : return CFixed(value + n.value);
245 : }
246 :
247 : /// Subtract a CFixed. Might overflow.
248 16995995 : CFixed operator-(CFixed n) const
249 : {
250 : CheckSignedSubtractionOverflow(T, value, n.value, L"Overflow in CFixed::operator-(CFixed n)", L"Underflow in CFixed::operator-(CFixed n)")
251 6849139 : return CFixed(value - n.value);
252 : }
253 :
254 : /// Add a CFixed. Might overflow.
255 147849 : constexpr CFixed& operator+=(CFixed n) { *this = *this + n; return *this; }
256 :
257 : /// Subtract a CFixed. Might overflow.
258 14654 : constexpr CFixed& operator-=(CFixed n) { *this = *this - n; return *this; }
259 :
260 : /// Negate a CFixed.
261 242372 : CFixed operator-() const
262 : {
263 : CheckNegationOverflow(value, T, L"Overflow in CFixed::operator-()")
264 218315 : return CFixed(-value);
265 : }
266 :
267 166996 : CFixed operator>>(int n) const
268 : {
269 : ASSERT(n >= 0 && n < 32);
270 166996 : return CFixed(value >> n);
271 : }
272 :
273 : CFixed operator<<(int n) const
274 : {
275 : ASSERT(n >= 0 && n < 32);
276 : // TODO: check for overflow
277 : return CFixed(value << n);
278 : }
279 :
280 : /// Divide by a CFixed. Must not have n.IsZero(). Might overflow.
281 211354 : CFixed operator/(CFixed n) const
282 : {
283 211354 : std::int64_t t = static_cast<std::int64_t>(value) << fract_bits;
284 211354 : std::int64_t result = t / static_cast<std::int64_t>(n.value);
285 :
286 : CheckCastOverflow(result, T, L"Overflow in CFixed::operator/(CFixed n)", L"Underflow in CFixed::operator/(CFixed n)")
287 210118 : return CFixed((T)result);
288 : }
289 :
290 : /// Multiply by an integer. Might overflow.
291 5824748 : CFixed operator*(int n) const
292 : {
293 : CheckMultiplicationOverflow(T, value, n, L"Overflow in CFixed::operator*(int n)", L"Underflow in CFixed::operator*(int n)")
294 5803696 : return CFixed(value * n);
295 : }
296 :
297 : /// Multiply by an integer. Avoids overflow by clamping to min/max representable value.
298 5308416 : constexpr CFixed MultiplyClamp(int n) const
299 : {
300 5308416 : std::int64_t t = static_cast<std::int64_t>(value) * n;
301 5308416 : t = std::max(static_cast<std::int64_t>(std::numeric_limits<T>::min()),
302 5308416 : std::min(static_cast<std::int64_t>(std::numeric_limits<T>::max()), t));
303 5308416 : return CFixed(static_cast<std::int32_t>(t));
304 : }
305 :
306 : /// Divide by an integer. Must not have n == 0. Cannot overflow unless n == -1.
307 28083888 : CFixed operator/(int n) const
308 : {
309 : CheckDivisionOverflow(T, value, n, L"Overflow in CFixed::operator/(int n)")
310 11740962 : return CFixed(value / n);
311 : }
312 :
313 : /// Mod by a fixed. Must not have n == 0. Result has the same sign as n.
314 19625 : constexpr CFixed operator%(CFixed n) const
315 : {
316 19622 : T t = value % n.value;
317 19622 : if (n.value > 0 && t < 0)
318 7670 : t += n.value;
319 : else if (n.value < 0 && t > 0)
320 : t += n.value;
321 :
322 19623 : return CFixed(t);
323 : }
324 :
325 199659 : constexpr CFixed Absolute() const { return CFixed(std::abs(value)); }
326 :
327 : /**
328 : * Multiply by a CFixed. Likely to overflow if both numbers are large,
329 : * so we use an ugly name instead of operator* to make it obvious.
330 : */
331 16389729 : CFixed Multiply(CFixed n) const
332 : {
333 16368194 : std::int64_t t = MUL_I64_I32_I32(value, n.value);
334 16389729 : t >>= fract_bits;
335 :
336 : CheckCastOverflow(t, T, L"Overflow in CFixed::Multiply(CFixed n)", L"Underflow in CFixed::Multiply(CFixed n)")
337 11661109 : return CFixed((T)t);
338 : }
339 :
340 : /**
341 : * Multiply the value by itself. Might overflow.
342 : */
343 4580399 : constexpr CFixed Square() const
344 : {
345 3623302 : return (*this).Multiply(*this);
346 : }
347 :
348 : /**
349 : * Compute this*m/d. Must not have d == 0. Won't overflow if the result can be represented as a CFixed.
350 : */
351 11642 : CFixed MulDiv(CFixed m, CFixed d) const
352 : {
353 11642 : std::int64_t t = MUL_I64_I32_I32(value, m.value) / static_cast<std::int64_t>(d.value);
354 : CheckCastOverflow(t, T, L"Overflow in CFixed::Multiply(CFixed n)", L"Underflow in CFixed::Multiply(CFixed n)")
355 11564 : return CFixed((T)t);
356 : }
357 :
358 201 : constexpr CFixed Sqrt() const
359 : {
360 0 : if (value <= 0)
361 1 : return CFixed(0);
362 199 : std::uint32_t s = isqrt64(static_cast<std::uint64_t>(value) << fract_bits);
363 199 : return CFixed(s);
364 : }
365 :
366 : private:
367 : // Prevent dangerous accidental implicit conversions of floats to ints in certain operations
368 : CFixed operator*(float n) const;
369 : CFixed operator/(float n) const;
370 : };
371 :
372 : /**
373 : * A fixed-point number class with 1-bit sign, 15-bit integral part, 16-bit fractional part.
374 : */
375 : typedef CFixed<std::int32_t, static_cast<std::int32_t>(0x7fffffff), 32, 15, 16, 65536> CFixed_15_16;
376 :
377 : /**
378 : * Default fixed-point type used by the engine.
379 : */
380 : typedef CFixed_15_16 fixed;
381 :
382 : namespace std
383 : {
384 : /**
385 : * std::numeric_limits specialisation, currently just providing min and max
386 : */
387 : template<typename T, T max_t, int total_bits, int int_bits, int fract_bits_, int fract_pow2>
388 : struct numeric_limits<CFixed<T, max_t, total_bits, int_bits, fract_bits_, fract_pow2> >
389 : {
390 : typedef CFixed<T, max_t, total_bits, int_bits, fract_bits_, fract_pow2> fixed;
391 : public:
392 : static const bool is_specialized = true;
393 80 : static fixed min() throw() { fixed f; f.SetInternalValue(std::numeric_limits<T>::min()); return f; }
394 95 : static fixed max() throw() { fixed f; f.SetInternalValue(std::numeric_limits<T>::max()); return f; }
395 : };
396 : }
397 :
398 : /**
399 : * Inaccurate approximation of atan2 over fixed-point numbers.
400 : * Maximum error is almost 0.08 radians (4.5 degrees).
401 : */
402 : CFixed_15_16 atan2_approx(CFixed_15_16 y, CFixed_15_16 x);
403 :
404 : /**
405 : * Compute sin(a) and cos(a).
406 : * Maximum error for -2pi < a < 2pi is almost 0.0005.
407 : */
408 : void sincos_approx(CFixed_15_16 a, CFixed_15_16& sin_out, CFixed_15_16& cos_out);
409 :
410 : #endif // INCLUDED_FIXED
|