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