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 * The OpenGL SI's __GLimports structure allows per-context specification of
16 * replacements for the standard C lib functions. In practice that's probably
17 * never needed; compile-time replacements are far more likely.
19 * The _mesa_*() functions defined here don't in general take a context
20 * parameter. I guess we can change that someday, if need be.
21 * So for now, the __GLimports stuff really isn't used.
23 * \todo Functions still needed:
30 * Mesa 3-D graphics library
33 * Copyright (C) 1999-2006 Brian Paul All Rights Reserved.
35 * Permission is hereby granted, free of charge, to any person obtaining a
36 * copy of this software and associated documentation files (the "Software"),
37 * to deal in the Software without restriction, including without limitation
38 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
39 * and/or sell copies of the Software, and to permit persons to whom the
40 * Software is furnished to do so, subject to the following conditions:
42 * The above copyright notice and this permission notice shall be included
43 * in all copies or substantial portions of the Software.
45 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
46 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
48 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
49 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
50 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
60 #define MAXSTRING 4000 /* for vsnprintf() */
63 #define vsnprintf _vsnprintf
64 #elif defined(__IBMC__) || defined(__IBMCPP__) || ( defined(__VMS) && __CRTL_VER < 70312000 )
65 extern int vsnprintf(char *str
, size_t count
, const char *fmt
, va_list arg
);
67 #include "vsnprintf.c"
71 /**********************************************************************/
75 /** Wrapper around malloc() */
77 _mesa_malloc(size_t bytes
)
82 /** Wrapper around calloc() */
84 _mesa_calloc(size_t bytes
)
86 return calloc(1, bytes
);
89 /** Wrapper around free() */
97 * Allocate aligned memory.
99 * \param bytes number of bytes to allocate.
100 * \param alignment alignment (must be greater than zero).
102 * Allocates extra memory to accommodate rounding up the address for
103 * alignment and to record the real malloc address.
105 * \sa _mesa_align_free().
108 _mesa_align_malloc(size_t bytes
, unsigned long alignment
)
110 #if defined(HAVE_POSIX_MEMALIGN)
113 (void) posix_memalign(& mem
, alignment
, bytes
);
118 ASSERT( alignment
> 0 );
120 ptr
= (uintptr_t) _mesa_malloc(bytes
+ alignment
+ sizeof(void *));
124 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
125 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
128 /* mark the non-aligned area */
129 while ( ptr
< buf
- sizeof(void *) ) {
130 *(unsigned long *)ptr
= 0xcdcdcdcd;
131 ptr
+= sizeof(unsigned long);
136 #endif /* defined(HAVE_POSIX_MEMALIGN) */
140 * Same as _mesa_align_malloc(), but using _mesa_calloc() instead of
144 _mesa_align_calloc(size_t bytes
, unsigned long alignment
)
146 #if defined(HAVE_POSIX_MEMALIGN)
149 mem
= _mesa_align_malloc(bytes
, alignment
);
151 (void) memset(mem
, 0, bytes
);
158 ASSERT( alignment
> 0 );
160 ptr
= (uintptr_t) _mesa_calloc(bytes
+ alignment
+ sizeof(void *));
164 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
165 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
168 /* mark the non-aligned area */
169 while ( ptr
< buf
- sizeof(void *) ) {
170 *(unsigned long *)ptr
= 0xcdcdcdcd;
171 ptr
+= sizeof(unsigned long);
176 #endif /* defined(HAVE_POSIX_MEMALIGN) */
180 * Free memory which was allocated with either _mesa_align_malloc()
181 * or _mesa_align_calloc().
182 * \param ptr pointer to the memory to be freed.
183 * The actual address to free is stored in the word immediately before the
184 * address the client sees.
187 _mesa_align_free(void *ptr
)
189 #if defined(HAVE_POSIX_MEMALIGN)
192 void **cubbyHole
= (void **) ((char *) ptr
- sizeof(void *));
193 void *realAddr
= *cubbyHole
;
194 _mesa_free(realAddr
);
195 #endif /* defined(HAVE_POSIX_MEMALIGN) */
199 * Reallocate memory, with alignment.
202 _mesa_align_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
,
203 unsigned long alignment
)
205 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
206 void *newBuf
= _mesa_align_malloc(newSize
, alignment
);
207 if (newBuf
&& oldBuffer
&& copySize
> 0) {
208 _mesa_memcpy(newBuf
, oldBuffer
, copySize
);
211 _mesa_align_free(oldBuffer
);
217 /** Reallocate memory */
219 _mesa_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
)
221 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
222 void *newBuffer
= _mesa_malloc(newSize
);
223 if (newBuffer
&& oldBuffer
&& copySize
> 0)
224 _mesa_memcpy(newBuffer
, oldBuffer
, copySize
);
226 _mesa_free(oldBuffer
);
230 /** memcpy wrapper */
232 _mesa_memcpy(void *dest
, const void *src
, size_t n
)
235 return memcpy((char *) dest
, (char *) src
, (int) n
);
237 return memcpy(dest
, src
, n
);
241 /** Wrapper around memset() */
243 _mesa_memset( void *dst
, int val
, size_t n
)
246 memset( (char *) dst
, (int) val
, (int) n
);
253 * Fill memory with a constant 16bit word.
254 * \param dst destination pointer.
256 * \param n number of words.
259 _mesa_memset16( unsigned short *dst
, unsigned short val
, size_t n
)
265 /** Wrapper around either memcpy() or bzero() */
267 _mesa_bzero( void *dst
, size_t n
)
269 #if defined(__FreeBSD__)
276 /** Wrapper around memcmp() */
278 _mesa_memcmp( const void *s1
, const void *s2
, size_t n
)
281 return memcmp( (char *) s1
, (char *) s2
, (int) n
);
283 return memcmp(s1
, s2
, n
);
290 /**********************************************************************/
294 /** Wrapper around sin() */
301 /** Single precision wrapper around sin() */
305 return (float) sin((double) a
);
308 /** Wrapper around cos() */
315 /** Single precision wrapper around asin() */
319 return (float) asin((double) x
);
322 /** Single precision wrapper around atan() */
326 return (float) atan((double) x
);
329 /** Wrapper around sqrt() */
331 _mesa_sqrtd(double x
)
338 * A High Speed, Low Precision Square Root
339 * by Paul Lalonde and Robert Dawson
340 * from "Graphics Gems", Academic Press, 1990
342 * SPARC implementation of a fast square root by table
344 * SPARC floating point format is as follows:
347 * sign exponent mantissa
349 static short sqrttab
[0x100]; /* declare table of square roots */
352 _mesa_init_sqrt_table(void)
354 #if defined(USE_IEEE) && !defined(DEBUG)
356 fi_type fi
; /* to access the bits of a float in C quickly */
357 /* we use a union defined in glheader.h */
359 for(i
=0; i
<= 0x7f; i
++) {
363 * Build a float with the bit pattern i as mantissa
364 * and an exponent of 0, stored as 127
367 fi
.i
= (i
<< 16) | (127 << 23);
368 fi
.f
= _mesa_sqrtd(fi
.f
);
371 * Take the square root then strip the first 7 bits of
372 * the mantissa into the table
375 sqrttab
[i
] = (fi
.i
& 0x7fffff) >> 16;
378 * Repeat the process, this time with an exponent of
383 fi
.i
= (i
<< 16) | (128 << 23);
385 sqrttab
[i
+0x80] = (fi
.i
& 0x7fffff) >> 16;
388 (void) sqrttab
; /* silence compiler warnings */
389 #endif /*HAVE_FAST_MATH*/
394 * Single precision square root.
397 _mesa_sqrtf( float x
)
399 #if defined(USE_IEEE) && !defined(DEBUG)
401 /* to access the bits of a float in C
402 * we use a union from glheader.h */
404 short e
; /* the exponent */
405 if (x
== 0.0F
) return 0.0F
; /* check for square root of 0 */
407 e
= (num
.i
>> 23) - 127; /* get the exponent - on a SPARC the */
408 /* exponent is stored with 127 added */
409 num
.i
&= 0x7fffff; /* leave only the mantissa */
410 if (e
& 0x01) num
.i
|= 0x800000;
411 /* the exponent is odd so we have to */
412 /* look it up in the second half of */
413 /* the lookup table, so we set the */
415 e
>>= 1; /* divide the exponent by two */
416 /* note that in C the shift */
417 /* operators are sign preserving */
418 /* for signed operands */
419 /* Do the table lookup, based on the quaternary mantissa,
420 * then reconstruct the result back into a float
422 num
.i
= ((sqrttab
[num
.i
>> 16]) << 16) | ((e
+ 127) << 23);
426 return (float) _mesa_sqrtd((double) x
);
432 inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
433 written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
437 _mesa_inv_sqrtf(float n
)
439 #if defined(USE_IEEE) && !defined(DEBUG)
443 #if 0 /* not used, see below -BP */
446 union { float f
; unsigned int i
; } u
;
450 Exponent part of the magic number -
453 1. subtract the bias from the exponent,
455 3. divide by two (rounding towards -inf)
458 Which is the same as subtracting the exponent from 381 and dividing
461 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
467 Significand part of magic number -
469 With the current magic number, "(magic - u.i) >> 1" will give you:
471 for 1 <= u.f <= 2: 1.25 - u.f / 4
472 for 2 <= u.f <= 4: 1.00 - u.f / 8
474 This isn't a bad approximation of 1/sqrt. The maximum difference from
475 1/sqrt will be around .06. After three Newton-Raphson iterations, the
476 maximum difference is less than 4.5e-8. (Which is actually close
477 enough to make the following bias academic...)
479 To get a better approximation you can add a bias to the magic
480 number. For example, if you subtract 1/2 of the maximum difference in
481 the first approximation (.03), you will get the following function:
483 for 1 <= u.f <= 2: 1.22 - u.f / 4
484 for 2 <= u.f <= 3.76: 0.97 - u.f / 8
485 for 3.76 <= u.f <= 4: 0.72 - u.f / 16
486 (The 3.76 to 4 range is where the result is < .5.)
488 This is the closest possible initial approximation, but with a maximum
489 error of 8e-11 after three NR iterations, it is still not perfect. If
490 you subtract 0.0332281 instead of .03, the maximum error will be
491 2.5e-11 after three NR iterations, which should be about as close as
494 for 1 <= u.f <= 2: 1.2167719 - u.f / 4
495 for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
496 for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
500 magic
-= (int)(0.0332281 * (1 << 25));
503 u
.i
= (magic
- u
.i
) >> 1;
506 Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
507 allows more parallelism. From what I understand, the parallelism
508 comes at the cost of less precision, because it lets error
509 accumulate across iterations.
524 return x2
* r2
; /* we can stop here, and be conformant -BP */
533 return (float) (1.0 / sqrt(n
));
538 /** Wrapper around pow() */
540 _mesa_pow(double x
, double y
)
547 * Find the first bit set in a word.
552 #if (defined(_WIN32) && !defined(__MINGW32__) ) || defined(__IBMC__) || defined(__IBMCPP__)
553 register int bit
= 0;
555 if ((i
& 0xffff) == 0) {
559 if ((i
& 0xff) == 0) {
563 if ((i
& 0xf) == 0) {
567 while ((i
& 1) == 0) {
580 * Find position of first bit set in given value.
581 * XXX Warning: this function can only be used on 64-bit systems!
582 * \return position of least-significant bit set, starting at 1, return zero
586 _mesa_ffsll(long long val
)
593 assert(sizeof(val
) == 8);
599 bit
= ffs(val
>> 32);
609 * Return number of bits set in given GLuint.
612 _mesa_bitcount(unsigned int n
)
615 for (bits
= 0; n
> 0; n
= n
>> 1) {
623 * Convert a 4-byte float to a 2-byte half float.
624 * Based on code from:
625 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
628 _mesa_float_to_half(float val
)
630 const int flt
= *((int *) (void *) &val
);
631 const int flt_m
= flt
& 0x7fffff;
632 const int flt_e
= (flt
>> 23) & 0xff;
633 const int flt_s
= (flt
>> 31) & 0x1;
640 /* handle special cases */
641 if ((flt_e
== 0) && (flt_m
== 0)) {
643 /* m = 0; - already set */
646 else if ((flt_e
== 0) && (flt_m
!= 0)) {
647 /* denorm -- denorm float maps to 0 half */
648 /* m = 0; - already set */
651 else if ((flt_e
== 0xff) && (flt_m
== 0)) {
653 /* m = 0; - already set */
656 else if ((flt_e
== 0xff) && (flt_m
!= 0)) {
663 const int new_exp
= flt_e
- 127;
666 /* m = 0; - already set */
669 else if (new_exp
< -14) {
670 /* this maps to a denorm */
671 unsigned int exp_val
= (unsigned int) (-14 - new_exp
); /* 2^-exp_val*/
676 "float_to_half: logical error in denorm creation!\n");
677 /* m = 0; - already set */
679 case 1: m
= 512 + (flt_m
>> 14); break;
680 case 2: m
= 256 + (flt_m
>> 15); break;
681 case 3: m
= 128 + (flt_m
>> 16); break;
682 case 4: m
= 64 + (flt_m
>> 17); break;
683 case 5: m
= 32 + (flt_m
>> 18); break;
684 case 6: m
= 16 + (flt_m
>> 19); break;
685 case 7: m
= 8 + (flt_m
>> 20); break;
686 case 8: m
= 4 + (flt_m
>> 21); break;
687 case 9: m
= 2 + (flt_m
>> 22); break;
688 case 10: m
= 1; break;
691 else if (new_exp
> 15) {
692 /* map this value to infinity */
693 /* m = 0; - already set */
703 result
= (s
<< 15) | (e
<< 10) | m
;
709 * Convert a 2-byte half float to a 4-byte float.
710 * Based on code from:
711 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
714 _mesa_half_to_float(GLhalfARB val
)
716 /* XXX could also use a 64K-entry lookup table */
717 const int m
= val
& 0x3ff;
718 const int e
= (val
>> 10) & 0x1f;
719 const int s
= (val
>> 15) & 0x1;
720 int flt_m
, flt_e
, flt_s
, flt
;
726 /* handle special cases */
727 if ((e
== 0) && (m
== 0)) {
732 else if ((e
== 0) && (m
!= 0)) {
733 /* denorm -- denorm half will fit in non-denorm single */
734 const float half_denorm
= 1.0f
/ 16384.0f
; /* 2^-14 */
735 float mantissa
= ((float) (m
)) / 1024.0f
;
736 float sign
= s
? -1.0f
: 1.0f
;
737 return sign
* mantissa
* half_denorm
;
739 else if ((e
== 31) && (m
== 0)) {
744 else if ((e
== 31) && (m
!= 0)) {
755 flt
= (flt_s
<< 31) | (flt_e
<< 23) | flt_m
;
756 result
= *((float *) (void *) &flt
);
763 /**********************************************************************/
764 /** \name Sort & Search */
768 * Wrapper for bsearch().
771 _mesa_bsearch( const void *key
, const void *base
, size_t nmemb
, size_t size
,
772 int (*compar
)(const void *, const void *) )
774 return bsearch(key
, base
, nmemb
, size
, compar
);
780 /**********************************************************************/
781 /** \name Environment vars */
785 * Wrapper for getenv().
788 _mesa_getenv( const char *var
)
800 /**********************************************************************/
804 /** Wrapper around strstr() */
806 _mesa_strstr( const char *haystack
, const char *needle
)
808 return strstr(haystack
, needle
);
811 /** Wrapper around strncat() */
813 _mesa_strncat( char *dest
, const char *src
, size_t n
)
815 return strncat(dest
, src
, n
);
818 /** Wrapper around strcpy() */
820 _mesa_strcpy( char *dest
, const char *src
)
822 return strcpy(dest
, src
);
825 /** Wrapper around strncpy() */
827 _mesa_strncpy( char *dest
, const char *src
, size_t n
)
829 return strncpy(dest
, src
, n
);
832 /** Wrapper around strlen() */
834 _mesa_strlen( const char *s
)
839 /** Wrapper around strcmp() */
841 _mesa_strcmp( const char *s1
, const char *s2
)
843 return strcmp(s1
, s2
);
846 /** Wrapper around strncmp() */
848 _mesa_strncmp( const char *s1
, const char *s2
, size_t n
)
850 return strncmp(s1
, s2
, n
);
854 * Implemented using _mesa_malloc() and _mesa_strcpy.
855 * Note that NULL is handled accordingly.
858 _mesa_strdup( const char *s
)
861 size_t l
= _mesa_strlen(s
);
862 char *s2
= (char *) _mesa_malloc(l
+ 1);
872 /** Wrapper around atoi() */
874 _mesa_atoi(const char *s
)
879 /** Wrapper around strtod() */
881 _mesa_strtod( const char *s
, char **end
)
883 return strtod(s
, end
);
889 /**********************************************************************/
893 /** Wrapper around vsprintf() */
895 _mesa_sprintf( char *str
, const char *fmt
, ... )
899 va_start( args
, fmt
);
900 r
= vsprintf( str
, fmt
, args
);
905 /** Wrapper around printf(), using vsprintf() for the formatting. */
907 _mesa_printf( const char *fmtString
, ... )
911 va_start( args
, fmtString
);
912 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
914 fprintf(stderr
,"%s", s
);
917 /** Wrapper around vsprintf() */
919 _mesa_vsprintf( char *str
, const char *fmt
, va_list args
)
921 return vsprintf( str
, fmt
, args
);
927 /**********************************************************************/
928 /** \name Diagnostics */
934 * \param ctx GL context.
935 * \param fmtString printf() alike format string.
937 * If debugging is enabled (either at compile-time via the DEBUG macro, or
938 * run-time via the MESA_DEBUG environment variable), prints the warning to
939 * stderr via fprintf().
942 _mesa_warning( GLcontext
*ctx
, const char *fmtString
, ... )
948 va_start( args
, fmtString
);
949 (void) vsnprintf( str
, MAXSTRING
, fmtString
, args
);
952 debug
= GL_TRUE
; /* always print warning */
954 debug
= _mesa_getenv("MESA_DEBUG") ? GL_TRUE
: GL_FALSE
;
957 fprintf(stderr
, "Mesa warning: %s\n", str
);
962 * This function is called when the Mesa user has stumbled into a code
963 * path which may not be implemented fully or correctly.
965 * \param ctx GL context.
966 * \param s problem description string.
968 * Prints the message to stderr via fprintf().
971 _mesa_problem( const GLcontext
*ctx
, const char *fmtString
, ... )
977 va_start( args
, fmtString
);
978 vsnprintf( str
, MAXSTRING
, fmtString
, args
);
981 fprintf(stderr
, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING
, str
);
982 fprintf(stderr
, "Please report at bugzilla.freedesktop.org\n");
986 * Display an error message.
988 * If in debug mode, print error message.
989 * Also, record the error code by calling _mesa_record_error().
991 * \param ctx the GL context.
992 * \param error the error value.
993 * \param fmtString printf() style format string, followed by optional args
995 * If debugging is enabled (either at compile-time via the DEBUG macro, or
996 * run-time via the MESA_DEBUG environment variable), interperts the error code and
997 * prints the error message via _mesa_debug().
1000 _mesa_error( GLcontext
*ctx
, GLenum error
, const char *fmtString
, ... )
1002 const char *debugEnv
;
1005 debugEnv
= _mesa_getenv("MESA_DEBUG");
1008 if (debugEnv
&& _mesa_strstr(debugEnv
, "silent"))
1021 char where
[MAXSTRING
];
1024 va_start( args
, fmtString
);
1025 vsnprintf( where
, MAXSTRING
, fmtString
, args
);
1030 errstr
= "GL_NO_ERROR";
1032 case GL_INVALID_VALUE
:
1033 errstr
= "GL_INVALID_VALUE";
1035 case GL_INVALID_ENUM
:
1036 errstr
= "GL_INVALID_ENUM";
1038 case GL_INVALID_OPERATION
:
1039 errstr
= "GL_INVALID_OPERATION";
1041 case GL_STACK_OVERFLOW
:
1042 errstr
= "GL_STACK_OVERFLOW";
1044 case GL_STACK_UNDERFLOW
:
1045 errstr
= "GL_STACK_UNDERFLOW";
1047 case GL_OUT_OF_MEMORY
:
1048 errstr
= "GL_OUT_OF_MEMORY";
1050 case GL_TABLE_TOO_LARGE
:
1051 errstr
= "GL_TABLE_TOO_LARGE";
1053 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT
:
1054 errstr
= "GL_INVALID_FRAMEBUFFER_OPERATION";
1060 _mesa_debug(ctx
, "User error: %s in %s\n", errstr
, where
);
1063 _mesa_record_error(ctx
, error
);
1067 * Report debug information.
1069 * \param ctx GL context.
1070 * \param fmtString printf() alike format string.
1072 * Prints the message to stderr via fprintf().
1075 _mesa_debug( const GLcontext
*ctx
, const char *fmtString
, ... )
1080 va_start(args
, fmtString
);
1081 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
1083 fprintf(stderr
, "Mesa: %s", s
);
1093 * Wrapper for exit().
1096 _mesa_exit( int status
)