u_math.h revision 1463c08d
1/**************************************************************************
2 *
3 * Copyright 2008 VMware, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28
29/**
30 * Math utilities and approximations for common math functions.
31 * Reduced precision is usually acceptable in shaders...
32 *
33 * "fast" is used in the names of functions which are low-precision,
34 * or at least lower-precision than the normal C lib functions.
35 */
36
37
38#ifndef U_MATH_H
39#define U_MATH_H
40
41
42#include "c99_math.h"
43#include <assert.h>
44#include <float.h>
45#include <stdarg.h>
46
47#include "bitscan.h"
48#include "u_endian.h" /* for UTIL_ARCH_BIG_ENDIAN */
49
50#ifdef __cplusplus
51extern "C" {
52#endif
53
54
55#ifndef M_SQRT2
56#define M_SQRT2 1.41421356237309504880
57#endif
58
59
60/**
61 * Initialize math module.  This should be called before using any
62 * other functions in this module.
63 */
64extern void
65util_init_math(void);
66
67
68union fi {
69   float f;
70   int32_t i;
71   uint32_t ui;
72};
73
74
75union di {
76   double d;
77   int64_t i;
78   uint64_t ui;
79};
80
81
82/**
83 * Extract the IEEE float32 exponent.
84 */
85static inline signed
86util_get_float32_exponent(float x)
87{
88   union fi f;
89
90   f.f = x;
91
92   return ((f.ui >> 23) & 0xff) - 127;
93}
94
95
96#define LOG2_TABLE_SIZE_LOG2 8
97#define LOG2_TABLE_SCALE (1 << LOG2_TABLE_SIZE_LOG2)
98#define LOG2_TABLE_SIZE (LOG2_TABLE_SCALE + 1)
99extern float log2_table[LOG2_TABLE_SIZE];
100
101
102/**
103 * Fast approximation to log2(x).
104 */
105static inline float
106util_fast_log2(float x)
107{
108   union fi num;
109   float epart, mpart;
110   num.f = x;
111   epart = (float)(((num.i & 0x7f800000) >> 23) - 127);
112   /* mpart = log2_table[mantissa*LOG2_TABLE_SCALE + 0.5] */
113   mpart = log2_table[((num.i & 0x007fffff) + (1 << (22 - LOG2_TABLE_SIZE_LOG2))) >> (23 - LOG2_TABLE_SIZE_LOG2)];
114   return epart + mpart;
115}
116
117
118/**
119 * Floor(x), returned as int.
120 */
121static inline int
122util_ifloor(float f)
123{
124#if defined(USE_X86_ASM) && defined(__GNUC__) && defined(__i386__)
125   /*
126    * IEEE floor for computers that round to nearest or even.
127    * 'f' must be between -4194304 and 4194303.
128    * This floor operation is done by "(iround(f + .5) + iround(f - .5)) >> 1",
129    * but uses some IEEE specific tricks for better speed.
130    * Contributed by Josh Vanderhoof
131    */
132   int ai, bi;
133   double af, bf;
134   af = (3 << 22) + 0.5 + (double)f;
135   bf = (3 << 22) + 0.5 - (double)f;
136   /* GCC generates an extra fstp/fld without this. */
137   __asm__ ("fstps %0" : "=m" (ai) : "t" (af) : "st");
138   __asm__ ("fstps %0" : "=m" (bi) : "t" (bf) : "st");
139   return (ai - bi) >> 1;
140#else
141   int ai, bi;
142   double af, bf;
143   union fi u;
144   af = (3 << 22) + 0.5 + (double) f;
145   bf = (3 << 22) + 0.5 - (double) f;
146   u.f = (float) af;  ai = u.i;
147   u.f = (float) bf;  bi = u.i;
148   return (ai - bi) >> 1;
149#endif
150}
151
152
153/**
154 * Round float to nearest int.
155 */
156static inline int
157util_iround(float f)
158{
159#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
160   int r;
161   __asm__ ("fistpl %0" : "=m" (r) : "t" (f) : "st");
162   return r;
163#elif defined(PIPE_CC_MSVC) && defined(PIPE_ARCH_X86)
164   int r;
165   _asm {
166      fld f
167      fistp r
168   }
169   return r;
170#else
171   if (f >= 0.0f)
172      return (int) (f + 0.5f);
173   else
174      return (int) (f - 0.5f);
175#endif
176}
177
178
179/**
180 * Approximate floating point comparison
181 */
182static inline bool
183util_is_approx(float a, float b, float tol)
184{
185   return fabsf(b - a) <= tol;
186}
187
188
189/**
190 * util_is_X_inf_or_nan = test if x is NaN or +/- Inf
191 * util_is_X_nan        = test if x is NaN
192 * util_X_inf_sign      = return +1 for +Inf, -1 for -Inf, or 0 for not Inf
193 *
194 * NaN can be checked with x != x, however this fails with the fast math flag
195 **/
196
197
198/**
199 * Single-float
200 */
201static inline bool
202util_is_inf_or_nan(float x)
203{
204   union fi tmp;
205   tmp.f = x;
206   return (tmp.ui & 0x7f800000) == 0x7f800000;
207}
208
209
210static inline bool
211util_is_nan(float x)
212{
213   union fi tmp;
214   tmp.f = x;
215   return (tmp.ui & 0x7fffffff) > 0x7f800000;
216}
217
218
219static inline int
220util_inf_sign(float x)
221{
222   union fi tmp;
223   tmp.f = x;
224   if ((tmp.ui & 0x7fffffff) != 0x7f800000) {
225      return 0;
226   }
227
228   return (x < 0) ? -1 : 1;
229}
230
231
232/**
233 * Double-float
234 */
235static inline bool
236util_is_double_inf_or_nan(double x)
237{
238   union di tmp;
239   tmp.d = x;
240   return (tmp.ui & 0x7ff0000000000000ULL) == 0x7ff0000000000000ULL;
241}
242
243
244static inline bool
245util_is_double_nan(double x)
246{
247   union di tmp;
248   tmp.d = x;
249   return (tmp.ui & 0x7fffffffffffffffULL) > 0x7ff0000000000000ULL;
250}
251
252
253static inline int
254util_double_inf_sign(double x)
255{
256   union di tmp;
257   tmp.d = x;
258   if ((tmp.ui & 0x7fffffffffffffffULL) != 0x7ff0000000000000ULL) {
259      return 0;
260   }
261
262   return (x < 0) ? -1 : 1;
263}
264
265
266/**
267 * Half-float
268 */
269static inline bool
270util_is_half_inf_or_nan(int16_t x)
271{
272   return (x & 0x7c00) == 0x7c00;
273}
274
275
276static inline bool
277util_is_half_nan(int16_t x)
278{
279   return (x & 0x7fff) > 0x7c00;
280}
281
282
283static inline int
284util_half_inf_sign(int16_t x)
285{
286   if ((x & 0x7fff) != 0x7c00) {
287      return 0;
288   }
289
290   return (x < 0) ? -1 : 1;
291}
292
293
294/**
295 * Return float bits.
296 */
297static inline unsigned
298fui( float f )
299{
300   union fi fi;
301   fi.f = f;
302   return fi.ui;
303}
304
305static inline float
306uif(uint32_t ui)
307{
308   union fi fi;
309   fi.ui = ui;
310   return fi.f;
311}
312
313
314/**
315 * Convert uint8_t to float in [0, 1].
316 */
317static inline float
318ubyte_to_float(uint8_t ub)
319{
320   return (float) ub * (1.0f / 255.0f);
321}
322
323
324/**
325 * Convert float in [0,1] to uint8_t in [0,255] with clamping.
326 */
327static inline uint8_t
328float_to_ubyte(float f)
329{
330   /* return 0 for NaN too */
331   if (!(f > 0.0f)) {
332      return (uint8_t) 0;
333   }
334   else if (f >= 1.0f) {
335      return (uint8_t) 255;
336   }
337   else {
338      union fi tmp;
339      tmp.f = f;
340      tmp.f = tmp.f * (255.0f/256.0f) + 32768.0f;
341      return (uint8_t) tmp.i;
342   }
343}
344
345/**
346 * Convert uint16_t to float in [0, 1].
347 */
348static inline float
349ushort_to_float(uint16_t us)
350{
351   return (float) us * (1.0f / 65535.0f);
352}
353
354
355/**
356 * Convert float in [0,1] to uint16_t in [0,65535] with clamping.
357 */
358static inline uint16_t
359float_to_ushort(float f)
360{
361   /* return 0 for NaN too */
362   if (!(f > 0.0f)) {
363      return (uint16_t) 0;
364   }
365   else if (f >= 1.0f) {
366      return (uint16_t) 65535;
367   }
368   else {
369      union fi tmp;
370      tmp.f = f;
371      tmp.f = tmp.f * (65535.0f/65536.0f) + 128.0f;
372      return (uint16_t) tmp.i;
373   }
374}
375
376static inline float
377byte_to_float_tex(int8_t b)
378{
379   return (b == -128) ? -1.0F : b * 1.0F / 127.0F;
380}
381
382static inline int8_t
383float_to_byte_tex(float f)
384{
385   return (int8_t) (127.0F * f);
386}
387
388/**
389 * Calc log base 2
390 */
391static inline unsigned
392util_logbase2(unsigned n)
393{
394#if defined(HAVE___BUILTIN_CLZ)
395   return ((sizeof(unsigned) * 8 - 1) - __builtin_clz(n | 1));
396#else
397   unsigned pos = 0;
398   if (n >= 1<<16) { n >>= 16; pos += 16; }
399   if (n >= 1<< 8) { n >>=  8; pos +=  8; }
400   if (n >= 1<< 4) { n >>=  4; pos +=  4; }
401   if (n >= 1<< 2) { n >>=  2; pos +=  2; }
402   if (n >= 1<< 1) {           pos +=  1; }
403   return pos;
404#endif
405}
406
407static inline uint64_t
408util_logbase2_64(uint64_t n)
409{
410#if defined(HAVE___BUILTIN_CLZLL)
411   return ((sizeof(uint64_t) * 8 - 1) - __builtin_clzll(n | 1));
412#else
413   uint64_t pos = 0ull;
414   if (n >= 1ull<<32) { n >>= 32; pos += 32; }
415   if (n >= 1ull<<16) { n >>= 16; pos += 16; }
416   if (n >= 1ull<< 8) { n >>=  8; pos +=  8; }
417   if (n >= 1ull<< 4) { n >>=  4; pos +=  4; }
418   if (n >= 1ull<< 2) { n >>=  2; pos +=  2; }
419   if (n >= 1ull<< 1) {           pos +=  1; }
420   return pos;
421#endif
422}
423
424/**
425 * Returns the ceiling of log n base 2, and 0 when n == 0. Equivalently,
426 * returns the smallest x such that n <= 2**x.
427 */
428static inline unsigned
429util_logbase2_ceil(unsigned n)
430{
431   if (n <= 1)
432      return 0;
433
434   return 1 + util_logbase2(n - 1);
435}
436
437static inline uint64_t
438util_logbase2_ceil64(uint64_t n)
439{
440   if (n <= 1)
441      return 0;
442
443   return 1ull + util_logbase2_64(n - 1);
444}
445
446/**
447 * Returns the smallest power of two >= x
448 */
449static inline unsigned
450util_next_power_of_two(unsigned x)
451{
452#if defined(HAVE___BUILTIN_CLZ)
453   if (x <= 1)
454       return 1;
455
456   return (1 << ((sizeof(unsigned) * 8) - __builtin_clz(x - 1)));
457#else
458   unsigned val = x;
459
460   if (x <= 1)
461      return 1;
462
463   if (util_is_power_of_two_or_zero(x))
464      return x;
465
466   val--;
467   val = (val >> 1) | val;
468   val = (val >> 2) | val;
469   val = (val >> 4) | val;
470   val = (val >> 8) | val;
471   val = (val >> 16) | val;
472   val++;
473   return val;
474#endif
475}
476
477static inline uint64_t
478util_next_power_of_two64(uint64_t x)
479{
480#if defined(HAVE___BUILTIN_CLZLL)
481   if (x <= 1)
482       return 1;
483
484   return (1ull << ((sizeof(uint64_t) * 8) - __builtin_clzll(x - 1)));
485#else
486   uint64_t val = x;
487
488   if (x <= 1)
489      return 1;
490
491   if (util_is_power_of_two_or_zero64(x))
492      return x;
493
494   val--;
495   val = (val >> 1)  | val;
496   val = (val >> 2)  | val;
497   val = (val >> 4)  | val;
498   val = (val >> 8)  | val;
499   val = (val >> 16) | val;
500   val = (val >> 32) | val;
501   val++;
502   return val;
503#endif
504}
505
506/**
507 * Reverse bits in n
508 * Algorithm taken from:
509 * http://stackoverflow.com/questions/9144800/c-reverse-bits-in-unsigned-integer
510 */
511static inline unsigned
512util_bitreverse(unsigned n)
513{
514    n = ((n >> 1) & 0x55555555u) | ((n & 0x55555555u) << 1);
515    n = ((n >> 2) & 0x33333333u) | ((n & 0x33333333u) << 2);
516    n = ((n >> 4) & 0x0f0f0f0fu) | ((n & 0x0f0f0f0fu) << 4);
517    n = ((n >> 8) & 0x00ff00ffu) | ((n & 0x00ff00ffu) << 8);
518    n = ((n >> 16) & 0xffffu) | ((n & 0xffffu) << 16);
519    return n;
520}
521
522/**
523 * Convert from little endian to CPU byte order.
524 */
525
526#if UTIL_ARCH_BIG_ENDIAN
527#define util_le64_to_cpu(x) util_bswap64(x)
528#define util_le32_to_cpu(x) util_bswap32(x)
529#define util_le16_to_cpu(x) util_bswap16(x)
530#else
531#define util_le64_to_cpu(x) (x)
532#define util_le32_to_cpu(x) (x)
533#define util_le16_to_cpu(x) (x)
534#endif
535
536#define util_cpu_to_le64(x) util_le64_to_cpu(x)
537#define util_cpu_to_le32(x) util_le32_to_cpu(x)
538#define util_cpu_to_le16(x) util_le16_to_cpu(x)
539
540/**
541 * Reverse byte order of a 32 bit word.
542 */
543static inline uint32_t
544util_bswap32(uint32_t n)
545{
546#if defined(HAVE___BUILTIN_BSWAP32)
547   return __builtin_bswap32(n);
548#else
549   return (n >> 24) |
550          ((n >> 8) & 0x0000ff00) |
551          ((n << 8) & 0x00ff0000) |
552          (n << 24);
553#endif
554}
555
556/**
557 * Reverse byte order of a 64bit word.
558 */
559static inline uint64_t
560util_bswap64(uint64_t n)
561{
562#if defined(HAVE___BUILTIN_BSWAP64)
563   return __builtin_bswap64(n);
564#else
565   return ((uint64_t)util_bswap32((uint32_t)n) << 32) |
566          util_bswap32((n >> 32));
567#endif
568}
569
570
571/**
572 * Reverse byte order of a 16 bit word.
573 */
574static inline uint16_t
575util_bswap16(uint16_t n)
576{
577   return (n >> 8) |
578          (n << 8);
579}
580
581/**
582 * Extend sign.
583 */
584static inline int64_t
585util_sign_extend(uint64_t val, unsigned width)
586{
587	assert(width > 0);
588	if (val & (UINT64_C(1) << (width - 1))) {
589		return -(int64_t)((UINT64_C(1) << width) - val);
590	} else {
591		return val;
592	}
593}
594
595static inline void*
596util_memcpy_cpu_to_le32(void * restrict dest, const void * restrict src, size_t n)
597{
598#if UTIL_ARCH_BIG_ENDIAN
599   size_t i, e;
600   assert(n % 4 == 0);
601
602   for (i = 0, e = n / 4; i < e; i++) {
603      uint32_t * restrict d = (uint32_t* restrict)dest;
604      const uint32_t * restrict s = (const uint32_t* restrict)src;
605      d[i] = util_bswap32(s[i]);
606   }
607   return dest;
608#else
609   return memcpy(dest, src, n);
610#endif
611}
612
613/**
614 * Clamp X to [MIN, MAX].
615 * This is a macro to allow float, int, uint, etc. types.
616 * We arbitrarily turn NaN into MIN.
617 */
618#define CLAMP( X, MIN, MAX )  ( (X)>(MIN) ? ((X)>(MAX) ? (MAX) : (X)) : (MIN) )
619
620/* Syntax sugar occuring frequently in graphics code */
621#define SATURATE( X ) CLAMP(X, 0.0f, 1.0f)
622
623#define MIN2( A, B )   ( (A)<(B) ? (A) : (B) )
624#define MAX2( A, B )   ( (A)>(B) ? (A) : (B) )
625
626#define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C))
627#define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C))
628
629#define MIN4( A, B, C, D ) ((A) < (B) ? MIN3(A, C, D) : MIN3(B, C, D))
630#define MAX4( A, B, C, D ) ((A) > (B) ? MAX3(A, C, D) : MAX3(B, C, D))
631
632
633/**
634 * Align a value up to an alignment value
635 *
636 * If \c value is not already aligned to the requested alignment value, it
637 * will be rounded up.
638 *
639 * \param value  Value to be rounded
640 * \param alignment  Alignment value to be used.  This must be a power of two.
641 *
642 * \sa ROUND_DOWN_TO()
643 */
644
645#if defined(ALIGN)
646#undef ALIGN
647#endif
648static inline uintptr_t
649ALIGN(uintptr_t value, int32_t alignment)
650{
651   assert(util_is_power_of_two_nonzero(alignment));
652   return (((value) + (alignment) - 1) & ~((alignment) - 1));
653}
654
655/**
656 * Like ALIGN(), but works with a non-power-of-two alignment.
657 */
658static inline uintptr_t
659ALIGN_NPOT(uintptr_t value, int32_t alignment)
660{
661   assert(alignment > 0);
662   return (value + alignment - 1) / alignment * alignment;
663}
664
665/**
666 * Align a value down to an alignment value
667 *
668 * If \c value is not already aligned to the requested alignment value, it
669 * will be rounded down.
670 *
671 * \param value  Value to be rounded
672 * \param alignment  Alignment value to be used.  This must be a power of two.
673 *
674 * \sa ALIGN()
675 */
676static inline uint64_t
677ROUND_DOWN_TO(uint64_t value, int32_t alignment)
678{
679   assert(util_is_power_of_two_nonzero(alignment));
680   return ((value) & ~(alignment - 1));
681}
682
683/**
684 * Align a value, only works pot alignemnts.
685 */
686static inline int
687align(int value, int alignment)
688{
689   return (value + alignment - 1) & ~(alignment - 1);
690}
691
692static inline uint64_t
693align64(uint64_t value, unsigned alignment)
694{
695   return (value + alignment - 1) & ~((uint64_t)alignment - 1);
696}
697
698/**
699 * Works like align but on npot alignments.
700 */
701static inline size_t
702util_align_npot(size_t value, size_t alignment)
703{
704   if (value % alignment)
705      return value + (alignment - (value % alignment));
706   return value;
707}
708
709static inline unsigned
710u_minify(unsigned value, unsigned levels)
711{
712    return MAX2(1, value >> levels);
713}
714
715#ifndef COPY_4V
716#define COPY_4V( DST, SRC )         \
717do {                                \
718   (DST)[0] = (SRC)[0];             \
719   (DST)[1] = (SRC)[1];             \
720   (DST)[2] = (SRC)[2];             \
721   (DST)[3] = (SRC)[3];             \
722} while (0)
723#endif
724
725
726#ifndef COPY_4FV
727#define COPY_4FV( DST, SRC )  COPY_4V(DST, SRC)
728#endif
729
730
731#ifndef ASSIGN_4V
732#define ASSIGN_4V( DST, V0, V1, V2, V3 ) \
733do {                                     \
734   (DST)[0] = (V0);                      \
735   (DST)[1] = (V1);                      \
736   (DST)[2] = (V2);                      \
737   (DST)[3] = (V3);                      \
738} while (0)
739#endif
740
741
742static inline uint32_t
743util_unsigned_fixed(float value, unsigned frac_bits)
744{
745   return value < 0 ? 0 : (uint32_t)(value * (1<<frac_bits));
746}
747
748static inline int32_t
749util_signed_fixed(float value, unsigned frac_bits)
750{
751   return (int32_t)(value * (1<<frac_bits));
752}
753
754unsigned
755util_fpstate_get(void);
756unsigned
757util_fpstate_set_denorms_to_zero(unsigned current_fpstate);
758void
759util_fpstate_set(unsigned fpstate);
760
761/**
762 * For indexed draw calls, return true if the vertex count to be drawn is
763 * much lower than the vertex count that has to be uploaded, meaning
764 * that the driver should flatten indices instead of trying to upload
765 * a too big range.
766 *
767 * This is used by vertex upload code in u_vbuf and glthread.
768 */
769static inline bool
770util_is_vbo_upload_ratio_too_large(unsigned draw_vertex_count,
771                                   unsigned upload_vertex_count)
772{
773   if (draw_vertex_count > 1024)
774      return upload_vertex_count > draw_vertex_count * 4;
775   else if (draw_vertex_count > 32)
776      return upload_vertex_count > draw_vertex_count * 8;
777   else
778      return upload_vertex_count > draw_vertex_count * 16;
779}
780
781bool util_invert_mat4x4(float *out, const float *m);
782
783/* Quantize the lod bias value to reduce the number of sampler state
784 * variants in gallium because apps use it for smooth mipmap transitions,
785 * thrashing cso_cache and degrading performance.
786 *
787 * This quantization matches the AMD hw specification, so having more
788 * precision would have no effect anyway.
789 */
790static inline float
791util_quantize_lod_bias(float lod)
792{
793   lod = CLAMP(lod, -16, 16);
794   return roundf(lod * 256) / 256;
795}
796
797#ifdef __cplusplus
798}
799#endif
800
801#endif /* U_MATH_H */
802