345a1c53e2fb0030b65a1db1e1aaa26882086917
[mesa.git] / src / mesa / main / imports.c
1 /**
2 * \file imports.c
3 * Standard C library function wrappers.
4 *
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,
8 * etc.
9 *
10 * Some drivers will want to override/replace this file with something
11 * specialized, but that'll be rare.
12 *
13 * Eventually, I want to move roll the glheader.h file into this.
14 *
15 * \todo Functions still needed:
16 * - scanf
17 * - qsort
18 * - rand and RAND_MAX
19 */
20
21 /*
22 * Mesa 3-D graphics library
23 * Version: 7.1
24 *
25 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
26 *
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:
33 *
34 * The above copyright notice and this permission notice shall be included
35 * in all copies or substantial portions of the Software.
36 *
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.
43 */
44
45
46
47 #include "imports.h"
48 #include "context.h"
49 #include "mtypes.h"
50 #include "version.h"
51
52 #ifdef _GNU_SOURCE
53 #include <locale.h>
54 #ifdef __APPLE__
55 #include <xlocale.h>
56 #endif
57 #endif
58
59
60 #define MAXSTRING 4000 /* for vsnprintf() */
61
62 #ifdef WIN32
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);
66 #ifdef __VMS
67 #include "vsnprintf.c"
68 #endif
69 #endif
70
71 /**********************************************************************/
72 /** \name Memory */
73 /*@{*/
74
75 /**
76 * Allocate aligned memory.
77 *
78 * \param bytes number of bytes to allocate.
79 * \param alignment alignment (must be greater than zero).
80 *
81 * Allocates extra memory to accommodate rounding up the address for
82 * alignment and to record the real malloc address.
83 *
84 * \sa _mesa_align_free().
85 */
86 void *
87 _mesa_align_malloc(size_t bytes, unsigned long alignment)
88 {
89 #if defined(HAVE_POSIX_MEMALIGN)
90 void *mem;
91 int err = posix_memalign(& mem, alignment, bytes);
92 if (err)
93 return NULL;
94 return mem;
95 #elif defined(_WIN32) && defined(_MSC_VER)
96 return _aligned_malloc(bytes, alignment);
97 #else
98 uintptr_t ptr, buf;
99
100 ASSERT( alignment > 0 );
101
102 ptr = (uintptr_t) malloc(bytes + alignment + sizeof(void *));
103 if (!ptr)
104 return NULL;
105
106 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
107 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
108
109 #ifdef DEBUG
110 /* mark the non-aligned area */
111 while ( ptr < buf - sizeof(void *) ) {
112 *(unsigned long *)ptr = 0xcdcdcdcd;
113 ptr += sizeof(unsigned long);
114 }
115 #endif
116
117 return (void *) buf;
118 #endif /* defined(HAVE_POSIX_MEMALIGN) */
119 }
120
121 /**
122 * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
123 * malloc()
124 */
125 void *
126 _mesa_align_calloc(size_t bytes, unsigned long alignment)
127 {
128 #if defined(HAVE_POSIX_MEMALIGN)
129 void *mem;
130
131 mem = _mesa_align_malloc(bytes, alignment);
132 if (mem != NULL) {
133 (void) memset(mem, 0, bytes);
134 }
135
136 return mem;
137 #elif defined(_WIN32) && defined(_MSC_VER)
138 void *mem;
139
140 mem = _aligned_malloc(bytes, alignment);
141 if (mem != NULL) {
142 (void) memset(mem, 0, bytes);
143 }
144
145 return mem;
146 #else
147 uintptr_t ptr, buf;
148
149 ASSERT( alignment > 0 );
150
151 ptr = (uintptr_t) calloc(1, bytes + alignment + sizeof(void *));
152 if (!ptr)
153 return NULL;
154
155 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
156 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
157
158 #ifdef DEBUG
159 /* mark the non-aligned area */
160 while ( ptr < buf - sizeof(void *) ) {
161 *(unsigned long *)ptr = 0xcdcdcdcd;
162 ptr += sizeof(unsigned long);
163 }
164 #endif
165
166 return (void *)buf;
167 #endif /* defined(HAVE_POSIX_MEMALIGN) */
168 }
169
170 /**
171 * Free memory which was allocated with either _mesa_align_malloc()
172 * or _mesa_align_calloc().
173 * \param ptr pointer to the memory to be freed.
174 * The actual address to free is stored in the word immediately before the
175 * address the client sees.
176 */
177 void
178 _mesa_align_free(void *ptr)
179 {
180 #if defined(HAVE_POSIX_MEMALIGN)
181 free(ptr);
182 #elif defined(_WIN32) && defined(_MSC_VER)
183 _aligned_free(ptr);
184 #else
185 void **cubbyHole = (void **) ((char *) ptr - sizeof(void *));
186 void *realAddr = *cubbyHole;
187 free(realAddr);
188 #endif /* defined(HAVE_POSIX_MEMALIGN) */
189 }
190
191 /**
192 * Reallocate memory, with alignment.
193 */
194 void *
195 _mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
196 unsigned long alignment)
197 {
198 #if defined(_WIN32) && defined(_MSC_VER)
199 (void) oldSize;
200 return _aligned_realloc(oldBuffer, newSize, alignment);
201 #else
202 const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
203 void *newBuf = _mesa_align_malloc(newSize, alignment);
204 if (newBuf && oldBuffer && copySize > 0) {
205 memcpy(newBuf, oldBuffer, copySize);
206 }
207 if (oldBuffer)
208 _mesa_align_free(oldBuffer);
209 return newBuf;
210 #endif
211 }
212
213
214
215 /** Reallocate memory */
216 void *
217 _mesa_realloc(void *oldBuffer, size_t oldSize, size_t newSize)
218 {
219 const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
220 void *newBuffer = malloc(newSize);
221 if (newBuffer && oldBuffer && copySize > 0)
222 memcpy(newBuffer, oldBuffer, copySize);
223 if (oldBuffer)
224 free(oldBuffer);
225 return newBuffer;
226 }
227
228 /**
229 * Fill memory with a constant 16bit word.
230 * \param dst destination pointer.
231 * \param val value.
232 * \param n number of words.
233 */
234 void
235 _mesa_memset16( unsigned short *dst, unsigned short val, size_t n )
236 {
237 while (n-- > 0)
238 *dst++ = val;
239 }
240
241 /*@}*/
242
243
244 /**********************************************************************/
245 /** \name Math */
246 /*@{*/
247
248 /** Wrapper around sqrt() */
249 double
250 _mesa_sqrtd(double x)
251 {
252 return sqrt(x);
253 }
254
255
256 /*
257 * A High Speed, Low Precision Square Root
258 * by Paul Lalonde and Robert Dawson
259 * from "Graphics Gems", Academic Press, 1990
260 *
261 * SPARC implementation of a fast square root by table
262 * lookup.
263 * SPARC floating point format is as follows:
264 *
265 * BIT 31 30 23 22 0
266 * sign exponent mantissa
267 */
268 static short sqrttab[0x100]; /* declare table of square roots */
269
270 void
271 _mesa_init_sqrt_table(void)
272 {
273 #if defined(USE_IEEE) && !defined(DEBUG)
274 unsigned short i;
275 fi_type fi; /* to access the bits of a float in C quickly */
276 /* we use a union defined in glheader.h */
277
278 for(i=0; i<= 0x7f; i++) {
279 fi.i = 0;
280
281 /*
282 * Build a float with the bit pattern i as mantissa
283 * and an exponent of 0, stored as 127
284 */
285
286 fi.i = (i << 16) | (127 << 23);
287 fi.f = _mesa_sqrtd(fi.f);
288
289 /*
290 * Take the square root then strip the first 7 bits of
291 * the mantissa into the table
292 */
293
294 sqrttab[i] = (fi.i & 0x7fffff) >> 16;
295
296 /*
297 * Repeat the process, this time with an exponent of
298 * 1, stored as 128
299 */
300
301 fi.i = 0;
302 fi.i = (i << 16) | (128 << 23);
303 fi.f = sqrt(fi.f);
304 sqrttab[i+0x80] = (fi.i & 0x7fffff) >> 16;
305 }
306 #else
307 (void) sqrttab; /* silence compiler warnings */
308 #endif /*HAVE_FAST_MATH*/
309 }
310
311
312 /**
313 * Single precision square root.
314 */
315 float
316 _mesa_sqrtf( float x )
317 {
318 #if defined(USE_IEEE) && !defined(DEBUG)
319 fi_type num;
320 /* to access the bits of a float in C
321 * we use a union from glheader.h */
322
323 short e; /* the exponent */
324 if (x == 0.0F) return 0.0F; /* check for square root of 0 */
325 num.f = x;
326 e = (num.i >> 23) - 127; /* get the exponent - on a SPARC the */
327 /* exponent is stored with 127 added */
328 num.i &= 0x7fffff; /* leave only the mantissa */
329 if (e & 0x01) num.i |= 0x800000;
330 /* the exponent is odd so we have to */
331 /* look it up in the second half of */
332 /* the lookup table, so we set the */
333 /* high bit */
334 e >>= 1; /* divide the exponent by two */
335 /* note that in C the shift */
336 /* operators are sign preserving */
337 /* for signed operands */
338 /* Do the table lookup, based on the quaternary mantissa,
339 * then reconstruct the result back into a float
340 */
341 num.i = ((sqrttab[num.i >> 16]) << 16) | ((e + 127) << 23);
342
343 return num.f;
344 #else
345 return (float) _mesa_sqrtd((double) x);
346 #endif
347 }
348
349
350 /**
351 inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
352 written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
353 and Vesa Karvonen.
354 */
355 float
356 _mesa_inv_sqrtf(float n)
357 {
358 #if defined(USE_IEEE) && !defined(DEBUG)
359 float r0, x0, y0;
360 float r1, x1, y1;
361 float r2, x2, y2;
362 #if 0 /* not used, see below -BP */
363 float r3, x3, y3;
364 #endif
365 fi_type u;
366 unsigned int magic;
367
368 /*
369 Exponent part of the magic number -
370
371 We want to:
372 1. subtract the bias from the exponent,
373 2. negate it
374 3. divide by two (rounding towards -inf)
375 4. add the bias back
376
377 Which is the same as subtracting the exponent from 381 and dividing
378 by 2.
379
380 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
381 */
382
383 magic = 381 << 23;
384
385 /*
386 Significand part of magic number -
387
388 With the current magic number, "(magic - u.i) >> 1" will give you:
389
390 for 1 <= u.f <= 2: 1.25 - u.f / 4
391 for 2 <= u.f <= 4: 1.00 - u.f / 8
392
393 This isn't a bad approximation of 1/sqrt. The maximum difference from
394 1/sqrt will be around .06. After three Newton-Raphson iterations, the
395 maximum difference is less than 4.5e-8. (Which is actually close
396 enough to make the following bias academic...)
397
398 To get a better approximation you can add a bias to the magic
399 number. For example, if you subtract 1/2 of the maximum difference in
400 the first approximation (.03), you will get the following function:
401
402 for 1 <= u.f <= 2: 1.22 - u.f / 4
403 for 2 <= u.f <= 3.76: 0.97 - u.f / 8
404 for 3.76 <= u.f <= 4: 0.72 - u.f / 16
405 (The 3.76 to 4 range is where the result is < .5.)
406
407 This is the closest possible initial approximation, but with a maximum
408 error of 8e-11 after three NR iterations, it is still not perfect. If
409 you subtract 0.0332281 instead of .03, the maximum error will be
410 2.5e-11 after three NR iterations, which should be about as close as
411 is possible.
412
413 for 1 <= u.f <= 2: 1.2167719 - u.f / 4
414 for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
415 for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
416
417 */
418
419 magic -= (int)(0.0332281 * (1 << 25));
420
421 u.f = n;
422 u.i = (magic - u.i) >> 1;
423
424 /*
425 Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
426 allows more parallelism. From what I understand, the parallelism
427 comes at the cost of less precision, because it lets error
428 accumulate across iterations.
429 */
430 x0 = 1.0f;
431 y0 = 0.5f * n;
432 r0 = u.f;
433
434 x1 = x0 * r0;
435 y1 = y0 * r0 * r0;
436 r1 = 1.5f - y1;
437
438 x2 = x1 * r1;
439 y2 = y1 * r1 * r1;
440 r2 = 1.5f - y2;
441
442 #if 1
443 return x2 * r2; /* we can stop here, and be conformant -BP */
444 #else
445 x3 = x2 * r2;
446 y3 = y2 * r2 * r2;
447 r3 = 1.5f - y3;
448
449 return x3 * r3;
450 #endif
451 #else
452 return (float) (1.0 / sqrt(n));
453 #endif
454 }
455
456 #ifndef __GNUC__
457 /**
458 * Find the first bit set in a word.
459 */
460 int
461 _mesa_ffs(int32_t i)
462 {
463 #if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
464 register int bit = 0;
465 if (i != 0) {
466 if ((i & 0xffff) == 0) {
467 bit += 16;
468 i >>= 16;
469 }
470 if ((i & 0xff) == 0) {
471 bit += 8;
472 i >>= 8;
473 }
474 if ((i & 0xf) == 0) {
475 bit += 4;
476 i >>= 4;
477 }
478 while ((i & 1) == 0) {
479 bit++;
480 i >>= 1;
481 }
482 bit++;
483 }
484 return bit;
485 #else
486 return ffs(i);
487 #endif
488 }
489
490
491 /**
492 * Find position of first bit set in given value.
493 * XXX Warning: this function can only be used on 64-bit systems!
494 * \return position of least-significant bit set, starting at 1, return zero
495 * if no bits set.
496 */
497 int
498 _mesa_ffsll(int64_t val)
499 {
500 int bit;
501
502 assert(sizeof(val) == 8);
503
504 bit = _mesa_ffs((int32_t)val);
505 if (bit != 0)
506 return bit;
507
508 bit = _mesa_ffs((int32_t)(val >> 32));
509 if (bit != 0)
510 return 32 + bit;
511
512 return 0;
513 }
514 #endif
515
516 #if !defined(__GNUC__) ||\
517 ((_GNUC__ == 3 && __GNUC_MINOR__ < 4) && __GNUC__ < 4)
518 /**
519 * Return number of bits set in given GLuint.
520 */
521 unsigned int
522 _mesa_bitcount(unsigned int n)
523 {
524 unsigned int bits;
525 for (bits = 0; n > 0; n = n >> 1) {
526 bits += (n & 1);
527 }
528 return bits;
529 }
530
531 /**
532 * Return number of bits set in given 64-bit uint.
533 */
534 unsigned int
535 _mesa_bitcount_64(uint64_t n)
536 {
537 unsigned int bits;
538 for (bits = 0; n > 0; n = n >> 1) {
539 bits += (n & 1);
540 }
541 return bits;
542 }
543 #endif
544
545
546 /**
547 * Convert a 4-byte float to a 2-byte half float.
548 * Based on code from:
549 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
550 */
551 GLhalfARB
552 _mesa_float_to_half(float val)
553 {
554 const fi_type fi = {val};
555 const int flt_m = fi.i & 0x7fffff;
556 const int flt_e = (fi.i >> 23) & 0xff;
557 const int flt_s = (fi.i >> 31) & 0x1;
558 int s, e, m = 0;
559 GLhalfARB result;
560
561 /* sign bit */
562 s = flt_s;
563
564 /* handle special cases */
565 if ((flt_e == 0) && (flt_m == 0)) {
566 /* zero */
567 /* m = 0; - already set */
568 e = 0;
569 }
570 else if ((flt_e == 0) && (flt_m != 0)) {
571 /* denorm -- denorm float maps to 0 half */
572 /* m = 0; - already set */
573 e = 0;
574 }
575 else if ((flt_e == 0xff) && (flt_m == 0)) {
576 /* infinity */
577 /* m = 0; - already set */
578 e = 31;
579 }
580 else if ((flt_e == 0xff) && (flt_m != 0)) {
581 /* NaN */
582 m = 1;
583 e = 31;
584 }
585 else {
586 /* regular number */
587 const int new_exp = flt_e - 127;
588 if (new_exp < -24) {
589 /* this maps to 0 */
590 /* m = 0; - already set */
591 e = 0;
592 }
593 else if (new_exp < -14) {
594 /* this maps to a denorm */
595 unsigned int exp_val = (unsigned int) (-14 - new_exp); /* 2^-exp_val*/
596 e = 0;
597 switch (exp_val) {
598 case 0:
599 _mesa_warning(NULL,
600 "float_to_half: logical error in denorm creation!\n");
601 /* m = 0; - already set */
602 break;
603 case 1: m = 512 + (flt_m >> 14); break;
604 case 2: m = 256 + (flt_m >> 15); break;
605 case 3: m = 128 + (flt_m >> 16); break;
606 case 4: m = 64 + (flt_m >> 17); break;
607 case 5: m = 32 + (flt_m >> 18); break;
608 case 6: m = 16 + (flt_m >> 19); break;
609 case 7: m = 8 + (flt_m >> 20); break;
610 case 8: m = 4 + (flt_m >> 21); break;
611 case 9: m = 2 + (flt_m >> 22); break;
612 case 10: m = 1; break;
613 }
614 }
615 else if (new_exp > 15) {
616 /* map this value to infinity */
617 /* m = 0; - already set */
618 e = 31;
619 }
620 else {
621 /* regular */
622 e = new_exp + 15;
623 m = flt_m >> 13;
624 }
625 }
626
627 result = (s << 15) | (e << 10) | m;
628 return result;
629 }
630
631
632 /**
633 * Convert a 2-byte half float to a 4-byte float.
634 * Based on code from:
635 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
636 */
637 float
638 _mesa_half_to_float(GLhalfARB val)
639 {
640 /* XXX could also use a 64K-entry lookup table */
641 const int m = val & 0x3ff;
642 const int e = (val >> 10) & 0x1f;
643 const int s = (val >> 15) & 0x1;
644 int flt_m, flt_e, flt_s;
645 fi_type fi;
646 float result;
647
648 /* sign bit */
649 flt_s = s;
650
651 /* handle special cases */
652 if ((e == 0) && (m == 0)) {
653 /* zero */
654 flt_m = 0;
655 flt_e = 0;
656 }
657 else if ((e == 0) && (m != 0)) {
658 /* denorm -- denorm half will fit in non-denorm single */
659 const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
660 float mantissa = ((float) (m)) / 1024.0f;
661 float sign = s ? -1.0f : 1.0f;
662 return sign * mantissa * half_denorm;
663 }
664 else if ((e == 31) && (m == 0)) {
665 /* infinity */
666 flt_e = 0xff;
667 flt_m = 0;
668 }
669 else if ((e == 31) && (m != 0)) {
670 /* NaN */
671 flt_e = 0xff;
672 flt_m = 1;
673 }
674 else {
675 /* regular */
676 flt_e = e + 112;
677 flt_m = m << 13;
678 }
679
680 fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
681 result = fi.f;
682 return result;
683 }
684
685 /*@}*/
686
687
688 /**********************************************************************/
689 /** \name Sort & Search */
690 /*@{*/
691
692 /**
693 * Wrapper for bsearch().
694 */
695 void *
696 _mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
697 int (*compar)(const void *, const void *) )
698 {
699 #if defined(_WIN32_WCE)
700 void *mid;
701 int cmp;
702 while (nmemb) {
703 nmemb >>= 1;
704 mid = (char *)base + nmemb * size;
705 cmp = (*compar)(key, mid);
706 if (cmp == 0)
707 return mid;
708 if (cmp > 0) {
709 base = (char *)mid + size;
710 --nmemb;
711 }
712 }
713 return NULL;
714 #else
715 return bsearch(key, base, nmemb, size, compar);
716 #endif
717 }
718
719 /*@}*/
720
721
722 /**********************************************************************/
723 /** \name Environment vars */
724 /*@{*/
725
726 /**
727 * Wrapper for getenv().
728 */
729 char *
730 _mesa_getenv( const char *var )
731 {
732 #if defined(_XBOX) || defined(_WIN32_WCE)
733 return NULL;
734 #else
735 return getenv(var);
736 #endif
737 }
738
739 /*@}*/
740
741
742 /**********************************************************************/
743 /** \name String */
744 /*@{*/
745
746 /**
747 * Implemented using malloc() and strcpy.
748 * Note that NULL is handled accordingly.
749 */
750 char *
751 _mesa_strdup( const char *s )
752 {
753 if (s) {
754 size_t l = strlen(s);
755 char *s2 = (char *) malloc(l + 1);
756 if (s2)
757 strcpy(s2, s);
758 return s2;
759 }
760 else {
761 return NULL;
762 }
763 }
764
765 /** Wrapper around strtof() */
766 float
767 _mesa_strtof( const char *s, char **end )
768 {
769 #if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__) && \
770 !defined(ANDROID)
771 static locale_t loc = NULL;
772 if (!loc) {
773 loc = newlocale(LC_CTYPE_MASK, "C", NULL);
774 }
775 return strtof_l(s, end, loc);
776 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
777 return strtof(s, end);
778 #else
779 return (float)strtod(s, end);
780 #endif
781 }
782
783 /** Compute simple checksum/hash for a string */
784 unsigned int
785 _mesa_str_checksum(const char *str)
786 {
787 /* This could probably be much better */
788 unsigned int sum, i;
789 const char *c;
790 sum = i = 1;
791 for (c = str; *c; c++, i++)
792 sum += *c * (i % 100);
793 return sum + i;
794 }
795
796
797 /*@}*/
798
799
800 /** Wrapper around vsnprintf() */
801 int
802 _mesa_snprintf( char *str, size_t size, const char *fmt, ... )
803 {
804 int r;
805 va_list args;
806 va_start( args, fmt );
807 r = vsnprintf( str, size, fmt, args );
808 va_end( args );
809 return r;
810 }
811
812
813 /**********************************************************************/
814 /** \name Diagnostics */
815 /*@{*/
816
817 static void
818 output_if_debug(const char *prefixString, const char *outputString,
819 GLboolean newline)
820 {
821 static int debug = -1;
822
823 /* Check the MESA_DEBUG environment variable if it hasn't
824 * been checked yet. We only have to check it once...
825 */
826 if (debug == -1) {
827 char *env = _mesa_getenv("MESA_DEBUG");
828
829 /* In a debug build, we print warning messages *unless*
830 * MESA_DEBUG is 0. In a non-debug build, we don't
831 * print warning messages *unless* MESA_DEBUG is
832 * set *to any value*.
833 */
834 #ifdef DEBUG
835 debug = (env != NULL && atoi(env) == 0) ? 0 : 1;
836 #else
837 debug = (env != NULL) ? 1 : 0;
838 #endif
839 }
840
841 /* Now only print the string if we're required to do so. */
842 if (debug) {
843 fprintf(stderr, "%s: %s", prefixString, outputString);
844 if (newline)
845 fprintf(stderr, "\n");
846
847 #if defined(_WIN32) && !defined(_WIN32_WCE)
848 /* stderr from windows applications without console is not usually
849 * visible, so communicate with the debugger instead */
850 {
851 char buf[4096];
852 _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
853 OutputDebugStringA(buf);
854 }
855 #endif
856 }
857 }
858
859
860 /**
861 * Return string version of GL error code.
862 */
863 static const char *
864 error_string( GLenum error )
865 {
866 switch (error) {
867 case GL_NO_ERROR:
868 return "GL_NO_ERROR";
869 case GL_INVALID_VALUE:
870 return "GL_INVALID_VALUE";
871 case GL_INVALID_ENUM:
872 return "GL_INVALID_ENUM";
873 case GL_INVALID_OPERATION:
874 return "GL_INVALID_OPERATION";
875 case GL_STACK_OVERFLOW:
876 return "GL_STACK_OVERFLOW";
877 case GL_STACK_UNDERFLOW:
878 return "GL_STACK_UNDERFLOW";
879 case GL_OUT_OF_MEMORY:
880 return "GL_OUT_OF_MEMORY";
881 case GL_TABLE_TOO_LARGE:
882 return "GL_TABLE_TOO_LARGE";
883 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
884 return "GL_INVALID_FRAMEBUFFER_OPERATION";
885 default:
886 return "unknown";
887 }
888 }
889
890
891 /**
892 * When a new type of error is recorded, print a message describing
893 * previous errors which were accumulated.
894 */
895 static void
896 flush_delayed_errors( struct gl_context *ctx )
897 {
898 char s[MAXSTRING];
899
900 if (ctx->ErrorDebugCount) {
901 _mesa_snprintf(s, MAXSTRING, "%d similar %s errors",
902 ctx->ErrorDebugCount,
903 error_string(ctx->ErrorValue));
904
905 output_if_debug("Mesa", s, GL_TRUE);
906
907 ctx->ErrorDebugCount = 0;
908 }
909 }
910
911
912 /**
913 * Report a warning (a recoverable error condition) to stderr if
914 * either DEBUG is defined or the MESA_DEBUG env var is set.
915 *
916 * \param ctx GL context.
917 * \param fmtString printf()-like format string.
918 */
919 void
920 _mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
921 {
922 char str[MAXSTRING];
923 va_list args;
924 va_start( args, fmtString );
925 (void) vsnprintf( str, MAXSTRING, fmtString, args );
926 va_end( args );
927
928 if (ctx)
929 flush_delayed_errors( ctx );
930
931 output_if_debug("Mesa warning", str, GL_TRUE);
932 }
933
934
935 /**
936 * Report an internal implementation problem.
937 * Prints the message to stderr via fprintf().
938 *
939 * \param ctx GL context.
940 * \param fmtString problem description string.
941 */
942 void
943 _mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
944 {
945 va_list args;
946 char str[MAXSTRING];
947 static int numCalls = 0;
948
949 (void) ctx;
950
951 if (numCalls < 50) {
952 numCalls++;
953
954 va_start( args, fmtString );
955 vsnprintf( str, MAXSTRING, fmtString, args );
956 va_end( args );
957 fprintf(stderr, "Mesa %s implementation error: %s\n",
958 MESA_VERSION_STRING, str);
959 fprintf(stderr, "Please report at bugs.freedesktop.org\n");
960 }
961 }
962
963
964 /**
965 * Record an OpenGL state error. These usually occur when the user
966 * passes invalid parameters to a GL function.
967 *
968 * If debugging is enabled (either at compile-time via the DEBUG macro, or
969 * run-time via the MESA_DEBUG environment variable), report the error with
970 * _mesa_debug().
971 *
972 * \param ctx the GL context.
973 * \param error the error value.
974 * \param fmtString printf() style format string, followed by optional args
975 */
976 void
977 _mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
978 {
979 static GLint debug = -1;
980
981 /* Check debug environment variable only once:
982 */
983 if (debug == -1) {
984 const char *debugEnv = _mesa_getenv("MESA_DEBUG");
985
986 #ifdef DEBUG
987 if (debugEnv && strstr(debugEnv, "silent"))
988 debug = GL_FALSE;
989 else
990 debug = GL_TRUE;
991 #else
992 if (debugEnv)
993 debug = GL_TRUE;
994 else
995 debug = GL_FALSE;
996 #endif
997 }
998
999 if (debug) {
1000 if (ctx->ErrorValue == error &&
1001 ctx->ErrorDebugFmtString == fmtString) {
1002 ctx->ErrorDebugCount++;
1003 }
1004 else {
1005 char s[MAXSTRING], s2[MAXSTRING];
1006 va_list args;
1007
1008 flush_delayed_errors( ctx );
1009
1010 va_start(args, fmtString);
1011 vsnprintf(s, MAXSTRING, fmtString, args);
1012 va_end(args);
1013
1014 _mesa_snprintf(s2, MAXSTRING, "%s in %s", error_string(error), s);
1015 output_if_debug("Mesa: User error", s2, GL_TRUE);
1016
1017 ctx->ErrorDebugFmtString = fmtString;
1018 ctx->ErrorDebugCount = 0;
1019 }
1020 }
1021
1022 _mesa_record_error(ctx, error);
1023 }
1024
1025
1026 /**
1027 * Report debug information. Print error message to stderr via fprintf().
1028 * No-op if DEBUG mode not enabled.
1029 *
1030 * \param ctx GL context.
1031 * \param fmtString printf()-style format string, followed by optional args.
1032 */
1033 void
1034 _mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
1035 {
1036 #ifdef DEBUG
1037 char s[MAXSTRING];
1038 va_list args;
1039 va_start(args, fmtString);
1040 vsnprintf(s, MAXSTRING, fmtString, args);
1041 va_end(args);
1042 output_if_debug("Mesa", s, GL_FALSE);
1043 #endif /* DEBUG */
1044 (void) ctx;
1045 (void) fmtString;
1046 }
1047
1048 /*@}*/