mesa: Don't use newlocale on Haiku
[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 ffs(int i)
462 {
463 register int bit = 0;
464 if (i != 0) {
465 if ((i & 0xffff) == 0) {
466 bit += 16;
467 i >>= 16;
468 }
469 if ((i & 0xff) == 0) {
470 bit += 8;
471 i >>= 8;
472 }
473 if ((i & 0xf) == 0) {
474 bit += 4;
475 i >>= 4;
476 }
477 while ((i & 1) == 0) {
478 bit++;
479 i >>= 1;
480 }
481 bit++;
482 }
483 return bit;
484 }
485
486
487 /**
488 * Find position of first bit set in given value.
489 * XXX Warning: this function can only be used on 64-bit systems!
490 * \return position of least-significant bit set, starting at 1, return zero
491 * if no bits set.
492 */
493 int
494 ffsll(long long int val)
495 {
496 int bit;
497
498 assert(sizeof(val) == 8);
499
500 bit = ffs((int) val);
501 if (bit != 0)
502 return bit;
503
504 bit = ffs((int) (val >> 32));
505 if (bit != 0)
506 return 32 + bit;
507
508 return 0;
509 }
510 #endif /* __GNUC__ */
511
512
513 #if !defined(__GNUC__) ||\
514 ((__GNUC__ * 100 + __GNUC_MINOR__) < 304) /* Not gcc 3.4 or later */
515 /**
516 * Return number of bits set in given GLuint.
517 */
518 unsigned int
519 _mesa_bitcount(unsigned int n)
520 {
521 unsigned int bits;
522 for (bits = 0; n > 0; n = n >> 1) {
523 bits += (n & 1);
524 }
525 return bits;
526 }
527
528 /**
529 * Return number of bits set in given 64-bit uint.
530 */
531 unsigned int
532 _mesa_bitcount_64(uint64_t n)
533 {
534 unsigned int bits;
535 for (bits = 0; n > 0; n = n >> 1) {
536 bits += (n & 1);
537 }
538 return bits;
539 }
540 #endif
541
542
543 /**
544 * Convert a 4-byte float to a 2-byte half float.
545 * Based on code from:
546 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
547 */
548 GLhalfARB
549 _mesa_float_to_half(float val)
550 {
551 const fi_type fi = {val};
552 const int flt_m = fi.i & 0x7fffff;
553 const int flt_e = (fi.i >> 23) & 0xff;
554 const int flt_s = (fi.i >> 31) & 0x1;
555 int s, e, m = 0;
556 GLhalfARB result;
557
558 /* sign bit */
559 s = flt_s;
560
561 /* handle special cases */
562 if ((flt_e == 0) && (flt_m == 0)) {
563 /* zero */
564 /* m = 0; - already set */
565 e = 0;
566 }
567 else if ((flt_e == 0) && (flt_m != 0)) {
568 /* denorm -- denorm float maps to 0 half */
569 /* m = 0; - already set */
570 e = 0;
571 }
572 else if ((flt_e == 0xff) && (flt_m == 0)) {
573 /* infinity */
574 /* m = 0; - already set */
575 e = 31;
576 }
577 else if ((flt_e == 0xff) && (flt_m != 0)) {
578 /* NaN */
579 m = 1;
580 e = 31;
581 }
582 else {
583 /* regular number */
584 const int new_exp = flt_e - 127;
585 if (new_exp < -24) {
586 /* this maps to 0 */
587 /* m = 0; - already set */
588 e = 0;
589 }
590 else if (new_exp < -14) {
591 /* this maps to a denorm */
592 unsigned int exp_val = (unsigned int) (-14 - new_exp); /* 2^-exp_val*/
593 e = 0;
594 switch (exp_val) {
595 case 0:
596 _mesa_warning(NULL,
597 "float_to_half: logical error in denorm creation!\n");
598 /* m = 0; - already set */
599 break;
600 case 1: m = 512 + (flt_m >> 14); break;
601 case 2: m = 256 + (flt_m >> 15); break;
602 case 3: m = 128 + (flt_m >> 16); break;
603 case 4: m = 64 + (flt_m >> 17); break;
604 case 5: m = 32 + (flt_m >> 18); break;
605 case 6: m = 16 + (flt_m >> 19); break;
606 case 7: m = 8 + (flt_m >> 20); break;
607 case 8: m = 4 + (flt_m >> 21); break;
608 case 9: m = 2 + (flt_m >> 22); break;
609 case 10: m = 1; break;
610 }
611 }
612 else if (new_exp > 15) {
613 /* map this value to infinity */
614 /* m = 0; - already set */
615 e = 31;
616 }
617 else {
618 /* regular */
619 e = new_exp + 15;
620 m = flt_m >> 13;
621 }
622 }
623
624 result = (s << 15) | (e << 10) | m;
625 return result;
626 }
627
628
629 /**
630 * Convert a 2-byte half float to a 4-byte float.
631 * Based on code from:
632 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
633 */
634 float
635 _mesa_half_to_float(GLhalfARB val)
636 {
637 /* XXX could also use a 64K-entry lookup table */
638 const int m = val & 0x3ff;
639 const int e = (val >> 10) & 0x1f;
640 const int s = (val >> 15) & 0x1;
641 int flt_m, flt_e, flt_s;
642 fi_type fi;
643 float result;
644
645 /* sign bit */
646 flt_s = s;
647
648 /* handle special cases */
649 if ((e == 0) && (m == 0)) {
650 /* zero */
651 flt_m = 0;
652 flt_e = 0;
653 }
654 else if ((e == 0) && (m != 0)) {
655 /* denorm -- denorm half will fit in non-denorm single */
656 const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
657 float mantissa = ((float) (m)) / 1024.0f;
658 float sign = s ? -1.0f : 1.0f;
659 return sign * mantissa * half_denorm;
660 }
661 else if ((e == 31) && (m == 0)) {
662 /* infinity */
663 flt_e = 0xff;
664 flt_m = 0;
665 }
666 else if ((e == 31) && (m != 0)) {
667 /* NaN */
668 flt_e = 0xff;
669 flt_m = 1;
670 }
671 else {
672 /* regular */
673 flt_e = e + 112;
674 flt_m = m << 13;
675 }
676
677 fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
678 result = fi.f;
679 return result;
680 }
681
682 /*@}*/
683
684
685 /**********************************************************************/
686 /** \name Sort & Search */
687 /*@{*/
688
689 /**
690 * Wrapper for bsearch().
691 */
692 void *
693 _mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
694 int (*compar)(const void *, const void *) )
695 {
696 #if defined(_WIN32_WCE)
697 void *mid;
698 int cmp;
699 while (nmemb) {
700 nmemb >>= 1;
701 mid = (char *)base + nmemb * size;
702 cmp = (*compar)(key, mid);
703 if (cmp == 0)
704 return mid;
705 if (cmp > 0) {
706 base = (char *)mid + size;
707 --nmemb;
708 }
709 }
710 return NULL;
711 #else
712 return bsearch(key, base, nmemb, size, compar);
713 #endif
714 }
715
716 /*@}*/
717
718
719 /**********************************************************************/
720 /** \name Environment vars */
721 /*@{*/
722
723 /**
724 * Wrapper for getenv().
725 */
726 char *
727 _mesa_getenv( const char *var )
728 {
729 #if defined(_XBOX) || defined(_WIN32_WCE)
730 return NULL;
731 #else
732 return getenv(var);
733 #endif
734 }
735
736 /*@}*/
737
738
739 /**********************************************************************/
740 /** \name String */
741 /*@{*/
742
743 /**
744 * Implemented using malloc() and strcpy.
745 * Note that NULL is handled accordingly.
746 */
747 char *
748 _mesa_strdup( const char *s )
749 {
750 if (s) {
751 size_t l = strlen(s);
752 char *s2 = (char *) malloc(l + 1);
753 if (s2)
754 strcpy(s2, s);
755 return s2;
756 }
757 else {
758 return NULL;
759 }
760 }
761
762 /** Wrapper around strtof() */
763 float
764 _mesa_strtof( const char *s, char **end )
765 {
766 #if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__) && \
767 !defined(ANDROID) && !defined(__HAIKU__)
768 static locale_t loc = NULL;
769 if (!loc) {
770 loc = newlocale(LC_CTYPE_MASK, "C", NULL);
771 }
772 return strtof_l(s, end, loc);
773 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
774 return strtof(s, end);
775 #else
776 return (float)strtod(s, end);
777 #endif
778 }
779
780 /** Compute simple checksum/hash for a string */
781 unsigned int
782 _mesa_str_checksum(const char *str)
783 {
784 /* This could probably be much better */
785 unsigned int sum, i;
786 const char *c;
787 sum = i = 1;
788 for (c = str; *c; c++, i++)
789 sum += *c * (i % 100);
790 return sum + i;
791 }
792
793
794 /*@}*/
795
796
797 /** Wrapper around vsnprintf() */
798 int
799 _mesa_snprintf( char *str, size_t size, const char *fmt, ... )
800 {
801 int r;
802 va_list args;
803 va_start( args, fmt );
804 r = vsnprintf( str, size, fmt, args );
805 va_end( args );
806 return r;
807 }
808
809
810 /**********************************************************************/
811 /** \name Diagnostics */
812 /*@{*/
813
814 static void
815 output_if_debug(const char *prefixString, const char *outputString,
816 GLboolean newline)
817 {
818 static int debug = -1;
819
820 /* Check the MESA_DEBUG environment variable if it hasn't
821 * been checked yet. We only have to check it once...
822 */
823 if (debug == -1) {
824 char *env = _mesa_getenv("MESA_DEBUG");
825
826 /* In a debug build, we print warning messages *unless*
827 * MESA_DEBUG is 0. In a non-debug build, we don't
828 * print warning messages *unless* MESA_DEBUG is
829 * set *to any value*.
830 */
831 #ifdef DEBUG
832 debug = (env != NULL && atoi(env) == 0) ? 0 : 1;
833 #else
834 debug = (env != NULL) ? 1 : 0;
835 #endif
836 }
837
838 /* Now only print the string if we're required to do so. */
839 if (debug) {
840 fprintf(stderr, "%s: %s", prefixString, outputString);
841 if (newline)
842 fprintf(stderr, "\n");
843
844 #if defined(_WIN32) && !defined(_WIN32_WCE)
845 /* stderr from windows applications without console is not usually
846 * visible, so communicate with the debugger instead */
847 {
848 char buf[4096];
849 _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
850 OutputDebugStringA(buf);
851 }
852 #endif
853 }
854 }
855
856
857 /**
858 * Return string version of GL error code.
859 */
860 static const char *
861 error_string( GLenum error )
862 {
863 switch (error) {
864 case GL_NO_ERROR:
865 return "GL_NO_ERROR";
866 case GL_INVALID_VALUE:
867 return "GL_INVALID_VALUE";
868 case GL_INVALID_ENUM:
869 return "GL_INVALID_ENUM";
870 case GL_INVALID_OPERATION:
871 return "GL_INVALID_OPERATION";
872 case GL_STACK_OVERFLOW:
873 return "GL_STACK_OVERFLOW";
874 case GL_STACK_UNDERFLOW:
875 return "GL_STACK_UNDERFLOW";
876 case GL_OUT_OF_MEMORY:
877 return "GL_OUT_OF_MEMORY";
878 case GL_TABLE_TOO_LARGE:
879 return "GL_TABLE_TOO_LARGE";
880 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
881 return "GL_INVALID_FRAMEBUFFER_OPERATION";
882 default:
883 return "unknown";
884 }
885 }
886
887
888 /**
889 * When a new type of error is recorded, print a message describing
890 * previous errors which were accumulated.
891 */
892 static void
893 flush_delayed_errors( struct gl_context *ctx )
894 {
895 char s[MAXSTRING];
896
897 if (ctx->ErrorDebugCount) {
898 _mesa_snprintf(s, MAXSTRING, "%d similar %s errors",
899 ctx->ErrorDebugCount,
900 error_string(ctx->ErrorValue));
901
902 output_if_debug("Mesa", s, GL_TRUE);
903
904 ctx->ErrorDebugCount = 0;
905 }
906 }
907
908
909 /**
910 * Report a warning (a recoverable error condition) to stderr if
911 * either DEBUG is defined or the MESA_DEBUG env var is set.
912 *
913 * \param ctx GL context.
914 * \param fmtString printf()-like format string.
915 */
916 void
917 _mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
918 {
919 char str[MAXSTRING];
920 va_list args;
921 va_start( args, fmtString );
922 (void) vsnprintf( str, MAXSTRING, fmtString, args );
923 va_end( args );
924
925 if (ctx)
926 flush_delayed_errors( ctx );
927
928 output_if_debug("Mesa warning", str, GL_TRUE);
929 }
930
931
932 /**
933 * Report an internal implementation problem.
934 * Prints the message to stderr via fprintf().
935 *
936 * \param ctx GL context.
937 * \param fmtString problem description string.
938 */
939 void
940 _mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
941 {
942 va_list args;
943 char str[MAXSTRING];
944 static int numCalls = 0;
945
946 (void) ctx;
947
948 if (numCalls < 50) {
949 numCalls++;
950
951 va_start( args, fmtString );
952 vsnprintf( str, MAXSTRING, fmtString, args );
953 va_end( args );
954 fprintf(stderr, "Mesa %s implementation error: %s\n",
955 MESA_VERSION_STRING, str);
956 fprintf(stderr, "Please report at bugs.freedesktop.org\n");
957 }
958 }
959
960
961 /**
962 * Record an OpenGL state error. These usually occur when the user
963 * passes invalid parameters to a GL function.
964 *
965 * If debugging is enabled (either at compile-time via the DEBUG macro, or
966 * run-time via the MESA_DEBUG environment variable), report the error with
967 * _mesa_debug().
968 *
969 * \param ctx the GL context.
970 * \param error the error value.
971 * \param fmtString printf() style format string, followed by optional args
972 */
973 void
974 _mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
975 {
976 static GLint debug = -1;
977
978 /* Check debug environment variable only once:
979 */
980 if (debug == -1) {
981 const char *debugEnv = _mesa_getenv("MESA_DEBUG");
982
983 #ifdef DEBUG
984 if (debugEnv && strstr(debugEnv, "silent"))
985 debug = GL_FALSE;
986 else
987 debug = GL_TRUE;
988 #else
989 if (debugEnv)
990 debug = GL_TRUE;
991 else
992 debug = GL_FALSE;
993 #endif
994 }
995
996 if (debug) {
997 if (ctx->ErrorValue == error &&
998 ctx->ErrorDebugFmtString == fmtString) {
999 ctx->ErrorDebugCount++;
1000 }
1001 else {
1002 char s[MAXSTRING], s2[MAXSTRING];
1003 va_list args;
1004
1005 flush_delayed_errors( ctx );
1006
1007 va_start(args, fmtString);
1008 vsnprintf(s, MAXSTRING, fmtString, args);
1009 va_end(args);
1010
1011 _mesa_snprintf(s2, MAXSTRING, "%s in %s", error_string(error), s);
1012 output_if_debug("Mesa: User error", s2, GL_TRUE);
1013
1014 ctx->ErrorDebugFmtString = fmtString;
1015 ctx->ErrorDebugCount = 0;
1016 }
1017 }
1018
1019 _mesa_record_error(ctx, error);
1020 }
1021
1022
1023 /**
1024 * Report debug information. Print error message to stderr via fprintf().
1025 * No-op if DEBUG mode not enabled.
1026 *
1027 * \param ctx GL context.
1028 * \param fmtString printf()-style format string, followed by optional args.
1029 */
1030 void
1031 _mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
1032 {
1033 #ifdef DEBUG
1034 char s[MAXSTRING];
1035 va_list args;
1036 va_start(args, fmtString);
1037 vsnprintf(s, MAXSTRING, fmtString, args);
1038 va_end(args);
1039 output_if_debug("Mesa", s, GL_FALSE);
1040 #endif /* DEBUG */
1041 (void) ctx;
1042 (void) fmtString;
1043 }
1044
1045 /*@}*/