3 * Standard C library function wrappers.
5 * Imports are services which the device driver or window system or
6 * operating system provides to the core renderer. The core renderer (Mesa)
7 * will call these functions in order to do memory allocation, simple I/O,
10 * Some drivers will want to override/replace this file with something
11 * specialized, but that'll be rare.
13 * Eventually, I want to move roll the glheader.h file into this.
15 * \todo Functions still needed:
22 * Mesa 3-D graphics library
25 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
27 * Permission is hereby granted, free of charge, to any person obtaining a
28 * copy of this software and associated documentation files (the "Software"),
29 * to deal in the Software without restriction, including without limitation
30 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
31 * and/or sell copies of the Software, and to permit persons to whom the
32 * Software is furnished to do so, subject to the following conditions:
34 * The above copyright notice and this permission notice shall be included
35 * in all copies or substantial portions of the Software.
37 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
38 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
39 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
40 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
41 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
42 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
52 #define MAXSTRING 4000 /* for vsnprintf() */
55 #define vsnprintf _vsnprintf
56 #elif defined(__IBMC__) || defined(__IBMCPP__) || ( defined(__VMS) && __CRTL_VER < 70312000 )
57 extern int vsnprintf(char *str
, size_t count
, const char *fmt
, va_list arg
);
59 #include "vsnprintf.c"
63 /**********************************************************************/
67 /** Wrapper around malloc() */
69 _mesa_malloc(size_t bytes
)
74 /** Wrapper around calloc() */
76 _mesa_calloc(size_t bytes
)
78 return calloc(1, bytes
);
81 /** Wrapper around free() */
89 * Allocate aligned memory.
91 * \param bytes number of bytes to allocate.
92 * \param alignment alignment (must be greater than zero).
94 * Allocates extra memory to accommodate rounding up the address for
95 * alignment and to record the real malloc address.
97 * \sa _mesa_align_free().
100 _mesa_align_malloc(size_t bytes
, unsigned long alignment
)
102 #if defined(HAVE_POSIX_MEMALIGN)
105 (void) posix_memalign(& mem
, alignment
, bytes
);
107 #elif defined(_WIN32) && defined(_MSC_VER)
108 return _aligned_malloc(bytes
, alignment
);
112 ASSERT( alignment
> 0 );
114 ptr
= (uintptr_t) _mesa_malloc(bytes
+ alignment
+ sizeof(void *));
118 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
119 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
122 /* mark the non-aligned area */
123 while ( ptr
< buf
- sizeof(void *) ) {
124 *(unsigned long *)ptr
= 0xcdcdcdcd;
125 ptr
+= sizeof(unsigned long);
130 #endif /* defined(HAVE_POSIX_MEMALIGN) */
134 * Same as _mesa_align_malloc(), but using _mesa_calloc() instead of
138 _mesa_align_calloc(size_t bytes
, unsigned long alignment
)
140 #if defined(HAVE_POSIX_MEMALIGN)
143 mem
= _mesa_align_malloc(bytes
, alignment
);
145 (void) memset(mem
, 0, bytes
);
149 #elif defined(_WIN32) && defined(_MSC_VER)
152 mem
= _aligned_malloc(bytes
, alignment
);
154 (void) memset(mem
, 0, bytes
);
161 ASSERT( alignment
> 0 );
163 ptr
= (uintptr_t) _mesa_calloc(bytes
+ alignment
+ sizeof(void *));
167 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
168 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
171 /* mark the non-aligned area */
172 while ( ptr
< buf
- sizeof(void *) ) {
173 *(unsigned long *)ptr
= 0xcdcdcdcd;
174 ptr
+= sizeof(unsigned long);
179 #endif /* defined(HAVE_POSIX_MEMALIGN) */
183 * Free memory which was allocated with either _mesa_align_malloc()
184 * or _mesa_align_calloc().
185 * \param ptr pointer to the memory to be freed.
186 * The actual address to free is stored in the word immediately before the
187 * address the client sees.
190 _mesa_align_free(void *ptr
)
192 #if defined(HAVE_POSIX_MEMALIGN)
194 #elif defined(_WIN32) && defined(_MSC_VER)
197 void **cubbyHole
= (void **) ((char *) ptr
- sizeof(void *));
198 void *realAddr
= *cubbyHole
;
199 _mesa_free(realAddr
);
200 #endif /* defined(HAVE_POSIX_MEMALIGN) */
204 * Reallocate memory, with alignment.
207 _mesa_align_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
,
208 unsigned long alignment
)
210 #if defined(_WIN32) && defined(_MSC_VER)
212 return _aligned_realloc(oldBuffer
, newSize
, alignment
);
214 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
215 void *newBuf
= _mesa_align_malloc(newSize
, alignment
);
216 if (newBuf
&& oldBuffer
&& copySize
> 0) {
217 _mesa_memcpy(newBuf
, oldBuffer
, copySize
);
220 _mesa_align_free(oldBuffer
);
227 /** Reallocate memory */
229 _mesa_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
)
231 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
232 void *newBuffer
= _mesa_malloc(newSize
);
233 if (newBuffer
&& oldBuffer
&& copySize
> 0)
234 _mesa_memcpy(newBuffer
, oldBuffer
, copySize
);
236 _mesa_free(oldBuffer
);
240 /** memcpy wrapper */
242 _mesa_memcpy(void *dest
, const void *src
, size_t n
)
245 return memcpy((char *) dest
, (char *) src
, (int) n
);
247 return memcpy(dest
, src
, n
);
251 /** Wrapper around memset() */
253 _mesa_memset( void *dst
, int val
, size_t n
)
256 memset( (char *) dst
, (int) val
, (int) n
);
263 * Fill memory with a constant 16bit word.
264 * \param dst destination pointer.
266 * \param n number of words.
269 _mesa_memset16( unsigned short *dst
, unsigned short val
, size_t n
)
275 /** Wrapper around either memset() or bzero() */
277 _mesa_bzero( void *dst
, size_t n
)
279 #if defined(__FreeBSD__)
286 /** Wrapper around memcmp() */
288 _mesa_memcmp( const void *s1
, const void *s2
, size_t n
)
291 return memcmp( (char *) s1
, (char *) s2
, (int) n
);
293 return memcmp(s1
, s2
, n
);
300 /**********************************************************************/
304 /** Wrapper around sin() */
311 /** Single precision wrapper around sin() */
315 return (float) sin((double) a
);
318 /** Wrapper around cos() */
325 /** Single precision wrapper around asin() */
329 return (float) asin((double) x
);
332 /** Single precision wrapper around atan() */
336 return (float) atan((double) x
);
339 /** Wrapper around sqrt() */
341 _mesa_sqrtd(double x
)
348 * A High Speed, Low Precision Square Root
349 * by Paul Lalonde and Robert Dawson
350 * from "Graphics Gems", Academic Press, 1990
352 * SPARC implementation of a fast square root by table
354 * SPARC floating point format is as follows:
357 * sign exponent mantissa
359 static short sqrttab
[0x100]; /* declare table of square roots */
362 _mesa_init_sqrt_table(void)
364 #if defined(USE_IEEE) && !defined(DEBUG)
366 fi_type fi
; /* to access the bits of a float in C quickly */
367 /* we use a union defined in glheader.h */
369 for(i
=0; i
<= 0x7f; i
++) {
373 * Build a float with the bit pattern i as mantissa
374 * and an exponent of 0, stored as 127
377 fi
.i
= (i
<< 16) | (127 << 23);
378 fi
.f
= _mesa_sqrtd(fi
.f
);
381 * Take the square root then strip the first 7 bits of
382 * the mantissa into the table
385 sqrttab
[i
] = (fi
.i
& 0x7fffff) >> 16;
388 * Repeat the process, this time with an exponent of
393 fi
.i
= (i
<< 16) | (128 << 23);
395 sqrttab
[i
+0x80] = (fi
.i
& 0x7fffff) >> 16;
398 (void) sqrttab
; /* silence compiler warnings */
399 #endif /*HAVE_FAST_MATH*/
404 * Single precision square root.
407 _mesa_sqrtf( float x
)
409 #if defined(USE_IEEE) && !defined(DEBUG)
411 /* to access the bits of a float in C
412 * we use a union from glheader.h */
414 short e
; /* the exponent */
415 if (x
== 0.0F
) return 0.0F
; /* check for square root of 0 */
417 e
= (num
.i
>> 23) - 127; /* get the exponent - on a SPARC the */
418 /* exponent is stored with 127 added */
419 num
.i
&= 0x7fffff; /* leave only the mantissa */
420 if (e
& 0x01) num
.i
|= 0x800000;
421 /* the exponent is odd so we have to */
422 /* look it up in the second half of */
423 /* the lookup table, so we set the */
425 e
>>= 1; /* divide the exponent by two */
426 /* note that in C the shift */
427 /* operators are sign preserving */
428 /* for signed operands */
429 /* Do the table lookup, based on the quaternary mantissa,
430 * then reconstruct the result back into a float
432 num
.i
= ((sqrttab
[num
.i
>> 16]) << 16) | ((e
+ 127) << 23);
436 return (float) _mesa_sqrtd((double) x
);
442 inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
443 written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
447 _mesa_inv_sqrtf(float n
)
449 #if defined(USE_IEEE) && !defined(DEBUG)
453 #if 0 /* not used, see below -BP */
456 union { float f
; unsigned int i
; } u
;
460 Exponent part of the magic number -
463 1. subtract the bias from the exponent,
465 3. divide by two (rounding towards -inf)
468 Which is the same as subtracting the exponent from 381 and dividing
471 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
477 Significand part of magic number -
479 With the current magic number, "(magic - u.i) >> 1" will give you:
481 for 1 <= u.f <= 2: 1.25 - u.f / 4
482 for 2 <= u.f <= 4: 1.00 - u.f / 8
484 This isn't a bad approximation of 1/sqrt. The maximum difference from
485 1/sqrt will be around .06. After three Newton-Raphson iterations, the
486 maximum difference is less than 4.5e-8. (Which is actually close
487 enough to make the following bias academic...)
489 To get a better approximation you can add a bias to the magic
490 number. For example, if you subtract 1/2 of the maximum difference in
491 the first approximation (.03), you will get the following function:
493 for 1 <= u.f <= 2: 1.22 - u.f / 4
494 for 2 <= u.f <= 3.76: 0.97 - u.f / 8
495 for 3.76 <= u.f <= 4: 0.72 - u.f / 16
496 (The 3.76 to 4 range is where the result is < .5.)
498 This is the closest possible initial approximation, but with a maximum
499 error of 8e-11 after three NR iterations, it is still not perfect. If
500 you subtract 0.0332281 instead of .03, the maximum error will be
501 2.5e-11 after three NR iterations, which should be about as close as
504 for 1 <= u.f <= 2: 1.2167719 - u.f / 4
505 for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
506 for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
510 magic
-= (int)(0.0332281 * (1 << 25));
513 u
.i
= (magic
- u
.i
) >> 1;
516 Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
517 allows more parallelism. From what I understand, the parallelism
518 comes at the cost of less precision, because it lets error
519 accumulate across iterations.
534 return x2
* r2
; /* we can stop here, and be conformant -BP */
543 return (float) (1.0 / sqrt(n
));
548 /** Wrapper around pow() */
550 _mesa_pow(double x
, double y
)
557 * Find the first bit set in a word.
562 #if (defined(_WIN32) && !defined(__MINGW32__) ) || defined(__IBMC__) || defined(__IBMCPP__)
563 register int bit
= 0;
565 if ((i
& 0xffff) == 0) {
569 if ((i
& 0xff) == 0) {
573 if ((i
& 0xf) == 0) {
577 while ((i
& 1) == 0) {
591 * Find position of first bit set in given value.
592 * XXX Warning: this function can only be used on 64-bit systems!
593 * \return position of least-significant bit set, starting at 1, return zero
598 _mesa_ffsll(long val
)
600 _mesa_ffsll(long long val
)
608 assert(sizeof(val
) == 8);
610 bit
= _mesa_ffs(val
);
614 bit
= _mesa_ffs(val
>> 32);
624 * Return number of bits set in given GLuint.
627 _mesa_bitcount(unsigned int n
)
630 for (bits
= 0; n
> 0; n
= n
>> 1) {
638 * Convert a 4-byte float to a 2-byte half float.
639 * Based on code from:
640 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
643 _mesa_float_to_half(float val
)
645 const int flt
= *((int *) (void *) &val
);
646 const int flt_m
= flt
& 0x7fffff;
647 const int flt_e
= (flt
>> 23) & 0xff;
648 const int flt_s
= (flt
>> 31) & 0x1;
655 /* handle special cases */
656 if ((flt_e
== 0) && (flt_m
== 0)) {
658 /* m = 0; - already set */
661 else if ((flt_e
== 0) && (flt_m
!= 0)) {
662 /* denorm -- denorm float maps to 0 half */
663 /* m = 0; - already set */
666 else if ((flt_e
== 0xff) && (flt_m
== 0)) {
668 /* m = 0; - already set */
671 else if ((flt_e
== 0xff) && (flt_m
!= 0)) {
678 const int new_exp
= flt_e
- 127;
681 /* m = 0; - already set */
684 else if (new_exp
< -14) {
685 /* this maps to a denorm */
686 unsigned int exp_val
= (unsigned int) (-14 - new_exp
); /* 2^-exp_val*/
691 "float_to_half: logical error in denorm creation!\n");
692 /* m = 0; - already set */
694 case 1: m
= 512 + (flt_m
>> 14); break;
695 case 2: m
= 256 + (flt_m
>> 15); break;
696 case 3: m
= 128 + (flt_m
>> 16); break;
697 case 4: m
= 64 + (flt_m
>> 17); break;
698 case 5: m
= 32 + (flt_m
>> 18); break;
699 case 6: m
= 16 + (flt_m
>> 19); break;
700 case 7: m
= 8 + (flt_m
>> 20); break;
701 case 8: m
= 4 + (flt_m
>> 21); break;
702 case 9: m
= 2 + (flt_m
>> 22); break;
703 case 10: m
= 1; break;
706 else if (new_exp
> 15) {
707 /* map this value to infinity */
708 /* m = 0; - already set */
718 result
= (s
<< 15) | (e
<< 10) | m
;
724 * Convert a 2-byte half float to a 4-byte float.
725 * Based on code from:
726 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
729 _mesa_half_to_float(GLhalfARB val
)
731 /* XXX could also use a 64K-entry lookup table */
732 const int m
= val
& 0x3ff;
733 const int e
= (val
>> 10) & 0x1f;
734 const int s
= (val
>> 15) & 0x1;
735 int flt_m
, flt_e
, flt_s
, flt
;
741 /* handle special cases */
742 if ((e
== 0) && (m
== 0)) {
747 else if ((e
== 0) && (m
!= 0)) {
748 /* denorm -- denorm half will fit in non-denorm single */
749 const float half_denorm
= 1.0f
/ 16384.0f
; /* 2^-14 */
750 float mantissa
= ((float) (m
)) / 1024.0f
;
751 float sign
= s
? -1.0f
: 1.0f
;
752 return sign
* mantissa
* half_denorm
;
754 else if ((e
== 31) && (m
== 0)) {
759 else if ((e
== 31) && (m
!= 0)) {
770 flt
= (flt_s
<< 31) | (flt_e
<< 23) | flt_m
;
771 result
= *((float *) (void *) &flt
);
778 /**********************************************************************/
779 /** \name Sort & Search */
783 * Wrapper for bsearch().
786 _mesa_bsearch( const void *key
, const void *base
, size_t nmemb
, size_t size
,
787 int (*compar
)(const void *, const void *) )
789 return bsearch(key
, base
, nmemb
, size
, compar
);
795 /**********************************************************************/
796 /** \name Environment vars */
800 * Wrapper for getenv().
803 _mesa_getenv( const char *var
)
815 /**********************************************************************/
819 /** Wrapper around strstr() */
821 _mesa_strstr( const char *haystack
, const char *needle
)
823 return strstr(haystack
, needle
);
826 /** Wrapper around strncat() */
828 _mesa_strncat( char *dest
, const char *src
, size_t n
)
830 return strncat(dest
, src
, n
);
833 /** Wrapper around strcpy() */
835 _mesa_strcpy( char *dest
, const char *src
)
837 return strcpy(dest
, src
);
840 /** Wrapper around strncpy() */
842 _mesa_strncpy( char *dest
, const char *src
, size_t n
)
844 return strncpy(dest
, src
, n
);
847 /** Wrapper around strlen() */
849 _mesa_strlen( const char *s
)
854 /** Wrapper around strcmp() */
856 _mesa_strcmp( const char *s1
, const char *s2
)
858 return strcmp(s1
, s2
);
861 /** Wrapper around strncmp() */
863 _mesa_strncmp( const char *s1
, const char *s2
, size_t n
)
865 return strncmp(s1
, s2
, n
);
869 * Implemented using _mesa_malloc() and _mesa_strcpy.
870 * Note that NULL is handled accordingly.
873 _mesa_strdup( const char *s
)
876 size_t l
= _mesa_strlen(s
);
877 char *s2
= (char *) _mesa_malloc(l
+ 1);
887 /** Wrapper around atoi() */
889 _mesa_atoi(const char *s
)
894 /** Wrapper around strtod() */
896 _mesa_strtod( const char *s
, char **end
)
898 return strtod(s
, end
);
904 /**********************************************************************/
908 /** Wrapper around vsprintf() */
910 _mesa_sprintf( char *str
, const char *fmt
, ... )
914 va_start( args
, fmt
);
915 r
= vsprintf( str
, fmt
, args
);
920 /** Wrapper around printf(), using vsprintf() for the formatting. */
922 _mesa_printf( const char *fmtString
, ... )
926 va_start( args
, fmtString
);
927 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
929 fprintf(stderr
,"%s", s
);
932 /** Wrapper around vsprintf() */
934 _mesa_vsprintf( char *str
, const char *fmt
, va_list args
)
936 return vsprintf( str
, fmt
, args
);
942 /**********************************************************************/
943 /** \name Diagnostics */
947 * Report a warning (a recoverable error condition) to stderr if
948 * either DEBUG is defined or the MESA_DEBUG env var is set.
950 * \param ctx GL context.
951 * \param fmtString printf() alike format string.
954 _mesa_warning( GLcontext
*ctx
, const char *fmtString
, ... )
960 va_start( args
, fmtString
);
961 (void) vsnprintf( str
, MAXSTRING
, fmtString
, args
);
964 debug
= GL_TRUE
; /* always print warning */
966 debug
= _mesa_getenv("MESA_DEBUG") ? GL_TRUE
: GL_FALSE
;
969 fprintf(stderr
, "Mesa warning: %s\n", str
);
974 * Report an internla implementation problem.
975 * Prints the message to stderr via fprintf().
977 * \param ctx GL context.
978 * \param s problem description string.
981 _mesa_problem( const GLcontext
*ctx
, const char *fmtString
, ... )
987 va_start( args
, fmtString
);
988 vsnprintf( str
, MAXSTRING
, fmtString
, args
);
991 fprintf(stderr
, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING
, str
);
992 fprintf(stderr
, "Please report at bugzilla.freedesktop.org\n");
996 * Record an OpenGL state error. These usually occur when the users
997 * passes invalid parameters to a GL function.
999 * If debugging is enabled (either at compile-time via the DEBUG macro, or
1000 * run-time via the MESA_DEBUG environment variable), report the error with
1003 * \param ctx the GL context.
1004 * \param error the error value.
1005 * \param fmtString printf() style format string, followed by optional args
1008 _mesa_error( GLcontext
*ctx
, GLenum error
, const char *fmtString
, ... )
1010 const char *debugEnv
;
1013 debugEnv
= _mesa_getenv("MESA_DEBUG");
1016 if (debugEnv
&& _mesa_strstr(debugEnv
, "silent"))
1029 char where
[MAXSTRING
];
1032 va_start( args
, fmtString
);
1033 vsnprintf( where
, MAXSTRING
, fmtString
, args
);
1038 errstr
= "GL_NO_ERROR";
1040 case GL_INVALID_VALUE
:
1041 errstr
= "GL_INVALID_VALUE";
1043 case GL_INVALID_ENUM
:
1044 errstr
= "GL_INVALID_ENUM";
1046 case GL_INVALID_OPERATION
:
1047 errstr
= "GL_INVALID_OPERATION";
1049 case GL_STACK_OVERFLOW
:
1050 errstr
= "GL_STACK_OVERFLOW";
1052 case GL_STACK_UNDERFLOW
:
1053 errstr
= "GL_STACK_UNDERFLOW";
1055 case GL_OUT_OF_MEMORY
:
1056 errstr
= "GL_OUT_OF_MEMORY";
1058 case GL_TABLE_TOO_LARGE
:
1059 errstr
= "GL_TABLE_TOO_LARGE";
1061 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT
:
1062 errstr
= "GL_INVALID_FRAMEBUFFER_OPERATION";
1068 _mesa_debug(ctx
, "User error: %s in %s\n", errstr
, where
);
1071 _mesa_record_error(ctx
, error
);
1075 * Report debug information. Print error message to stderr via fprintf().
1076 * No-op if DEBUG mode not enabled.
1078 * \param ctx GL context.
1079 * \param fmtString printf()-style format string, followed by optional args.
1082 _mesa_debug( const GLcontext
*ctx
, const char *fmtString
, ... )
1087 va_start(args
, fmtString
);
1088 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
1090 fprintf(stderr
, "Mesa: %s", s
);
1100 * Wrapper for exit().
1103 _mesa_exit( int status
)