blob: 5b1dd9956cb2f2f6b21b0df3e65547041f00e810 [file] [log] [blame]
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +00001//
shannonwoods@chromium.org92b9cd52013-05-30 00:14:48 +00002// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +00003// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7// mathutil.h: Math and bit manipulation functions.
8
Geoff Lang0a73dd82014-11-19 16:18:08 -05009#ifndef COMMON_MATHUTIL_H_
10#define COMMON_MATHUTIL_H_
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +000011
Jamie Madillb155bbc2014-01-13 09:51:03 -050012#include <limits>
13#include <algorithm>
Arun Patolecdfa8f52015-06-30 17:48:25 +053014#include <math.h>
Jamie Madill4f267862014-04-17 15:53:37 -040015#include <string.h>
Arun Patolecdfa8f52015-06-30 17:48:25 +053016#include <stdint.h>
Jamie Madill3b9bb722015-01-05 16:17:02 -050017#include <stdlib.h>
Jamie Madillb155bbc2014-01-13 09:51:03 -050018
Jamie Madill5ea762a2017-06-07 14:59:51 -040019#include <anglebase/numerics/safe_math.h>
Jamie Madille2e406c2016-06-02 13:04:10 -040020
21#include "common/debug.h"
22#include "common/platform.h"
23
24namespace angle
25{
26using base::CheckedNumeric;
27using base::IsValueInRangeForNumericType;
28}
29
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +000030namespace gl
31{
shannonwoods@chromium.org49ec9922013-05-30 00:16:38 +000032
33const unsigned int Float32One = 0x3F800000;
34const unsigned short Float16One = 0x3C00;
35
Corentin Wallez0c7baf12016-12-19 15:43:10 -050036template<typename T>
37inline bool isPow2(T x)
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +000038{
Corentin Wallez0c7baf12016-12-19 15:43:10 -050039 static_assert(std::is_integral<T>::value, "isPow2 must be called on an integer type.");
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +000040 return (x & (x - 1)) == 0 && (x != 0);
41}
42
43inline int log2(int x)
44{
45 int r = 0;
daniel@transgaming.come2b22122010-03-11 19:22:14 +000046 while ((x >> r) > 1) r++;
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +000047 return r;
48}
49
daniel@transgaming.com81655a72010-05-20 19:18:17 +000050inline unsigned int ceilPow2(unsigned int x)
51{
52 if (x != 0) x--;
53 x |= x >> 1;
54 x |= x >> 2;
55 x |= x >> 4;
56 x |= x >> 8;
57 x |= x >> 16;
58 x++;
59
60 return x;
61}
62
Jamie Madillb155bbc2014-01-13 09:51:03 -050063inline int clampToInt(unsigned int x)
64{
65 return static_cast<int>(std::min(x, static_cast<unsigned int>(std::numeric_limits<int>::max())));
66}
67
Jamie Madill70656a62014-03-05 15:01:26 -050068template <typename DestT, typename SrcT>
69inline DestT clampCast(SrcT value)
70{
Corentin Wallez630d85c2015-09-30 14:35:48 -070071 static const DestT destLo = std::numeric_limits<DestT>::min();
72 static const DestT destHi = std::numeric_limits<DestT>::max();
73 static const SrcT srcLo = static_cast<SrcT>(destLo);
74 static const SrcT srcHi = static_cast<SrcT>(destHi);
Jamie Madill62d31cb2015-09-11 13:25:51 -040075
Corentin Wallez630d85c2015-09-30 14:35:48 -070076 // When value is outside of or equal to the limits for DestT we use the DestT limit directly.
77 // This avoids undefined behaviors due to loss of precision when converting from floats to
78 // integers:
79 // destHi for ints is 2147483647 but the closest float number is around 2147483648, so when
80 // doing a conversion from float to int we run into an UB because the float is outside of the
81 // range representable by the int.
82 if (value <= srcLo)
83 {
84 return destLo;
85 }
86 else if (value >= srcHi)
87 {
88 return destHi;
89 }
90 else
91 {
92 return static_cast<DestT>(value);
93 }
Jamie Madill70656a62014-03-05 15:01:26 -050094}
95
apatrick@chromium.orgb31f5322011-01-19 19:02:52 +000096template<typename T, typename MIN, typename MAX>
97inline T clamp(T x, MIN min, MAX max)
98{
shannon.woods@transgaming.com31c4f232013-02-28 23:14:18 +000099 // Since NaNs fail all comparison tests, a NaN value will default to min
100 return x > min ? (x > max ? max : x) : min;
apatrick@chromium.orgb31f5322011-01-19 19:02:52 +0000101}
102
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +0000103inline float clamp01(float x)
104{
apatrick@chromium.orgb31f5322011-01-19 19:02:52 +0000105 return clamp(x, 0.0f, 1.0f);
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +0000106}
107
108template<const int n>
109inline unsigned int unorm(float x)
110{
111 const unsigned int max = 0xFFFFFFFF >> (32 - n);
112
daniel@transgaming.come2b22122010-03-11 19:22:14 +0000113 if (x > 1)
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +0000114 {
115 return max;
116 }
daniel@transgaming.come2b22122010-03-11 19:22:14 +0000117 else if (x < 0)
daniel@transgaming.com4f39fd92010-03-08 20:26:45 +0000118 {
119 return 0;
120 }
121 else
122 {
123 return (unsigned int)(max * x + 0.5f);
124 }
125}
apatrick@chromium.orgb31f5322011-01-19 19:02:52 +0000126
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000127inline bool supportsSSE2()
128{
Geoff Lang5695fc92016-07-05 14:47:30 -0400129#if defined(ANGLE_USE_SSE)
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000130 static bool checked = false;
131 static bool supports = false;
132
133 if (checked)
134 {
135 return supports;
136 }
137
Geoff Lang5695fc92016-07-05 14:47:30 -0400138#if defined(ANGLE_PLATFORM_WINDOWS) && !defined(_M_ARM)
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000139 {
Geoff Lang5695fc92016-07-05 14:47:30 -0400140 int info[4];
141 __cpuid(info, 0);
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000142
Geoff Lang5695fc92016-07-05 14:47:30 -0400143 if (info[0] >= 1)
144 {
145 __cpuid(info, 1);
146
147 supports = (info[3] >> 26) & 1;
148 }
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000149 }
Geoff Lang5695fc92016-07-05 14:47:30 -0400150#endif // defined(ANGLE_PLATFORM_WINDOWS) && !defined(_M_ARM)
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000151 checked = true;
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000152 return supports;
Geoff Lang5695fc92016-07-05 14:47:30 -0400153#else // defined(ANGLE_USE_SSE)
Geoff Lang83217792014-01-16 09:52:38 -0500154 return false;
155#endif
jbauman@chromium.orgf1f28c82011-05-12 20:53:34 +0000156}
apatrick@chromium.orgaa480672012-09-05 19:32:38 +0000157
shannonwoods@chromium.orga43d8292013-05-30 00:15:50 +0000158template <typename destType, typename sourceType>
159destType bitCast(const sourceType &source)
160{
Jamie Madill7ab02fa2014-02-04 16:04:08 -0500161 size_t copySize = std::min(sizeof(destType), sizeof(sourceType));
shannonwoods@chromium.orga43d8292013-05-30 00:15:50 +0000162 destType output;
Jamie Madill7ab02fa2014-02-04 16:04:08 -0500163 memcpy(&output, &source, copySize);
shannonwoods@chromium.orga43d8292013-05-30 00:15:50 +0000164 return output;
165}
166
daniel@transgaming.com2e38b802012-10-17 18:30:06 +0000167inline unsigned short float32ToFloat16(float fp32)
168{
hendrikw75782622015-09-25 11:28:50 -0700169 unsigned int fp32i = bitCast<unsigned int>(fp32);
daniel@transgaming.com2e38b802012-10-17 18:30:06 +0000170 unsigned int sign = (fp32i & 0x80000000) >> 16;
171 unsigned int abs = fp32i & 0x7FFFFFFF;
172
173 if(abs > 0x47FFEFFF) // Infinity
174 {
Minmin Gong794e0002015-04-07 18:31:54 -0700175 return static_cast<unsigned short>(sign | 0x7FFF);
daniel@transgaming.com2e38b802012-10-17 18:30:06 +0000176 }
177 else if(abs < 0x38800000) // Denormal
178 {
shannonwoods@chromium.orga2ecfcc2013-05-30 00:11:59 +0000179 unsigned int mantissa = (abs & 0x007FFFFF) | 0x00800000;
daniel@transgaming.com2e38b802012-10-17 18:30:06 +0000180 int e = 113 - (abs >> 23);
181
182 if(e < 24)
183 {
184 abs = mantissa >> e;
185 }
186 else
187 {
188 abs = 0;
189 }
190
Minmin Gong794e0002015-04-07 18:31:54 -0700191 return static_cast<unsigned short>(sign | (abs + 0x00000FFF + ((abs >> 13) & 1)) >> 13);
daniel@transgaming.com2e38b802012-10-17 18:30:06 +0000192 }
193 else
194 {
Minmin Gong794e0002015-04-07 18:31:54 -0700195 return static_cast<unsigned short>(sign | (abs + 0xC8000000 + 0x00000FFF + ((abs >> 13) & 1)) >> 13);
daniel@transgaming.com2e38b802012-10-17 18:30:06 +0000196 }
197}
198
apatrick@chromium.orgaa480672012-09-05 19:32:38 +0000199float float16ToFloat32(unsigned short h);
200
shannonwoods@chromium.org92b9cd52013-05-30 00:14:48 +0000201unsigned int convertRGBFloatsTo999E5(float red, float green, float blue);
202void convert999E5toRGBFloats(unsigned int input, float *red, float *green, float *blue);
203
shannonwoods@chromium.orga43d8292013-05-30 00:15:50 +0000204inline unsigned short float32ToFloat11(float fp32)
205{
206 const unsigned int float32MantissaMask = 0x7FFFFF;
207 const unsigned int float32ExponentMask = 0x7F800000;
208 const unsigned int float32SignMask = 0x80000000;
209 const unsigned int float32ValueMask = ~float32SignMask;
210 const unsigned int float32ExponentFirstBit = 23;
211 const unsigned int float32ExponentBias = 127;
212
213 const unsigned short float11Max = 0x7BF;
214 const unsigned short float11MantissaMask = 0x3F;
215 const unsigned short float11ExponentMask = 0x7C0;
216 const unsigned short float11BitMask = 0x7FF;
217 const unsigned int float11ExponentBias = 14;
218
219 const unsigned int float32Maxfloat11 = 0x477E0000;
220 const unsigned int float32Minfloat11 = 0x38800000;
221
222 const unsigned int float32Bits = bitCast<unsigned int>(fp32);
223 const bool float32Sign = (float32Bits & float32SignMask) == float32SignMask;
224
225 unsigned int float32Val = float32Bits & float32ValueMask;
226
227 if ((float32Val & float32ExponentMask) == float32ExponentMask)
228 {
229 // INF or NAN
230 if ((float32Val & float32MantissaMask) != 0)
231 {
232 return float11ExponentMask | (((float32Val >> 17) | (float32Val >> 11) | (float32Val >> 6) | (float32Val)) & float11MantissaMask);
233 }
234 else if (float32Sign)
235 {
236 // -INF is clamped to 0 since float11 is positive only
237 return 0;
238 }
239 else
240 {
241 return float11ExponentMask;
242 }
243 }
244 else if (float32Sign)
245 {
246 // float11 is positive only, so clamp to zero
247 return 0;
248 }
249 else if (float32Val > float32Maxfloat11)
250 {
251 // The number is too large to be represented as a float11, set to max
252 return float11Max;
253 }
254 else
255 {
256 if (float32Val < float32Minfloat11)
257 {
258 // The number is too small to be represented as a normalized float11
259 // Convert it to a denormalized value.
260 const unsigned int shift = (float32ExponentBias - float11ExponentBias) - (float32Val >> float32ExponentFirstBit);
261 float32Val = ((1 << float32ExponentFirstBit) | (float32Val & float32MantissaMask)) >> shift;
262 }
263 else
264 {
265 // Rebias the exponent to represent the value as a normalized float11
266 float32Val += 0xC8000000;
267 }
268
269 return ((float32Val + 0xFFFF + ((float32Val >> 17) & 1)) >> 17) & float11BitMask;
270 }
271}
272
273inline unsigned short float32ToFloat10(float fp32)
274{
275 const unsigned int float32MantissaMask = 0x7FFFFF;
276 const unsigned int float32ExponentMask = 0x7F800000;
277 const unsigned int float32SignMask = 0x80000000;
278 const unsigned int float32ValueMask = ~float32SignMask;
279 const unsigned int float32ExponentFirstBit = 23;
280 const unsigned int float32ExponentBias = 127;
281
282 const unsigned short float10Max = 0x3DF;
283 const unsigned short float10MantissaMask = 0x1F;
284 const unsigned short float10ExponentMask = 0x3E0;
285 const unsigned short float10BitMask = 0x3FF;
286 const unsigned int float10ExponentBias = 14;
287
288 const unsigned int float32Maxfloat10 = 0x477C0000;
289 const unsigned int float32Minfloat10 = 0x38800000;
290
291 const unsigned int float32Bits = bitCast<unsigned int>(fp32);
292 const bool float32Sign = (float32Bits & float32SignMask) == float32SignMask;
293
294 unsigned int float32Val = float32Bits & float32ValueMask;
295
296 if ((float32Val & float32ExponentMask) == float32ExponentMask)
297 {
298 // INF or NAN
299 if ((float32Val & float32MantissaMask) != 0)
300 {
301 return float10ExponentMask | (((float32Val >> 18) | (float32Val >> 13) | (float32Val >> 3) | (float32Val)) & float10MantissaMask);
302 }
303 else if (float32Sign)
304 {
305 // -INF is clamped to 0 since float11 is positive only
306 return 0;
307 }
308 else
309 {
310 return float10ExponentMask;
311 }
312 }
313 else if (float32Sign)
314 {
315 // float10 is positive only, so clamp to zero
316 return 0;
317 }
318 else if (float32Val > float32Maxfloat10)
319 {
320 // The number is too large to be represented as a float11, set to max
321 return float10Max;
322 }
323 else
324 {
325 if (float32Val < float32Minfloat10)
326 {
327 // The number is too small to be represented as a normalized float11
328 // Convert it to a denormalized value.
329 const unsigned int shift = (float32ExponentBias - float10ExponentBias) - (float32Val >> float32ExponentFirstBit);
330 float32Val = ((1 << float32ExponentFirstBit) | (float32Val & float32MantissaMask)) >> shift;
331 }
332 else
333 {
334 // Rebias the exponent to represent the value as a normalized float11
335 float32Val += 0xC8000000;
336 }
337
338 return ((float32Val + 0x1FFFF + ((float32Val >> 18) & 1)) >> 18) & float10BitMask;
339 }
340}
341
342inline float float11ToFloat32(unsigned short fp11)
343{
344 unsigned short exponent = (fp11 >> 6) & 0x1F;
345 unsigned short mantissa = fp11 & 0x3F;
346
347 if (exponent == 0x1F)
348 {
349 // INF or NAN
350 return bitCast<float>(0x7f800000 | (mantissa << 17));
351 }
352 else
353 {
354 if (exponent != 0)
355 {
356 // normalized
357 }
358 else if (mantissa != 0)
359 {
360 // The value is denormalized
361 exponent = 1;
362
363 do
364 {
365 exponent--;
366 mantissa <<= 1;
367 }
368 while ((mantissa & 0x40) == 0);
369
370 mantissa = mantissa & 0x3F;
371 }
372 else // The value is zero
373 {
Austin Kinrossb8af7232015-03-16 22:33:25 -0700374 exponent = static_cast<unsigned short>(-112);
shannonwoods@chromium.orga43d8292013-05-30 00:15:50 +0000375 }
376
377 return bitCast<float>(((exponent + 112) << 23) | (mantissa << 17));
378 }
379}
380
381inline float float10ToFloat32(unsigned short fp11)
382{
383 unsigned short exponent = (fp11 >> 5) & 0x1F;
384 unsigned short mantissa = fp11 & 0x1F;
385
386 if (exponent == 0x1F)
387 {
388 // INF or NAN
389 return bitCast<float>(0x7f800000 | (mantissa << 17));
390 }
391 else
392 {
393 if (exponent != 0)
394 {
395 // normalized
396 }
397 else if (mantissa != 0)
398 {
399 // The value is denormalized
400 exponent = 1;
401
402 do
403 {
404 exponent--;
405 mantissa <<= 1;
406 }
407 while ((mantissa & 0x20) == 0);
408
409 mantissa = mantissa & 0x1F;
410 }
411 else // The value is zero
412 {
Austin Kinrossb8af7232015-03-16 22:33:25 -0700413 exponent = static_cast<unsigned short>(-112);
shannonwoods@chromium.orga43d8292013-05-30 00:15:50 +0000414 }
415
416 return bitCast<float>(((exponent + 112) << 23) | (mantissa << 18));
417 }
418}
419
Geoff Lang446a4472013-06-04 10:03:14 -0400420template <typename T>
421inline float normalizedToFloat(T input)
422{
Geoff Langd4475812015-03-18 10:53:05 -0400423 static_assert(std::numeric_limits<T>::is_integer, "T must be an integer.");
Geoff Lang446a4472013-06-04 10:03:14 -0400424
425 const float inverseMax = 1.0f / std::numeric_limits<T>::max();
426 return input * inverseMax;
427}
428
429template <unsigned int inputBitCount, typename T>
430inline float normalizedToFloat(T input)
431{
Geoff Langd4475812015-03-18 10:53:05 -0400432 static_assert(std::numeric_limits<T>::is_integer, "T must be an integer.");
433 static_assert(inputBitCount < (sizeof(T) * 8), "T must have more bits than inputBitCount.");
Geoff Lang446a4472013-06-04 10:03:14 -0400434
435 const float inverseMax = 1.0f / ((1 << inputBitCount) - 1);
436 return input * inverseMax;
437}
438
439template <typename T>
440inline T floatToNormalized(float input)
441{
Minmin Gong794e0002015-04-07 18:31:54 -0700442 return static_cast<T>(std::numeric_limits<T>::max() * input + 0.5f);
Geoff Lang446a4472013-06-04 10:03:14 -0400443}
444
445template <unsigned int outputBitCount, typename T>
446inline T floatToNormalized(float input)
447{
Geoff Langd4475812015-03-18 10:53:05 -0400448 static_assert(outputBitCount < (sizeof(T) * 8), "T must have more bits than outputBitCount.");
Minmin Gong794e0002015-04-07 18:31:54 -0700449 return static_cast<T>(((1 << outputBitCount) - 1) * input + 0.5f);
Geoff Lang446a4472013-06-04 10:03:14 -0400450}
451
452template <unsigned int inputBitCount, unsigned int inputBitStart, typename T>
453inline T getShiftedData(T input)
454{
Geoff Langd4475812015-03-18 10:53:05 -0400455 static_assert(inputBitCount + inputBitStart <= (sizeof(T) * 8),
456 "T must have at least as many bits as inputBitCount + inputBitStart.");
Geoff Lang446a4472013-06-04 10:03:14 -0400457 const T mask = (1 << inputBitCount) - 1;
458 return (input >> inputBitStart) & mask;
459}
460
461template <unsigned int inputBitCount, unsigned int inputBitStart, typename T>
462inline T shiftData(T input)
463{
Geoff Langd4475812015-03-18 10:53:05 -0400464 static_assert(inputBitCount + inputBitStart <= (sizeof(T) * 8),
465 "T must have at least as many bits as inputBitCount + inputBitStart.");
Geoff Lang446a4472013-06-04 10:03:14 -0400466 const T mask = (1 << inputBitCount) - 1;
467 return (input & mask) << inputBitStart;
468}
469
Olli Etuaho0f2b1562016-05-13 16:15:35 +0300470inline unsigned int CountLeadingZeros(uint32_t x)
471{
472 // Use binary search to find the amount of leading zeros.
473 unsigned int zeros = 32u;
474 uint32_t y;
475
476 y = x >> 16u;
477 if (y != 0)
478 {
479 zeros = zeros - 16u;
480 x = y;
481 }
482 y = x >> 8u;
483 if (y != 0)
484 {
485 zeros = zeros - 8u;
486 x = y;
487 }
488 y = x >> 4u;
489 if (y != 0)
490 {
491 zeros = zeros - 4u;
492 x = y;
493 }
494 y = x >> 2u;
495 if (y != 0)
496 {
497 zeros = zeros - 2u;
498 x = y;
499 }
500 y = x >> 1u;
501 if (y != 0)
502 {
503 return zeros - 2u;
504 }
505 return zeros - x;
506}
Geoff Lang446a4472013-06-04 10:03:14 -0400507
508inline unsigned char average(unsigned char a, unsigned char b)
509{
510 return ((a ^ b) >> 1) + (a & b);
511}
512
513inline signed char average(signed char a, signed char b)
514{
515 return ((short)a + (short)b) / 2;
516}
517
518inline unsigned short average(unsigned short a, unsigned short b)
519{
520 return ((a ^ b) >> 1) + (a & b);
521}
522
523inline signed short average(signed short a, signed short b)
524{
525 return ((int)a + (int)b) / 2;
526}
527
528inline unsigned int average(unsigned int a, unsigned int b)
529{
530 return ((a ^ b) >> 1) + (a & b);
531}
532
Corentin Wallezca311dd2015-12-07 15:07:48 -0500533inline int average(int a, int b)
Geoff Lang446a4472013-06-04 10:03:14 -0400534{
Corentin Wallezca311dd2015-12-07 15:07:48 -0500535 long long average = (static_cast<long long>(a) + static_cast<long long>(b)) / 2ll;
536 return static_cast<int>(average);
Geoff Lang446a4472013-06-04 10:03:14 -0400537}
538
539inline float average(float a, float b)
540{
541 return (a + b) * 0.5f;
542}
543
544inline unsigned short averageHalfFloat(unsigned short a, unsigned short b)
545{
546 return float32ToFloat16((float16ToFloat32(a) + float16ToFloat32(b)) * 0.5f);
547}
548
549inline unsigned int averageFloat11(unsigned int a, unsigned int b)
550{
Minmin Gong794e0002015-04-07 18:31:54 -0700551 return float32ToFloat11((float11ToFloat32(static_cast<unsigned short>(a)) + float11ToFloat32(static_cast<unsigned short>(b))) * 0.5f);
Geoff Lang446a4472013-06-04 10:03:14 -0400552}
553
554inline unsigned int averageFloat10(unsigned int a, unsigned int b)
555{
Minmin Gong794e0002015-04-07 18:31:54 -0700556 return float32ToFloat10((float10ToFloat32(static_cast<unsigned short>(a)) + float10ToFloat32(static_cast<unsigned short>(b))) * 0.5f);
Geoff Lang446a4472013-06-04 10:03:14 -0400557}
558
Jamie Madill39b43462014-08-18 16:39:50 -0400559template <typename T>
shannon.woods@transgaming.comb3560252013-02-28 23:07:04 +0000560struct Range
561{
562 Range() {}
Jamie Madillcc002392014-09-09 10:21:56 -0400563 Range(T lo, T hi) : start(lo), end(hi) { ASSERT(lo <= hi); }
shannon.woods@transgaming.comb3560252013-02-28 23:07:04 +0000564
Jamie Madill39b43462014-08-18 16:39:50 -0400565 T start;
566 T end;
567
Jamie Madillcc002392014-09-09 10:21:56 -0400568 T length() const { return end - start; }
Corentin Wallezac6ff932014-11-12 06:16:53 -0800569
570 bool intersects(Range<T> other)
571 {
572 if (start <= other.start)
573 {
574 return other.start < end;
575 }
576 else
577 {
578 return start < other.end;
579 }
580 }
Jamie Madillaa9e9972015-06-22 13:57:16 -0400581
582 void extend(T value)
583 {
584 start = value > start ? value : start;
585 end = value < end ? value : end;
586 }
587
588 bool empty() const
589 {
590 return end <= start;
591 }
shannon.woods@transgaming.comb3560252013-02-28 23:07:04 +0000592};
593
Jamie Madill39b43462014-08-18 16:39:50 -0400594typedef Range<int> RangeI;
595typedef Range<unsigned int> RangeUI;
596
Geoff Lang3edfe032015-09-04 16:38:24 -0400597struct IndexRange
598{
599 IndexRange() : IndexRange(0, 0, 0) {}
600 IndexRange(size_t start_, size_t end_, size_t vertexIndexCount_)
601 : start(start_), end(end_), vertexIndexCount(vertexIndexCount_)
602 {
603 ASSERT(start <= end);
604 }
605
606 // Number of vertices in the range.
607 size_t vertexCount() const { return (end - start) + 1; }
608
609 // Inclusive range of indices that are not primitive restart
610 size_t start;
611 size_t end;
612
613 // Number of non-primitive restart indices
614 size_t vertexIndexCount;
615};
616
Olli Etuaho74da73f2017-02-01 15:37:48 +0000617// Combine a floating-point value representing a mantissa (x) and an integer exponent (exp) into a
618// floating-point value. As in GLSL ldexp() built-in.
619inline float Ldexp(float x, int exp)
620{
621 if (exp > 128)
622 {
623 return std::numeric_limits<float>::infinity();
624 }
625 if (exp < -126)
626 {
627 return 0.0f;
628 }
629 double result = static_cast<double>(x) * std::pow(2.0, static_cast<double>(exp));
630 return static_cast<float>(result);
631}
632
Arun Patolecdfa8f52015-06-30 17:48:25 +0530633// First, both normalized floating-point values are converted into 16-bit integer values.
634// Then, the results are packed into the returned 32-bit unsigned integer.
635// The first float value will be written to the least significant bits of the output;
636// the last float value will be written to the most significant bits.
637// The conversion of each value to fixed point is done as follows :
638// packSnorm2x16 : round(clamp(c, -1, +1) * 32767.0)
639inline uint32_t packSnorm2x16(float f1, float f2)
640{
Yuly Novikov451ed252016-01-21 21:16:45 -0500641 int16_t leastSignificantBits = static_cast<int16_t>(roundf(clamp(f1, -1.0f, 1.0f) * 32767.0f));
642 int16_t mostSignificantBits = static_cast<int16_t>(roundf(clamp(f2, -1.0f, 1.0f) * 32767.0f));
643 return static_cast<uint32_t>(mostSignificantBits) << 16 |
644 (static_cast<uint32_t>(leastSignificantBits) & 0xFFFF);
Arun Patolecdfa8f52015-06-30 17:48:25 +0530645}
646
647// First, unpacks a single 32-bit unsigned integer u into a pair of 16-bit unsigned integers. Then, each
648// component is converted to a normalized floating-point value to generate the returned two float values.
649// The first float value will be extracted from the least significant bits of the input;
650// the last float value will be extracted from the most-significant bits.
651// The conversion for unpacked fixed-point value to floating point is done as follows:
652// unpackSnorm2x16 : clamp(f / 32767.0, -1, +1)
653inline void unpackSnorm2x16(uint32_t u, float *f1, float *f2)
654{
655 int16_t leastSignificantBits = static_cast<int16_t>(u & 0xFFFF);
656 int16_t mostSignificantBits = static_cast<int16_t>(u >> 16);
657 *f1 = clamp(static_cast<float>(leastSignificantBits) / 32767.0f, -1.0f, 1.0f);
658 *f2 = clamp(static_cast<float>(mostSignificantBits) / 32767.0f, -1.0f, 1.0f);
659}
660
661// First, both normalized floating-point values are converted into 16-bit integer values.
662// Then, the results are packed into the returned 32-bit unsigned integer.
663// The first float value will be written to the least significant bits of the output;
664// the last float value will be written to the most significant bits.
665// The conversion of each value to fixed point is done as follows:
666// packUnorm2x16 : round(clamp(c, 0, +1) * 65535.0)
667inline uint32_t packUnorm2x16(float f1, float f2)
668{
669 uint16_t leastSignificantBits = static_cast<uint16_t>(roundf(clamp(f1, 0.0f, 1.0f) * 65535.0f));
670 uint16_t mostSignificantBits = static_cast<uint16_t>(roundf(clamp(f2, 0.0f, 1.0f) * 65535.0f));
671 return static_cast<uint32_t>(mostSignificantBits) << 16 | static_cast<uint32_t>(leastSignificantBits);
672}
673
674// First, unpacks a single 32-bit unsigned integer u into a pair of 16-bit unsigned integers. Then, each
675// component is converted to a normalized floating-point value to generate the returned two float values.
676// The first float value will be extracted from the least significant bits of the input;
677// the last float value will be extracted from the most-significant bits.
678// The conversion for unpacked fixed-point value to floating point is done as follows:
679// unpackUnorm2x16 : f / 65535.0
680inline void unpackUnorm2x16(uint32_t u, float *f1, float *f2)
681{
682 uint16_t leastSignificantBits = static_cast<uint16_t>(u & 0xFFFF);
683 uint16_t mostSignificantBits = static_cast<uint16_t>(u >> 16);
684 *f1 = static_cast<float>(leastSignificantBits) / 65535.0f;
685 *f2 = static_cast<float>(mostSignificantBits) / 65535.0f;
686}
687
Olli Etuaho25aef452017-01-29 16:15:44 -0800688// Helper functions intended to be used only here.
689namespace priv
690{
691
692inline uint8_t ToPackedUnorm8(float f)
693{
694 return static_cast<uint8_t>(roundf(clamp(f, 0.0f, 1.0f) * 255.0f));
695}
696
697inline int8_t ToPackedSnorm8(float f)
698{
699 return static_cast<int8_t>(roundf(clamp(f, -1.0f, 1.0f) * 127.0f));
700}
701
702} // namespace priv
703
704// Packs 4 normalized unsigned floating-point values to a single 32-bit unsigned integer. Works
705// similarly to packUnorm2x16. The floats are clamped to the range 0.0 to 1.0, and written to the
706// unsigned integer starting from the least significant bits.
707inline uint32_t PackUnorm4x8(float f1, float f2, float f3, float f4)
708{
709 uint8_t bits[4];
710 bits[0] = priv::ToPackedUnorm8(f1);
711 bits[1] = priv::ToPackedUnorm8(f2);
712 bits[2] = priv::ToPackedUnorm8(f3);
713 bits[3] = priv::ToPackedUnorm8(f4);
714 uint32_t result = 0u;
715 for (int i = 0; i < 4; ++i)
716 {
717 int shift = i * 8;
718 result |= (static_cast<uint32_t>(bits[i]) << shift);
719 }
720 return result;
721}
722
723// Unpacks 4 normalized unsigned floating-point values from a single 32-bit unsigned integer into f.
724// Works similarly to unpackUnorm2x16. The floats are unpacked starting from the least significant
725// bits.
726inline void UnpackUnorm4x8(uint32_t u, float *f)
727{
728 for (int i = 0; i < 4; ++i)
729 {
730 int shift = i * 8;
731 uint8_t bits = static_cast<uint8_t>((u >> shift) & 0xFF);
732 f[i] = static_cast<float>(bits) / 255.0f;
733 }
734}
735
736// Packs 4 normalized signed floating-point values to a single 32-bit unsigned integer. The floats
737// are clamped to the range -1.0 to 1.0, and written to the unsigned integer starting from the least
738// significant bits.
739inline uint32_t PackSnorm4x8(float f1, float f2, float f3, float f4)
740{
741 int8_t bits[4];
742 bits[0] = priv::ToPackedSnorm8(f1);
743 bits[1] = priv::ToPackedSnorm8(f2);
744 bits[2] = priv::ToPackedSnorm8(f3);
745 bits[3] = priv::ToPackedSnorm8(f4);
746 uint32_t result = 0u;
747 for (int i = 0; i < 4; ++i)
748 {
749 int shift = i * 8;
750 result |= ((static_cast<uint32_t>(bits[i]) & 0xFF) << shift);
751 }
752 return result;
753}
754
755// Unpacks 4 normalized signed floating-point values from a single 32-bit unsigned integer into f.
756// Works similarly to unpackSnorm2x16. The floats are unpacked starting from the least significant
757// bits, and clamped to the range -1.0 to 1.0.
758inline void UnpackSnorm4x8(uint32_t u, float *f)
759{
760 for (int i = 0; i < 4; ++i)
761 {
762 int shift = i * 8;
763 int8_t bits = static_cast<int8_t>((u >> shift) & 0xFF);
764 f[i] = clamp(static_cast<float>(bits) / 127.0f, -1.0f, 1.0f);
765 }
766}
767
Arun Patolecdfa8f52015-06-30 17:48:25 +0530768// Returns an unsigned integer obtained by converting the two floating-point values to the 16-bit
769// floating-point representation found in the OpenGL ES Specification, and then packing these
770// two 16-bit integers into a 32-bit unsigned integer.
771// f1: The 16 least-significant bits of the result;
772// f2: The 16 most-significant bits.
773inline uint32_t packHalf2x16(float f1, float f2)
774{
775 uint16_t leastSignificantBits = static_cast<uint16_t>(float32ToFloat16(f1));
776 uint16_t mostSignificantBits = static_cast<uint16_t>(float32ToFloat16(f2));
777 return static_cast<uint32_t>(mostSignificantBits) << 16 | static_cast<uint32_t>(leastSignificantBits);
778}
779
780// Returns two floating-point values obtained by unpacking a 32-bit unsigned integer into a pair of 16-bit values,
781// interpreting those values as 16-bit floating-point numbers according to the OpenGL ES Specification,
782// and converting them to 32-bit floating-point values.
783// The first float value is obtained from the 16 least-significant bits of u;
784// the second component is obtained from the 16 most-significant bits of u.
785inline void unpackHalf2x16(uint32_t u, float *f1, float *f2)
786{
787 uint16_t leastSignificantBits = static_cast<uint16_t>(u & 0xFFFF);
788 uint16_t mostSignificantBits = static_cast<uint16_t>(u >> 16);
789
790 *f1 = float16ToFloat32(leastSignificantBits);
791 *f2 = float16ToFloat32(mostSignificantBits);
792}
793
Geoff Lang451b2b72017-05-15 15:32:02 -0400794inline uint8_t sRGBToLinear(uint8_t srgbValue)
795{
796 float value = srgbValue / 255.0f;
797 if (value <= 0.04045f)
798 {
799 value = value / 12.92f;
800 }
801 else
802 {
803 value = std::pow((value + 0.055f) / 1.055f, 2.4f);
804 }
805 return static_cast<uint8_t>(clamp(value * 255.0f + 0.5f, 0.0f, 255.0f));
806}
807
808inline uint8_t linearToSRGB(uint8_t linearValue)
809{
810 float value = linearValue / 255.0f;
811 if (value <= 0.0f)
812 {
813 value = 0.0f;
814 }
815 else if (value < 0.0031308f)
816 {
817 value = value * 12.92f;
818 }
819 else if (value < 1.0f)
820 {
821 value = std::pow(value, 0.41666f) * 1.055f - 0.055f;
822 }
823 else
824 {
825 value = 1.0f;
826 }
827 return static_cast<uint8_t>(clamp(value * 255.0f + 0.5f, 0.0f, 255.0f));
828}
829
Olli Etuaho9250cb22017-01-21 10:51:27 +0000830// Reverse the order of the bits.
831inline uint32_t BitfieldReverse(uint32_t value)
832{
833 // TODO(oetuaho@nvidia.com): Optimize this if needed. There don't seem to be compiler intrinsics
834 // for this, and right now it's not used in performance-critical paths.
835 uint32_t result = 0u;
836 for (size_t j = 0u; j < 32u; ++j)
837 {
838 result |= (((value >> j) & 1u) << (31u - j));
839 }
840 return result;
841}
842
843// Count the 1 bits.
Jamie Madill6de51852017-04-12 09:53:01 -0400844#if defined(ANGLE_PLATFORM_WINDOWS)
845inline int BitCount(uint32_t bits)
Olli Etuaho9250cb22017-01-21 10:51:27 +0000846{
Olli Etuaho9250cb22017-01-21 10:51:27 +0000847 return static_cast<int>(__popcnt(bits));
Jamie Madill6de51852017-04-12 09:53:01 -0400848}
849#if defined(ANGLE_X64_CPU)
850inline int BitCount(uint64_t bits)
851{
852 return static_cast<int>(__popcnt64(bits));
853}
854#endif // defined(ANGLE_X64_CPU)
855#endif // defined(ANGLE_PLATFORM_WINDOWS)
856
857#if defined(ANGLE_PLATFORM_POSIX)
858inline int BitCount(uint32_t bits)
859{
Olli Etuaho9250cb22017-01-21 10:51:27 +0000860 return __builtin_popcount(bits);
Olli Etuaho9250cb22017-01-21 10:51:27 +0000861}
862
Jamie Madill6de51852017-04-12 09:53:01 -0400863#if defined(ANGLE_X64_CPU)
864inline int BitCount(uint64_t bits)
865{
866 return __builtin_popcountll(bits);
867}
868#endif // defined(ANGLE_X64_CPU)
869#endif // defined(ANGLE_PLATFORM_POSIX)
870
871#if defined(ANGLE_PLATFORM_WINDOWS)
Olli Etuaho9250cb22017-01-21 10:51:27 +0000872// Return the index of the least significant bit set. Indexing is such that bit 0 is the least
Jamie Madill6de51852017-04-12 09:53:01 -0400873// significant bit. Implemented for different bit widths on different platforms.
874inline unsigned long ScanForward(uint32_t bits)
Olli Etuaho9250cb22017-01-21 10:51:27 +0000875{
876 ASSERT(bits != 0u);
Olli Etuaho9250cb22017-01-21 10:51:27 +0000877 unsigned long firstBitIndex = 0ul;
878 unsigned char ret = _BitScanForward(&firstBitIndex, bits);
879 ASSERT(ret != 0u);
880 return firstBitIndex;
Olli Etuaho9250cb22017-01-21 10:51:27 +0000881}
882
Jamie Madill6de51852017-04-12 09:53:01 -0400883#if defined(ANGLE_X64_CPU)
884inline unsigned long ScanForward(uint64_t bits)
885{
886 ASSERT(bits != 0u);
887 unsigned long firstBitIndex = 0ul;
888 unsigned char ret = _BitScanForward64(&firstBitIndex, bits);
889 ASSERT(ret != 0u);
890 return firstBitIndex;
891}
892#endif // defined(ANGLE_X64_CPU)
893#endif // defined(ANGLE_PLATFORM_WINDOWS)
894
895#if defined(ANGLE_PLATFORM_POSIX)
896inline unsigned long ScanForward(uint32_t bits)
897{
898 ASSERT(bits != 0u);
899 return static_cast<unsigned long>(__builtin_ctz(bits));
900}
901
902#if defined(ANGLE_X64_CPU)
903inline unsigned long ScanForward(uint64_t bits)
904{
905 ASSERT(bits != 0u);
906 return static_cast<unsigned long>(__builtin_ctzll(bits));
907}
908#endif // defined(ANGLE_X64_CPU)
909#endif // defined(ANGLE_PLATFORM_POSIX)
910
Olli Etuaho9250cb22017-01-21 10:51:27 +0000911// Return the index of the most significant bit set. Indexing is such that bit 0 is the least
912// significant bit.
913inline unsigned long ScanReverse(unsigned long bits)
914{
915 ASSERT(bits != 0u);
916#if defined(ANGLE_PLATFORM_WINDOWS)
917 unsigned long lastBitIndex = 0ul;
918 unsigned char ret = _BitScanReverse(&lastBitIndex, bits);
919 ASSERT(ret != 0u);
920 return lastBitIndex;
921#elif defined(ANGLE_PLATFORM_POSIX)
922 return static_cast<unsigned long>(sizeof(unsigned long) * CHAR_BIT - 1 - __builtin_clzl(bits));
923#else
924#error Please implement bit-scan-reverse for your platform!
925#endif
926}
927
928// Returns -1 on 0, otherwise the index of the least significant 1 bit as in GLSL.
Jamie Madill6de51852017-04-12 09:53:01 -0400929template <typename T>
930int FindLSB(T bits)
Olli Etuaho9250cb22017-01-21 10:51:27 +0000931{
Jamie Madill6de51852017-04-12 09:53:01 -0400932 static_assert(std::is_integral<T>::value, "must be integral type.");
Olli Etuaho9250cb22017-01-21 10:51:27 +0000933 if (bits == 0u)
934 {
935 return -1;
936 }
937 else
938 {
939 return static_cast<int>(ScanForward(bits));
940 }
941}
942
943// Returns -1 on 0, otherwise the index of the most significant 1 bit as in GLSL.
Jamie Madill6de51852017-04-12 09:53:01 -0400944template <typename T>
945int FindMSB(T bits)
Olli Etuaho9250cb22017-01-21 10:51:27 +0000946{
Jamie Madill6de51852017-04-12 09:53:01 -0400947 static_assert(std::is_integral<T>::value, "must be integral type.");
Olli Etuaho9250cb22017-01-21 10:51:27 +0000948 if (bits == 0u)
949 {
950 return -1;
951 }
952 else
953 {
954 return static_cast<int>(ScanReverse(bits));
955 }
956}
957
Arun Patole551279e2015-07-07 18:18:23 +0530958// Returns whether the argument is Not a Number.
959// IEEE 754 single precision NaN representation: Exponent(8 bits) - 255, Mantissa(23 bits) - non-zero.
960inline bool isNaN(float f)
961{
962 // Exponent mask: ((1u << 8) - 1u) << 23 = 0x7f800000u
963 // Mantissa mask: ((1u << 23) - 1u) = 0x7fffffu
964 return ((bitCast<uint32_t>(f) & 0x7f800000u) == 0x7f800000u) && (bitCast<uint32_t>(f) & 0x7fffffu);
965}
966
967// Returns whether the argument is infinity.
968// IEEE 754 single precision infinity representation: Exponent(8 bits) - 255, Mantissa(23 bits) - zero.
969inline bool isInf(float f)
970{
971 // Exponent mask: ((1u << 8) - 1u) << 23 = 0x7f800000u
972 // Mantissa mask: ((1u << 23) - 1u) = 0x7fffffu
973 return ((bitCast<uint32_t>(f) & 0x7f800000u) == 0x7f800000u) && !(bitCast<uint32_t>(f) & 0x7fffffu);
974}
975
Sami Väisänene45e53b2016-05-25 10:36:04 +0300976namespace priv
977{
978template <unsigned int N, unsigned int R>
979struct iSquareRoot
980{
981 static constexpr unsigned int solve()
982 {
983 return (R * R > N)
984 ? 0
985 : ((R * R == N) ? R : static_cast<unsigned int>(iSquareRoot<N, R + 1>::value));
986 }
987 enum Result
988 {
989 value = iSquareRoot::solve()
990 };
991};
992
993template <unsigned int N>
994struct iSquareRoot<N, N>
995{
996 enum result
997 {
998 value = N
999 };
1000};
1001
1002} // namespace priv
1003
1004template <unsigned int N>
1005constexpr unsigned int iSquareRoot()
1006{
1007 return priv::iSquareRoot<N, 1>::value;
Geoff Lang831b1952015-05-05 11:02:27 -04001008}
1009
Olli Etuaho7f9a55f2016-10-03 14:32:08 +01001010// Sum, difference and multiplication operations for signed ints that wrap on 32-bit overflow.
1011//
1012// Unsigned types are defined to do arithmetic modulo 2^n in C++. For signed types, overflow
1013// behavior is undefined.
1014
1015template <typename T>
1016inline T WrappingSum(T lhs, T rhs)
1017{
1018 uint32_t lhsUnsigned = static_cast<uint32_t>(lhs);
1019 uint32_t rhsUnsigned = static_cast<uint32_t>(rhs);
1020 return static_cast<T>(lhsUnsigned + rhsUnsigned);
1021}
1022
1023template <typename T>
1024inline T WrappingDiff(T lhs, T rhs)
1025{
1026 uint32_t lhsUnsigned = static_cast<uint32_t>(lhs);
1027 uint32_t rhsUnsigned = static_cast<uint32_t>(rhs);
1028 return static_cast<T>(lhsUnsigned - rhsUnsigned);
1029}
1030
1031inline int32_t WrappingMul(int32_t lhs, int32_t rhs)
1032{
1033 int64_t lhsWide = static_cast<int64_t>(lhs);
1034 int64_t rhsWide = static_cast<int64_t>(rhs);
1035 // The multiplication is guaranteed not to overflow.
1036 int64_t resultWide = lhsWide * rhsWide;
1037 // Implement the desired wrapping behavior by masking out the high-order 32 bits.
1038 resultWide = resultWide & 0xffffffffll;
1039 // Casting to a narrower signed type is fine since the casted value is representable in the
1040 // narrower type.
1041 return static_cast<int32_t>(resultWide);
1042}
1043
Sami Väisänene45e53b2016-05-25 10:36:04 +03001044} // namespace gl
1045
Geoff Lang831b1952015-05-05 11:02:27 -04001046namespace rx
1047{
1048
shannonwoods@chromium.org06d4e842013-05-30 00:04:42 +00001049template <typename T>
1050T roundUp(const T value, const T alignment)
1051{
Jamie Madille2e406c2016-06-02 13:04:10 -04001052 auto temp = value + alignment - static_cast<T>(1);
1053 return temp - temp % alignment;
1054}
1055
1056template <typename T>
1057angle::CheckedNumeric<T> CheckedRoundUp(const T value, const T alignment)
1058{
1059 angle::CheckedNumeric<T> checkedValue(value);
1060 angle::CheckedNumeric<T> checkedAlignment(alignment);
1061 return roundUp(checkedValue, checkedAlignment);
shannonwoods@chromium.org06d4e842013-05-30 00:04:42 +00001062}
1063
Jamie Madillaff80842014-08-04 10:47:56 -04001064inline unsigned int UnsignedCeilDivide(unsigned int value, unsigned int divisor)
1065{
1066 unsigned int divided = value / divisor;
1067 return (divided + ((value % divisor == 0) ? 0 : 1));
1068}
1069
Jamie Madill3b9bb722015-01-05 16:17:02 -05001070#if defined(_MSC_VER)
1071
1072#define ANGLE_ROTL(x,y) _rotl(x,y)
Austin Kinross405f3472015-06-04 13:09:06 -07001073#define ANGLE_ROTR16(x,y) _rotr16(x,y)
Jamie Madill3b9bb722015-01-05 16:17:02 -05001074
1075#else
1076
1077inline uint32_t RotL(uint32_t x, int8_t r)
1078{
1079 return (x << r) | (x >> (32 - r));
1080}
1081
Austin Kinross405f3472015-06-04 13:09:06 -07001082inline uint16_t RotR16(uint16_t x, int8_t r)
1083{
1084 return (x >> r) | (x << (16 - r));
1085}
1086
Geoff Lang6e4cfce2016-06-13 15:06:31 -04001087#define ANGLE_ROTL(x, y) ::rx::RotL(x, y)
1088#define ANGLE_ROTR16(x, y) ::rx::RotR16(x, y)
Jamie Madill3b9bb722015-01-05 16:17:02 -05001089
1090#endif // namespace rx
1091
shannon.woods@transgaming.comb3560252013-02-28 23:07:04 +00001092}
1093
Geoff Lang0a73dd82014-11-19 16:18:08 -05001094#endif // COMMON_MATHUTIL_H_