xm_api.c revision 190d34874cdf2a074364980d1cf2d3fa201ac7a1
1/* $Id: xm_api.c,v 1.28 2001/09/01 20:27:31 brianp Exp $ */
2
3/*
4 * Mesa 3-D graphics library
5 * Version:  3.5
6 *
7 * Copyright (C) 1999-2000  Brian Paul   All Rights Reserved.
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a
10 * copy of this software and associated documentation files (the "Software"),
11 * to deal in the Software without restriction, including without limitation
12 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 * and/or sell copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included
17 * in all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
22 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
23 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 */
26
27
28/*
29 * This file contains the implementations of all the XMesa* functions.
30 *
31 *
32 * NOTES:
33 *
34 * The window coordinate system origin (0,0) is in the lower-left corner
35 * of the window.  X11's window coordinate origin is in the upper-left
36 * corner of the window.  Therefore, most drawing functions in this
37 * file have to flip Y coordinates.
38 *
39 * Define USE_XSHM in the Makefile with -DUSE_XSHM if you want to compile
40 * in support for the MIT Shared Memory extension.  If enabled, when you
41 * use an Ximage for the back buffer in double buffered mode, the "swap"
42 * operation will be faster.  You must also link with -lXext.
43 *
44 * Byte swapping:  If the Mesa host and the X display use a different
45 * byte order then there's some trickiness to be aware of when using
46 * XImages.  The byte ordering used for the XImage is that of the X
47 * display, not the Mesa host.
48 * The color-to-pixel encoding for True/DirectColor must be done
49 * according to the display's visual red_mask, green_mask, and blue_mask.
50 * If XPutPixel is used to put a pixel into an XImage then XPutPixel will
51 * do byte swapping if needed.  If one wants to directly "poke" the pixel
52 * into the XImage's buffer then the pixel must be byte swapped first.  In
53 * Mesa, when byte swapping is needed we use the PF_TRUECOLOR pixel format
54 * and use XPutPixel everywhere except in the implementation of
55 * glClear(GL_COLOR_BUFFER_BIT).  We want this function to be fast so
56 * instead of using XPutPixel we "poke" our values after byte-swapping
57 * the clear pixel value if needed.
58 *
59 */
60
61#ifdef __CYGWIN__
62#undef WIN32
63#undef __WIN32__
64#endif
65
66#include "glxheader.h"
67#include "GL/xmesa.h"
68#include "xmesaP.h"
69#include "context.h"
70#include "extensions.h"
71#include "glthread.h"
72#include "matrix.h"
73#include "mem.h"
74#include "mmath.h"
75#include "mtypes.h"
76#ifdef HAVE_CONFIG_H
77#include "conf.h"
78#endif
79#include "macros.h"
80#include "texformat.h"
81#include "texstore.h"
82#include "swrast/swrast.h"
83#include "swrast_setup/swrast_setup.h"
84#include "array_cache/acache.h"
85#include "tnl/tnl.h"
86
87#ifndef GLX_NONE_EXT
88#define GLX_NONE_EXT 0x8000
89#endif
90
91
92/*
93 * Global X driver lock
94 */
95_glthread_Mutex _xmesa_lock;
96
97
98
99/*
100 * Lookup tables for HPCR pixel format:
101 */
102static short hpcr_rgbTbl[3][256] = {
103{
104 16,  16,  17,  17,  18,  18,  19,  19,  20,  20,  21,  21,  22,  22,  23,  23,
105 24,  24,  25,  25,  26,  26,  27,  27,  28,  28,  29,  29,  30,  30,  31,  31,
106 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
107 32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,
108 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
109 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,
110 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
111 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
113128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
114144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
115160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
116176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
117192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
118208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
119224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239
120},
121{
122 16,  16,  17,  17,  18,  18,  19,  19,  20,  20,  21,  21,  22,  22,  23,  23,
123 24,  24,  25,  25,  26,  26,  27,  27,  28,  28,  29,  29,  30,  30,  31,  31,
124 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
125 32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,
126 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
127 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,
128 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
129 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
130112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
131128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
132144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
133160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
134176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
135192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
136208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
137224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239
138},
139{
140 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
141 40,  40,  41,  41,  42,  42,  43,  43,  44,  44,  45,  45,  46,  46,  47,  47,
142 48,  48,  49,  49,  50,  50,  51,  51,  52,  52,  53,  53,  54,  54,  55,  55,
143 56,  56,  57,  57,  58,  58,  59,  59,  60,  60,  61,  61,  62,  62,  63,  63,
144 64,  64,  65,  65,  66,  66,  67,  67,  68,  68,  69,  69,  70,  70,  71,  71,
145 72,  72,  73,  73,  74,  74,  75,  75,  76,  76,  77,  77,  78,  78,  79,  79,
146 80,  80,  81,  81,  82,  82,  83,  83,  84,  84,  85,  85,  86,  86,  87,  87,
147 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
148 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
149112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
150128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
151144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
152160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
153176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
154192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
155208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223
156}
157};
158
159
160
161/**********************************************************************/
162/*****                     X Utility Functions                    *****/
163/**********************************************************************/
164
165
166/*
167 * X/Mesa error reporting function:
168 */
169static void error( const char *msg )
170{
171   if (getenv("MESA_DEBUG"))
172      fprintf( stderr, "X/Mesa error: %s\n", msg );
173}
174
175
176/*
177 * Return the host's byte order as LSBFirst or MSBFirst ala X.
178 */
179#ifndef XFree86Server
180static int host_byte_order( void )
181{
182   int i = 1;
183   char *cptr = (char *) &i;
184   return (*cptr==1) ? LSBFirst : MSBFirst;
185}
186#endif
187
188
189/*
190 * Error handling.
191 */
192#ifndef XFree86Server
193static int mesaXErrorFlag = 0;
194
195static int mesaHandleXError( XMesaDisplay *dpy, XErrorEvent *event )
196{
197   (void) dpy;
198   (void) event;
199   mesaXErrorFlag = 1;
200   return 0;
201}
202#endif
203
204
205/*
206 * Check if the X Shared Memory extension is available.
207 * Return:  0 = not available
208 *          1 = shared XImage support available
209 *          2 = shared Pixmap support available also
210 */
211#ifndef XFree86Server
212static int check_for_xshm( XMesaDisplay *display )
213{
214#ifdef USE_XSHM
215   int major, minor, ignore;
216   Bool pixmaps;
217
218   if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
219      if (XShmQueryVersion( display, &major, &minor, &pixmaps )==True) {
220	 return (pixmaps==True) ? 2 : 1;
221      }
222      else {
223	 return 0;
224      }
225   }
226   else {
227      return 0;
228   }
229#else
230   /* Can't compile XSHM support */
231   return 0;
232#endif
233}
234#endif
235
236
237/*
238 * Return the width and height of the given drawable.
239 */
240static void get_drawable_size( XMesaDisplay *dpy, XMesaDrawable d,
241                               unsigned int *width, unsigned int *height)
242{
243#ifdef XFree86Server
244    (void) dpy;
245    *width = d->width;
246    *height = d->height;
247#else
248   Window root;
249   int x, y;
250   unsigned int bw, depth;
251
252   _glthread_LOCK_MUTEX(_xmesa_lock);
253   XGetGeometry( dpy, d, &root, &x, &y, width, height, &bw, &depth );
254   _glthread_UNLOCK_MUTEX(_xmesa_lock);
255#endif
256}
257
258
259/*
260 * Apply gamma correction to an intensity value in [0..max].  Return the
261 * new intensity value.
262 */
263static GLint gamma_adjust( GLfloat gamma, GLint value, GLint max )
264{
265   if (gamma == 1.0) {
266      return value;
267   }
268   else {
269      double x = (double) value / (double) max;
270      return IROUND_POS((GLfloat) max * pow(x, 1.0F/gamma));
271   }
272}
273
274
275
276/*
277 * Return the true number of bits per pixel for XImages.
278 * For example, if we request a 24-bit deep visual we may actually need/get
279 * 32bpp XImages.  This function returns the appropriate bpp.
280 * Input:  dpy - the X display
281 *         visinfo - desribes the visual to be used for XImages
282 * Return:  true number of bits per pixel for XImages
283 */
284#define GET_BITS_PER_PIXEL(xmv) bits_per_pixel(xmv)
285
286#ifdef XFree86Server
287
288static int bits_per_pixel( XMesaVisual xmv )
289{
290   XMesaVisualInfo visinfo = xmv->visinfo;
291   const int depth = visinfo->nplanes;
292   int i;
293   for (i = 0; i < screenInfo.numPixmapFormats; i++) {
294      if (screenInfo.formats[i].depth == depth)
295         return screenInfo.formats[i].bitsPerPixel;
296   }
297   return depth;  /* should never get here, but this should be safe */
298}
299
300#else
301
302static int bits_per_pixel( XMesaVisual xmv )
303{
304   XMesaDisplay *dpy = xmv->display;
305   XMesaVisualInfo visinfo = xmv->visinfo;
306   XMesaImage *img;
307   int bitsPerPixel;
308   /* Create a temporary XImage */
309   img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
310		       ZPixmap, 0,           /*format, offset*/
311		       (char*) MALLOC(8),    /*data*/
312		       1, 1,                 /*width, height*/
313		       32,                   /*bitmap_pad*/
314		       0                     /*bytes_per_line*/
315                     );
316   assert(img);
317   /* grab the bits/pixel value */
318   bitsPerPixel = img->bits_per_pixel;
319   /* free the XImage */
320   FREE( img->data );
321   img->data = NULL;
322   XMesaDestroyImage( img );
323   return bitsPerPixel;
324}
325#endif
326
327
328
329/*
330 * Determine if a given X window ID is valid (window exists).
331 * Do this by calling XGetWindowAttributes() for the window and
332 * checking if we catch an X error.
333 * Input:  dpy - the display
334 *         win - the window to check for existance
335 * Return:  GL_TRUE - window exists
336 *          GL_FALSE - window doesn't exist
337 */
338#ifndef XFree86Server
339static GLboolean WindowExistsFlag;
340
341static int window_exists_err_handler( XMesaDisplay* dpy, XErrorEvent* xerr )
342{
343   (void) dpy;
344   if (xerr->error_code == BadWindow) {
345      WindowExistsFlag = GL_FALSE;
346   }
347   return 0;
348}
349
350static GLboolean window_exists( XMesaDisplay *dpy, Window win )
351{
352   XWindowAttributes wa;
353   int (*old_handler)( XMesaDisplay*, XErrorEvent* );
354   WindowExistsFlag = GL_TRUE;
355   old_handler = XSetErrorHandler(window_exists_err_handler);
356   XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
357   XSetErrorHandler(old_handler);
358   return WindowExistsFlag;
359}
360#endif
361
362
363
364/**********************************************************************/
365/*****                Linked list of XMesaBuffers                 *****/
366/**********************************************************************/
367
368static XMesaBuffer XMesaBufferList = NULL;
369
370
371/* Allocate a new XMesaBuffer, add to linked list */
372static XMesaBuffer alloc_xmesa_buffer(void)
373{
374   XMesaBuffer b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
375   if (b) {
376      b->Next = XMesaBufferList;
377      XMesaBufferList = b;
378   }
379   return b;
380}
381
382
383/*
384 * Find an XMesaBuffer by matching X display and colormap but NOT matching
385 * the notThis buffer.
386 */
387static XMesaBuffer find_xmesa_buffer(XMesaDisplay *dpy,
388                                     XMesaColormap cmap,
389                                     XMesaBuffer notThis)
390{
391   XMesaBuffer b;
392   for (b=XMesaBufferList; b; b=b->Next) {
393      if (b->display==dpy && b->cmap==cmap && b!=notThis) {
394         return b;
395      }
396   }
397   return NULL;
398}
399
400
401/*
402 * Free an XMesaBuffer, remove from linked list, perhaps free X colormap
403 * entries.
404 */
405static void free_xmesa_buffer(int client, XMesaBuffer buffer)
406{
407   XMesaBuffer prev = NULL, b;
408   (void) client;
409   for (b=XMesaBufferList; b; b=b->Next) {
410      if (b==buffer) {
411         /* unlink bufer from list */
412         if (prev)
413            prev->Next = buffer->Next;
414         else
415            XMesaBufferList = buffer->Next;
416         /* Check to free X colors */
417         if (buffer->num_alloced>0) {
418            /* If no other buffer uses this X colormap then free the colors. */
419            if (!find_xmesa_buffer(buffer->display, buffer->cmap, buffer)) {
420#ifdef XFree86Server
421               (void)FreeColors(buffer->cmap, client,
422				buffer->num_alloced, buffer->alloced_colors,
423				0);
424#else
425               XFreeColors(buffer->display, buffer->cmap,
426                           buffer->alloced_colors, buffer->num_alloced, 0);
427#endif
428            }
429         }
430
431         _mesa_free_framebuffer_data(&buffer->mesa_buffer);
432         FREE(buffer);
433
434         return;
435      }
436      /* continue search */
437      prev = b;
438   }
439   /* buffer not found in XMesaBufferList */
440   _mesa_problem(NULL,"free_xmesa_buffer() - buffer not found\n");
441}
442
443
444/* Copy X color table stuff from one XMesaBuffer to another. */
445static void copy_colortable_info(XMesaBuffer dst, const XMesaBuffer src)
446{
447   MEMCPY(dst->color_table, src->color_table, sizeof(src->color_table));
448   MEMCPY(dst->pixel_to_r, src->pixel_to_r, sizeof(src->pixel_to_r));
449   MEMCPY(dst->pixel_to_g, src->pixel_to_g, sizeof(src->pixel_to_g));
450   MEMCPY(dst->pixel_to_b, src->pixel_to_b, sizeof(src->pixel_to_b));
451   dst->num_alloced = src->num_alloced;
452   MEMCPY(dst->alloced_colors, src->alloced_colors,
453          sizeof(src->alloced_colors));
454}
455
456
457
458/**********************************************************************/
459/*****                   Misc Private Functions                   *****/
460/**********************************************************************/
461
462
463/*
464 * Return number of bits set in n.
465 */
466static int bitcount( unsigned long n )
467{
468   int bits;
469   for (bits=0; n>0; n=n>>1) {
470      if (n&1) {
471         bits++;
472      }
473   }
474   return bits;
475}
476
477
478
479/*
480 * Allocate a shared memory XImage back buffer for the given XMesaBuffer.
481 * Return:  GL_TRUE if success, GL_FALSE if error
482 */
483#ifndef XFree86Server
484static GLboolean alloc_shm_back_buffer( XMesaBuffer b )
485{
486#ifdef USE_XSHM
487   /*
488    * We have to do a _lot_ of error checking here to be sure we can
489    * really use the XSHM extension.  It seems different servers trigger
490    * errors at different points if the extension won't work.  Therefore
491    * we have to be very careful...
492    */
493   GC gc;
494   int (*old_handler)( XMesaDisplay *, XErrorEvent * );
495
496   b->backimage = XShmCreateImage( b->xm_visual->display,
497                                   b->xm_visual->visinfo->visual,
498                                   b->xm_visual->visinfo->depth,
499				   ZPixmap, NULL, &b->shminfo,
500				   b->width, b->height );
501   if (b->backimage == NULL) {
502      error("alloc_back_buffer: Shared memory error (XShmCreateImage), disabling.");
503      b->shm = 0;
504      return GL_FALSE;
505   }
506
507   b->shminfo.shmid = shmget( IPC_PRIVATE, b->backimage->bytes_per_line
508			     * b->backimage->height, IPC_CREAT|0777 );
509   if (b->shminfo.shmid < 0) {
510      if (getenv("MESA_DEBUG"))
511          perror("alloc_back_buffer");
512      XDestroyImage( b->backimage );
513      b->backimage = NULL;
514      error("alloc_back_buffer: Shared memory error (shmget), disabling.");
515      b->shm = 0;
516      return GL_FALSE;
517   }
518
519   b->shminfo.shmaddr = b->backimage->data
520                      = (char*)shmat( b->shminfo.shmid, 0, 0 );
521   if (b->shminfo.shmaddr == (char *) -1) {
522      if (getenv("MESA_DEBUG"))
523          perror("alloc_back_buffer");
524      XDestroyImage( b->backimage );
525      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
526      b->backimage = NULL;
527      error("alloc_back_buffer: Shared memory error (shmat), disabling.");
528      b->shm = 0;
529      return GL_FALSE;
530   }
531
532   b->shminfo.readOnly = False;
533   mesaXErrorFlag = 0;
534   old_handler = XSetErrorHandler( mesaHandleXError );
535   /* This may trigger the X protocol error we're ready to catch: */
536   XShmAttach( b->xm_visual->display, &b->shminfo );
537   XSync( b->xm_visual->display, False );
538
539   if (mesaXErrorFlag) {
540      /* we are on a remote display, this error is normal, don't print it */
541      XFlush( b->xm_visual->display );
542      mesaXErrorFlag = 0;
543      XDestroyImage( b->backimage );
544      shmdt( b->shminfo.shmaddr );
545      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
546      b->backimage = NULL;
547      b->shm = 0;
548      (void) XSetErrorHandler( old_handler );
549      return GL_FALSE;
550   }
551
552   shmctl( b->shminfo.shmid, IPC_RMID, 0 ); /* nobody else needs it */
553
554   /* Finally, try an XShmPutImage to be really sure the extension works */
555   gc = XCreateGC( b->xm_visual->display, b->frontbuffer, 0, NULL );
556   XShmPutImage( b->xm_visual->display, b->frontbuffer, gc,
557		 b->backimage, 0, 0, 0, 0, 1, 1 /*one pixel*/, False );
558   XSync( b->xm_visual->display, False );
559   XFreeGC( b->xm_visual->display, gc );
560   (void) XSetErrorHandler( old_handler );
561   if (mesaXErrorFlag) {
562      XFlush( b->xm_visual->display );
563      mesaXErrorFlag = 0;
564      XDestroyImage( b->backimage );
565      shmdt( b->shminfo.shmaddr );
566      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
567      b->backimage = NULL;
568      b->shm = 0;
569      return GL_FALSE;
570   }
571
572   if (b->backimage) {
573      int height = b->backimage->height;
574      /* Needed by PIXELADDR1 macro */
575      b->ximage_width1 = b->backimage->bytes_per_line;
576      b->ximage_origin1 = (GLubyte *) b->backimage->data
577                        + b->ximage_width1 * (height-1);
578      /* Needed by PIXELADDR2 macro */
579      b->ximage_width2 = b->backimage->bytes_per_line / 2;
580      b->ximage_origin2 = (GLushort *) b->backimage->data
581                        + b->ximage_width2 * (height-1);
582      /* Needed by PIXELADDR3 macro */
583      b->ximage_width3 = b->backimage->bytes_per_line;
584      b->ximage_origin3 = (GLubyte *) b->backimage->data
585                        + b->ximage_width3 * (height-1);
586      /* Needed by PIXELADDR4 macro */
587      b->ximage_width4 = b->backimage->width;
588      b->ximage_origin4 = (GLuint *) b->backimage->data
589                        + b->ximage_width4 * (height-1);
590   }
591
592   return GL_TRUE;
593#else
594   /* Can't compile XSHM support */
595   return GL_FALSE;
596#endif
597}
598#endif
599
600
601
602/*
603 * Setup an off-screen pixmap or Ximage to use as the back buffer.
604 * Input:  b - the X/Mesa buffer
605 */
606void xmesa_alloc_back_buffer( XMesaBuffer b )
607{
608   if (b->db_state==BACK_XIMAGE) {
609      /* Deallocate the old backimage, if any */
610      if (b->backimage) {
611#if defined(USE_XSHM) && !defined(XFree86Server)
612	 if (b->shm) {
613	    XShmDetach( b->xm_visual->display, &b->shminfo );
614	    XDestroyImage( b->backimage );
615	    shmdt( b->shminfo.shmaddr );
616	 }
617	 else
618#endif
619	   XMesaDestroyImage( b->backimage );
620	 b->backimage = NULL;
621      }
622
623      /* Allocate new back buffer */
624#ifdef XFree86Server
625      {
626	 /* Allocate a regular XImage for the back buffer. */
627	 b->backimage = XMesaCreateImage(b->xm_visual->BitsPerPixel,
628					 b->width, b->height, NULL);
629#else
630      if (b->shm==0
631	  || alloc_shm_back_buffer(b)==GL_FALSE
632	  ) {
633	 /* Allocate a regular XImage for the back buffer. */
634	 b->backimage = XCreateImage( b->xm_visual->display,
635                                      b->xm_visual->visinfo->visual,
636                                      GET_VISUAL_DEPTH(b->xm_visual),
637				      ZPixmap, 0,   /* format, offset */
638				      NULL, b->width, b->height,
639				      8, 0 );  /* pad, bytes_per_line */
640#endif
641	 if (!b->backimage) {
642	    error("alloc_back_buffer: XCreateImage failed.");
643	 }
644         b->backimage->data = (char *) MALLOC( b->backimage->height
645                                             * b->backimage->bytes_per_line );
646         if (!b->backimage->data) {
647            error("alloc_back_buffer: MALLOC failed.");
648            XMesaDestroyImage( b->backimage );
649            b->backimage = NULL;
650         }
651      }
652      b->backpixmap = None;
653   }
654   else if (b->db_state==BACK_PIXMAP) {
655      XMesaPixmap old_pixmap = b->backpixmap;
656      /* Free the old back pixmap */
657      if (b->backpixmap) {
658	 XMesaFreePixmap( b->xm_visual->display, b->backpixmap );
659      }
660      /* Allocate new back pixmap */
661      b->backpixmap = XMesaCreatePixmap( b->xm_visual->display, b->frontbuffer,
662					 b->width, b->height,
663					 GET_VISUAL_DEPTH(b->xm_visual) );
664      b->backimage = NULL;
665      /* update other references to backpixmap */
666      if (b->buffer==(XMesaDrawable)old_pixmap) {
667	 b->buffer = (XMesaDrawable)b->backpixmap;
668      }
669   }
670}
671
672
673
674/*
675 * A replacement for XAllocColor.  This function should never
676 * fail to allocate a color.  When XAllocColor fails, we return
677 * the nearest matching color.  If we have to allocate many colors
678 * this function isn't too efficient; the XQueryColors() could be
679 * done just once.
680 * Written by Michael Pichler, Brian Paul, Mark Kilgard
681 * Input:  dpy - X display
682 *         cmap - X colormap
683 *         cmapSize - size of colormap
684 * In/Out: color - the XColor struct
685 * Output:  exact - 1=exact color match, 0=closest match
686 *          alloced - 1=XAlloc worked, 0=XAlloc failed
687 */
688static void
689noFaultXAllocColor( int client,
690                    XMesaDisplay *dpy,
691                    XMesaColormap cmap,
692                    int cmapSize,
693                    XMesaColor *color,
694                    int *exact, int *alloced )
695{
696#ifdef XFree86Server
697   Pixel *ppixIn;
698   xrgb *ctable;
699#else
700   /* we'll try to cache ctable for better remote display performance */
701   static Display *prevDisplay = NULL;
702   static XMesaColormap prevCmap = 0;
703   static int prevCmapSize = 0;
704   static XMesaColor *ctable = NULL;
705#endif
706   XMesaColor subColor;
707   int i, bestmatch;
708   double mindist;       /* 3*2^16^2 exceeds long int precision. */
709
710   (void) client;
711
712   /* First try just using XAllocColor. */
713#ifdef XFree86Server
714   if (AllocColor(cmap,
715		  &color->red, &color->green, &color->blue,
716		  &color->pixel,
717		  client) == Success) {
718#else
719   if (XAllocColor(dpy, cmap, color)) {
720#endif
721      *exact = 1;
722      *alloced = 1;
723      return;
724   }
725
726   /* Alloc failed, search for closest match */
727
728   /* Retrieve color table entries. */
729   /* XXX alloca candidate. */
730#ifdef XFree86Server
731   ppixIn = (Pixel *) MALLOC(cmapSize * sizeof(Pixel));
732   ctable = (xrgb *) MALLOC(cmapSize * sizeof(xrgb));
733   for (i = 0; i < cmapSize; i++) {
734      ppixIn[i] = i;
735   }
736   QueryColors(cmap, cmapSize, ppixIn, ctable);
737#else
738   if (prevDisplay != dpy || prevCmap != cmap
739       || prevCmapSize != cmapSize || !ctable) {
740      /* free previously cached color table */
741      if (ctable)
742         FREE(ctable);
743      /* Get the color table from X */
744      ctable = (XMesaColor *) MALLOC(cmapSize * sizeof(XMesaColor));
745      assert(ctable);
746      for (i = 0; i < cmapSize; i++) {
747         ctable[i].pixel = i;
748      }
749      XQueryColors(dpy, cmap, ctable, cmapSize);
750      prevDisplay = dpy;
751      prevCmap = cmap;
752      prevCmapSize = cmapSize;
753   }
754#endif
755
756   /* Find best match. */
757   bestmatch = -1;
758   mindist = 0.0;
759   for (i = 0; i < cmapSize; i++) {
760      double dr = 0.30 * ((double) color->red - (double) ctable[i].red);
761      double dg = 0.59 * ((double) color->green - (double) ctable[i].green);
762      double db = 0.11 * ((double) color->blue - (double) ctable[i].blue);
763      double dist = dr * dr + dg * dg + db * db;
764      if (bestmatch < 0 || dist < mindist) {
765         bestmatch = i;
766         mindist = dist;
767      }
768   }
769
770   /* Return result. */
771   subColor.red   = ctable[bestmatch].red;
772   subColor.green = ctable[bestmatch].green;
773   subColor.blue  = ctable[bestmatch].blue;
774   /* Try to allocate the closest match color.  This should only
775    * fail if the cell is read/write.  Otherwise, we're incrementing
776    * the cell's reference count.
777    */
778#ifdef XFree86Server
779   if (AllocColor(cmap,
780		  &subColor.red, &subColor.green, &subColor.blue,
781		  &subColor.pixel,
782		  client) == Success) {
783#else
784   if (XAllocColor(dpy, cmap, &subColor)) {
785#endif
786      *alloced = 1;
787   }
788   else {
789      /* do this to work around a problem reported by Frank Ortega */
790      subColor.pixel = (unsigned long) bestmatch;
791      subColor.red   = ctable[bestmatch].red;
792      subColor.green = ctable[bestmatch].green;
793      subColor.blue  = ctable[bestmatch].blue;
794      subColor.flags = DoRed | DoGreen | DoBlue;
795      *alloced = 0;
796   }
797#ifdef XFree86Server
798   FREE(ppixIn);
799   FREE(ctable);
800#else
801   /* don't free table, save it for next time */
802#endif
803
804   *color = subColor;
805   *exact = 0;
806}
807
808
809
810
811/*
812 * Do setup for PF_GRAYSCALE pixel format.
813 * Note that buffer may be NULL.
814 */
815static GLboolean setup_grayscale( int client, XMesaVisual v,
816                                  XMesaBuffer buffer, XMesaColormap cmap )
817{
818   if (GET_VISUAL_DEPTH(v)<4 || GET_VISUAL_DEPTH(v)>16) {
819      return GL_FALSE;
820   }
821
822   if (buffer) {
823      XMesaBuffer prevBuffer;
824
825      if (!cmap) {
826         return GL_FALSE;
827      }
828
829      prevBuffer = find_xmesa_buffer(v->display, cmap, buffer);
830      if (prevBuffer &&
831          (buffer->xm_visual->mesa_visual.rgbMode ==
832           prevBuffer->xm_visual->mesa_visual.rgbMode)) {
833         /* Copy colormap stuff from previous XMesaBuffer which uses same
834          * X colormap.  Do this to avoid time spent in noFaultXAllocColor.
835          */
836         copy_colortable_info(buffer, prevBuffer);
837      }
838      else {
839         /* Allocate 256 shades of gray */
840         int gray;
841         int colorsfailed = 0;
842         for (gray=0;gray<256;gray++) {
843            GLint r = gamma_adjust( v->RedGamma,   gray, 255 );
844            GLint g = gamma_adjust( v->GreenGamma, gray, 255 );
845            GLint b = gamma_adjust( v->BlueGamma,  gray, 255 );
846            int exact, alloced;
847            XMesaColor xcol;
848            xcol.red   = (r << 8) | r;
849            xcol.green = (g << 8) | g;
850            xcol.blue  = (b << 8) | b;
851            noFaultXAllocColor( client, v->display,
852                                cmap, GET_COLORMAP_SIZE(v),
853                                &xcol, &exact, &alloced );
854            if (!exact) {
855               colorsfailed++;
856            }
857            if (alloced) {
858               assert(buffer->num_alloced<256);
859               buffer->alloced_colors[buffer->num_alloced] = xcol.pixel;
860               buffer->num_alloced++;
861            }
862
863            /*OLD
864            assert(gray < 576);
865            buffer->color_table[gray*3+0] = xcol.pixel;
866            buffer->color_table[gray*3+1] = xcol.pixel;
867            buffer->color_table[gray*3+2] = xcol.pixel;
868            assert(xcol.pixel < 65536);
869            buffer->pixel_to_r[xcol.pixel] = gray * 30 / 100;
870            buffer->pixel_to_g[xcol.pixel] = gray * 59 / 100;
871            buffer->pixel_to_b[xcol.pixel] = gray * 11 / 100;
872            */
873            buffer->color_table[gray] = xcol.pixel;
874            assert(xcol.pixel < 65536);
875            buffer->pixel_to_r[xcol.pixel] = gray;
876            buffer->pixel_to_g[xcol.pixel] = gray;
877            buffer->pixel_to_b[xcol.pixel] = gray;
878         }
879
880         if (colorsfailed && getenv("MESA_DEBUG")) {
881            fprintf( stderr,
882                  "Note: %d out of 256 needed colors do not match exactly.\n",
883                  colorsfailed );
884         }
885      }
886   }
887
888   v->dithered_pf = PF_GRAYSCALE;
889   v->undithered_pf = PF_GRAYSCALE;
890   return GL_TRUE;
891}
892
893
894
895/*
896 * Setup RGB rendering for a window with a PseudoColor, StaticColor,
897 * or 8-bit TrueColor visual visual.  We try to allocate a palette of 225
898 * colors (5 red, 9 green, 5 blue) and dither to approximate a 24-bit RGB
899 * color.  While this function was originally designed just for 8-bit
900 * visuals, it has also proven to work from 4-bit up to 16-bit visuals.
901 * Dithering code contributed by Bob Mercier.
902 */
903static GLboolean setup_dithered_color( int client, XMesaVisual v,
904                                       XMesaBuffer buffer, XMesaColormap cmap )
905{
906   if (GET_VISUAL_DEPTH(v)<4 || GET_VISUAL_DEPTH(v)>16) {
907      return GL_FALSE;
908   }
909
910   if (buffer) {
911      XMesaBuffer prevBuffer;
912
913      if (!cmap) {
914         return GL_FALSE;
915      }
916
917      prevBuffer = find_xmesa_buffer(v->display, cmap, buffer);
918      if (prevBuffer &&
919          (buffer->xm_visual->mesa_visual.rgbMode ==
920           prevBuffer->xm_visual->mesa_visual.rgbMode)) {
921         /* Copy colormap stuff from previous, matching XMesaBuffer.
922          * Do this to avoid time spent in noFaultXAllocColor.
923          */
924         copy_colortable_info(buffer, prevBuffer);
925      }
926      else {
927         /* Allocate X colors and initialize color_table[], red_table[], etc */
928         int r, g, b, i;
929         int colorsfailed = 0;
930         for (r = 0; r < _R; r++) {
931            for (g = 0; g < _G; g++) {
932               for (b = 0; b < _B; b++) {
933                  XMesaColor xcol;
934                  int exact, alloced;
935                  xcol.red  =gamma_adjust(v->RedGamma,   r*65535/(_R-1),65535);
936                  xcol.green=gamma_adjust(v->GreenGamma, g*65535/(_G-1),65535);
937                  xcol.blue =gamma_adjust(v->BlueGamma,  b*65535/(_B-1),65535);
938                  noFaultXAllocColor( client, v->display,
939                                      cmap, GET_COLORMAP_SIZE(v),
940                                      &xcol, &exact, &alloced );
941                  if (!exact) {
942                     colorsfailed++;
943                  }
944                  if (alloced) {
945                     assert(buffer->num_alloced<256);
946                     buffer->alloced_colors[buffer->num_alloced] = xcol.pixel;
947                     buffer->num_alloced++;
948                  }
949                  i = _MIX( r, g, b );
950                  assert(i < 576);
951                  buffer->color_table[i] = xcol.pixel;
952                  assert(xcol.pixel < 65536);
953                  buffer->pixel_to_r[xcol.pixel] = r * 255 / (_R-1);
954                  buffer->pixel_to_g[xcol.pixel] = g * 255 / (_G-1);
955                  buffer->pixel_to_b[xcol.pixel] = b * 255 / (_B-1);
956               }
957            }
958         }
959
960         if (colorsfailed && getenv("MESA_DEBUG")) {
961            fprintf( stderr,
962                  "Note: %d out of %d needed colors do not match exactly.\n",
963                  colorsfailed, _R*_G*_B );
964         }
965      }
966   }
967
968   v->dithered_pf = PF_DITHER;
969   v->undithered_pf = PF_LOOKUP;
970   return GL_TRUE;
971}
972
973
974/*
975 * Setup for Hewlett Packard Color Recovery 8-bit TrueColor mode.
976 * HPCR simulates 24-bit color fidelity with an 8-bit frame buffer.
977 * Special dithering tables have to be initialized.
978 */
979static void setup_8bit_hpcr( XMesaVisual v )
980{
981   /* HP Color Recovery contributed by:  Alex De Bruyn (ad@lms.be)
982    * To work properly, the atom _HP_RGB_SMOOTH_MAP_LIST must be defined
983    * on the root window AND the colormap obtainable by XGetRGBColormaps
984    * for that atom must be set on the window.  (see also tkInitWindow)
985    * If that colormap is not set, the output will look stripy.
986    */
987
988   /* Setup color tables with gamma correction */
989   int i;
990   double g;
991
992   g = 1.0 / v->RedGamma;
993   for (i=0; i<256; i++) {
994      GLint red = IROUND_POS(255.0 * pow( hpcr_rgbTbl[0][i]/255.0, g ));
995      v->hpcr_rgbTbl[0][i] = CLAMP( red, 16, 239 );
996   }
997
998   g = 1.0 / v->GreenGamma;
999   for (i=0; i<256; i++) {
1000      GLint green = IROUND_POS(255.0 * pow( hpcr_rgbTbl[1][i]/255.0, g ));
1001      v->hpcr_rgbTbl[1][i] = CLAMP( green, 16, 239 );
1002   }
1003
1004   g = 1.0 / v->BlueGamma;
1005   for (i=0; i<256; i++) {
1006      GLint blue = IROUND_POS(255.0 * pow( hpcr_rgbTbl[2][i]/255.0, g ));
1007      v->hpcr_rgbTbl[2][i] = CLAMP( blue, 32, 223 );
1008   }
1009   v->undithered_pf = PF_HPCR;  /* can't really disable dithering for now */
1010   v->dithered_pf = PF_HPCR;
1011
1012   /* which method should I use to clear */
1013   /* GL_FALSE: keep the ordinary method  */
1014   /* GL_TRUE : clear with dither pattern */
1015   v->hpcr_clear_flag = getenv("MESA_HPCR_CLEAR") ? GL_TRUE : GL_FALSE;
1016
1017   if (v->hpcr_clear_flag) {
1018      v->hpcr_clear_pixmap = XMesaCreatePixmap(v->display,
1019                                               DefaultRootWindow(v->display),
1020                                               16, 2, 8);
1021#ifndef XFree86Server
1022      v->hpcr_clear_ximage = XGetImage(v->display, v->hpcr_clear_pixmap,
1023                                       0, 0, 16, 2, AllPlanes, ZPixmap);
1024#endif
1025   }
1026}
1027
1028
1029/*
1030 * Setup RGB rendering for a window with a True/DirectColor visual.
1031 */
1032static void setup_truecolor( XMesaVisual v, XMesaBuffer buffer,
1033                             XMesaColormap cmap )
1034{
1035   unsigned long rmask, gmask, bmask;
1036   (void) buffer;
1037   (void) cmap;
1038
1039   /* Compute red multiplier (mask) and bit shift */
1040   v->rshift = 0;
1041   rmask = GET_REDMASK(v);
1042   while ((rmask & 1)==0) {
1043      v->rshift++;
1044      rmask = rmask >> 1;
1045   }
1046
1047   /* Compute green multiplier (mask) and bit shift */
1048   v->gshift = 0;
1049   gmask = GET_GREENMASK(v);
1050   while ((gmask & 1)==0) {
1051      v->gshift++;
1052      gmask = gmask >> 1;
1053   }
1054
1055   /* Compute blue multiplier (mask) and bit shift */
1056   v->bshift = 0;
1057   bmask = GET_BLUEMASK(v);
1058   while ((bmask & 1)==0) {
1059      v->bshift++;
1060      bmask = bmask >> 1;
1061   }
1062
1063   /*
1064    * Compute component-to-pixel lookup tables and dithering kernel
1065    */
1066   {
1067      static GLubyte kernel[16] = {
1068          0*16,  8*16,  2*16, 10*16,
1069         12*16,  4*16, 14*16,  6*16,
1070          3*16, 11*16,  1*16,  9*16,
1071         15*16,  7*16, 13*16,  5*16,
1072      };
1073      GLint rBits = bitcount(rmask);
1074      GLint gBits = bitcount(gmask);
1075      GLint bBits = bitcount(bmask);
1076      GLint maxBits;
1077      GLuint i;
1078
1079      /* convert pixel components in [0,_mask] to RGB values in [0,255] */
1080      for (i=0; i<=rmask; i++)
1081         v->PixelToR[i] = (unsigned char) ((i * 255) / rmask);
1082      for (i=0; i<=gmask; i++)
1083         v->PixelToG[i] = (unsigned char) ((i * 255) / gmask);
1084      for (i=0; i<=bmask; i++)
1085         v->PixelToB[i] = (unsigned char) ((i * 255) / bmask);
1086
1087      /* convert RGB values from [0,255] to pixel components */
1088
1089      for (i=0;i<256;i++) {
1090         GLint r = gamma_adjust(v->RedGamma,   i, 255);
1091         GLint g = gamma_adjust(v->GreenGamma, i, 255);
1092         GLint b = gamma_adjust(v->BlueGamma,  i, 255);
1093         v->RtoPixel[i] = (r >> (8-rBits)) << v->rshift;
1094         v->GtoPixel[i] = (g >> (8-gBits)) << v->gshift;
1095         v->BtoPixel[i] = (b >> (8-bBits)) << v->bshift;
1096      }
1097      /* overflow protection */
1098      for (i=256;i<512;i++) {
1099         v->RtoPixel[i] = v->RtoPixel[255];
1100         v->GtoPixel[i] = v->GtoPixel[255];
1101         v->BtoPixel[i] = v->BtoPixel[255];
1102      }
1103
1104      /* setup dithering kernel */
1105      maxBits = rBits;
1106      if (gBits > maxBits)  maxBits = gBits;
1107      if (bBits > maxBits)  maxBits = bBits;
1108      for (i=0;i<16;i++) {
1109         v->Kernel[i] = kernel[i] >> maxBits;
1110      }
1111
1112      v->undithered_pf = PF_TRUECOLOR;
1113      v->dithered_pf = (GET_VISUAL_DEPTH(v)<24) ? PF_TRUEDITHER : PF_TRUECOLOR;
1114   }
1115
1116   /*
1117    * Now check for TrueColor visuals which we can optimize.
1118    */
1119   if (   GET_REDMASK(v)  ==0x0000ff
1120       && GET_GREENMASK(v)==0x00ff00
1121       && GET_BLUEMASK(v) ==0xff0000
1122       && CHECK_BYTE_ORDER(v)
1123       && v->BitsPerPixel==32
1124       && sizeof(GLuint)==4
1125       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1126      /* common 32 bpp config used on SGI, Sun */
1127      v->undithered_pf = v->dithered_pf = PF_8A8B8G8R;
1128   }
1129   else if (GET_REDMASK(v)  ==0xff0000
1130       &&   GET_GREENMASK(v)==0x00ff00
1131       &&   GET_BLUEMASK(v) ==0x0000ff
1132       && CHECK_BYTE_ORDER(v)
1133       && v->BitsPerPixel==32
1134       && sizeof(GLuint)==4
1135       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1136      /* common 32 bpp config used on Linux, HP, IBM */
1137      v->undithered_pf = v->dithered_pf = PF_8R8G8B;
1138   }
1139   else if (GET_REDMASK(v)  ==0xff0000
1140       &&   GET_GREENMASK(v)==0x00ff00
1141       &&   GET_BLUEMASK(v) ==0x0000ff
1142       && CHECK_BYTE_ORDER(v)
1143       && v->BitsPerPixel==24
1144       && sizeof(GLuint)==4
1145       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1146      /* common packed 24 bpp config used on Linux */
1147      v->undithered_pf = v->dithered_pf = PF_8R8G8B24;
1148   }
1149   else if (GET_REDMASK(v)  ==0xf800
1150       &&   GET_GREENMASK(v)==0x07e0
1151       &&   GET_BLUEMASK(v) ==0x001f
1152       && CHECK_BYTE_ORDER(v)
1153       && v->BitsPerPixel==16
1154       && sizeof(GLushort)==2
1155       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1156      /* 5-6-5 color weight on common PC VGA boards */
1157      v->undithered_pf = PF_5R6G5B;
1158      v->dithered_pf = PF_DITHER_5R6G5B;
1159   }
1160   else if (GET_REDMASK(v)  ==0xe0
1161       &&   GET_GREENMASK(v)==0x1c
1162       &&   GET_BLUEMASK(v) ==0x03
1163       && CHECK_FOR_HPCR(v)) {
1164      setup_8bit_hpcr( v );
1165   }
1166}
1167
1168
1169
1170/*
1171 * Setup RGB rendering for a window with a monochrome visual.
1172 */
1173static void setup_monochrome( XMesaVisual v, XMesaBuffer b )
1174{
1175   (void) b;
1176   v->dithered_pf = v->undithered_pf = PF_1BIT;
1177   /* if black=1 then we must flip pixel values */
1178   v->bitFlip = (GET_BLACK_PIXEL(v) != 0);
1179}
1180
1181
1182
1183/*
1184 * When a context is "made current" for the first time, we can finally
1185 * finish initializing the context's visual and buffer information.
1186 * Input:  v - the XMesaVisual to initialize
1187 *         b - the XMesaBuffer to initialize (may be NULL)
1188 *         rgb_flag - TRUE = RGBA mode, FALSE = color index mode
1189 *         window - the window/pixmap we're rendering into
1190 *         cmap - the colormap associated with the window/pixmap
1191 * Return:  GL_TRUE=success, GL_FALSE=failure
1192 */
1193static GLboolean initialize_visual_and_buffer( int client,
1194                                               XMesaVisual v,
1195                                               XMesaBuffer b,
1196                                               GLboolean rgb_flag,
1197                                               XMesaDrawable window,
1198                                               XMesaColormap cmap
1199                                             )
1200{
1201#ifndef XFree86Server
1202   XGCValues gcvalues;
1203#endif
1204
1205   if (b) {
1206      assert(b->xm_visual == v);
1207   }
1208
1209   /* Save true bits/pixel */
1210   v->BitsPerPixel = GET_BITS_PER_PIXEL(v);
1211   assert(v->BitsPerPixel > 0);
1212
1213
1214   if (rgb_flag==GL_FALSE) {
1215      /* COLOR-INDEXED WINDOW:
1216       * Even if the visual is TrueColor or DirectColor we treat it as
1217       * being color indexed.  This is weird but might be useful to someone.
1218       */
1219      v->dithered_pf = v->undithered_pf = PF_INDEX;
1220      v->index_bits = GET_VISUAL_DEPTH(v);
1221   }
1222   else {
1223      /* RGB WINDOW:
1224       * We support RGB rendering into almost any kind of visual.
1225       */
1226      int xclass;
1227      xclass = GET_VISUAL_CLASS(v);
1228      if (xclass==TrueColor || xclass==DirectColor) {
1229	 setup_truecolor( v, b, cmap );
1230      }
1231      else if (xclass==StaticGray && GET_VISUAL_DEPTH(v)==1) {
1232	 setup_monochrome( v, b );
1233      }
1234      else if (xclass==GrayScale || xclass==StaticGray) {
1235         if (!setup_grayscale( client, v, b, cmap )) {
1236            return GL_FALSE;
1237         }
1238      }
1239      else if ((xclass==PseudoColor || xclass==StaticColor)
1240               && GET_VISUAL_DEPTH(v)>=4 && GET_VISUAL_DEPTH(v)<=16) {
1241	 if (!setup_dithered_color( client, v, b, cmap )) {
1242            return GL_FALSE;
1243         }
1244      }
1245      else {
1246	 error("XMesa: RGB mode rendering not supported in given visual.");
1247	 return GL_FALSE;
1248      }
1249      v->index_bits = 0;
1250
1251      if (getenv("MESA_NO_DITHER")) {
1252	 v->dithered_pf = v->undithered_pf;
1253      }
1254   }
1255
1256
1257   /*
1258    * If MESA_INFO env var is set print out some debugging info
1259    * which can help Brian figure out what's going on when a user
1260    * reports bugs.
1261    */
1262   if (getenv("MESA_INFO")) {
1263      fprintf(stderr, "X/Mesa visual = %p\n", v);
1264      fprintf(stderr, "X/Mesa dithered pf = %u\n", v->dithered_pf);
1265      fprintf(stderr, "X/Mesa undithered pf = %u\n", v->undithered_pf);
1266      fprintf(stderr, "X/Mesa level = %d\n", v->level);
1267      fprintf(stderr, "X/Mesa depth = %d\n", GET_VISUAL_DEPTH(v));
1268      fprintf(stderr, "X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
1269   }
1270
1271   if (b && window) {
1272      /* Do window-specific initializations */
1273
1274      /* Window dimensions */
1275      unsigned int w, h;
1276      get_drawable_size( v->display, window, &w, &h );
1277      b->width = w;
1278      b->height = h;
1279
1280      b->frontbuffer = window;
1281
1282      /* Setup for single/double buffering */
1283      if (v->mesa_visual.doubleBufferMode) {
1284         /* Double buffered */
1285#ifndef XFree86Server
1286         b->shm = check_for_xshm( v->display );
1287#endif
1288         xmesa_alloc_back_buffer( b );
1289         if (b->db_state==BACK_PIXMAP) {
1290            b->buffer = (XMesaDrawable)b->backpixmap;
1291         }
1292         else {
1293            b->buffer = XIMAGE;
1294         }
1295      }
1296      else {
1297         /* Single Buffered */
1298         b->buffer = b->frontbuffer;
1299      }
1300
1301      /* X11 graphics contexts */
1302#ifdef XFree86Server
1303      b->gc = CreateScratchGC(v->display, window->depth);
1304#else
1305      b->gc = XCreateGC( v->display, window, 0, NULL );
1306#endif
1307      XMesaSetFunction( v->display, b->gc, GXcopy );
1308
1309      /*
1310       * Don't generate Graphics Expose/NoExpose events in swapbuffers().
1311       * Patch contributed by Michael Pichler May 15, 1995.
1312       */
1313#ifdef XFree86Server
1314      b->cleargc = CreateScratchGC(v->display, window->depth);
1315      {
1316	  CARD32 v[1];
1317	  v[0] = FALSE;
1318	  dixChangeGC(NullClient, b->cleargc, GCGraphicsExposures, v, NULL);
1319      }
1320#else
1321      gcvalues.graphics_exposures = False;
1322      b->cleargc = XCreateGC( v->display, window,
1323                              GCGraphicsExposures, &gcvalues);
1324#endif
1325      XMesaSetFunction( v->display, b->cleargc, GXcopy );
1326      /*
1327       * Set fill style and tile pixmap once for all for HPCR stuff
1328       * (instead of doing it each time in clear_color_HPCR_pixmap())
1329       * Initialize whole stuff
1330       * Patch contributed by Jacques Leroy March 8, 1998.
1331       */
1332      if (v->hpcr_clear_flag && b->buffer!=XIMAGE) {
1333	int i;
1334	for (i=0; i<16; i++)
1335        {
1336	   XMesaPutPixel(v->hpcr_clear_ximage, i, 0, 0);
1337	   XMesaPutPixel(v->hpcr_clear_ximage, i, 1, 0);
1338        }
1339        XMesaPutImage(b->display, (XMesaDrawable)v->hpcr_clear_pixmap,
1340		      b->cleargc, v->hpcr_clear_ximage, 0, 0, 0, 0, 16, 2);
1341	XMesaSetFillStyle( v->display, b->cleargc, FillTiled);
1342	XMesaSetTile( v->display, b->cleargc, v->hpcr_clear_pixmap );
1343      }
1344
1345      /* Initialize the row buffer XImage for use in write_color_span() */
1346#ifdef XFree86Server
1347      b->rowimage = XMesaCreateImage(GET_VISUAL_DEPTH(v), MAX_WIDTH, 1,
1348				     (char *)MALLOC(MAX_WIDTH*4));
1349#else
1350      b->rowimage = XCreateImage( v->display,
1351                                  v->visinfo->visual,
1352                                  v->visinfo->depth,
1353                                  ZPixmap, 0,           /*format, offset*/
1354                                  (char*) MALLOC(MAX_WIDTH*4),  /*data*/
1355                                  MAX_WIDTH, 1,         /*width, height*/
1356                                  32,                   /*bitmap_pad*/
1357                                  0                     /*bytes_per_line*/ );
1358#endif
1359   }
1360
1361   return GL_TRUE;
1362}
1363
1364
1365
1366/*
1367 * Convert an RGBA color to a pixel value.
1368 */
1369unsigned long
1370xmesa_color_to_pixel( XMesaContext xmesa, GLubyte r, GLubyte g, GLubyte b, GLubyte a,
1371                      GLuint pixelFormat)
1372{
1373   switch (pixelFormat) {
1374      case PF_INDEX:
1375         return 0;
1376      case PF_TRUECOLOR:
1377         {
1378            unsigned long p;
1379            PACK_TRUECOLOR( p, r, g, b );
1380            return p;
1381         }
1382      case PF_8A8B8G8R:
1383         return PACK_8A8B8G8R( r, g, b, a );
1384      case PF_8R8G8B:
1385         /* fall through */
1386      case PF_8R8G8B24:
1387         return PACK_8R8G8B( r, g, b );
1388      case PF_5R6G5B:
1389         return PACK_5R6G5B( r, g, b );
1390      case PF_DITHER:
1391         {
1392            DITHER_SETUP;
1393            return DITHER( 1, 0, r, g, b );
1394         }
1395      case PF_1BIT:
1396         /* 382 = (3*255)/2 */
1397         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
1398      case PF_HPCR:
1399         return DITHER_HPCR(1, 1, r, g, b);
1400      case PF_LOOKUP:
1401         {
1402            LOOKUP_SETUP;
1403            return LOOKUP( r, g, b );
1404         }
1405      case PF_GRAYSCALE:
1406         return GRAY_RGB( r, g, b );
1407      case PF_TRUEDITHER:
1408         /* fall through */
1409      case PF_DITHER_5R6G5B:
1410         {
1411            unsigned long p;
1412            PACK_TRUEDITHER(p, 1, 0, r, g, b);
1413            return p;
1414         }
1415      default:
1416         _mesa_problem(NULL, "Bad pixel format in xmesa_color_to_pixel");
1417   }
1418   return 0;
1419}
1420
1421
1422/**********************************************************************/
1423/*****                       Public Functions                     *****/
1424/**********************************************************************/
1425
1426
1427/*
1428 * Create a new X/Mesa visual.
1429 * Input:  display - X11 display
1430 *         visinfo - an XVisualInfo pointer
1431 *         rgb_flag - GL_TRUE = RGB mode,
1432 *                    GL_FALSE = color index mode
1433 *         alpha_flag - alpha buffer requested?
1434 *         db_flag - GL_TRUE = double-buffered,
1435 *                   GL_FALSE = single buffered
1436 *         stereo_flag - stereo visual?
1437 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
1438 *                       GL_FALSE = use an off-screen pixmap for back buffer
1439 *         depth_size - requested bits/depth values, or zero
1440 *         stencil_size - requested bits/stencil values, or zero
1441 *         accum_red_size - requested bits/red accum values, or zero
1442 *         accum_green_size - requested bits/green accum values, or zero
1443 *         accum_blue_size - requested bits/blue accum values, or zero
1444 *         accum_alpha_size - requested bits/alpha accum values, or zero
1445 *         num_samples - number of samples/pixel if multisampling, or zero
1446 *         level - visual level, usually 0
1447 *         visualCaveat - ala the GLX extension, usually GLX_NONE_EXT
1448 * Return;  a new XMesaVisual or 0 if error.
1449 */
1450XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
1451                               XMesaVisualInfo visinfo,
1452                               GLboolean rgb_flag,
1453                               GLboolean alpha_flag,
1454                               GLboolean db_flag,
1455                               GLboolean stereo_flag,
1456                               GLboolean ximage_flag,
1457                               GLint depth_size,
1458                               GLint stencil_size,
1459                               GLint accum_red_size,
1460                               GLint accum_green_size,
1461                               GLint accum_blue_size,
1462                               GLint accum_alpha_size,
1463                               GLint num_samples,
1464                               GLint level,
1465                               GLint visualCaveat )
1466{
1467   char *gamma;
1468   XMesaVisual v;
1469   GLint red_bits, green_bits, blue_bits, alpha_bits;
1470
1471   /* For debugging only */
1472   if (getenv("MESA_XSYNC")) {
1473      /* This makes debugging X easier.
1474       * In your debugger, set a breakpoint on _XError to stop when an
1475       * X protocol error is generated.
1476       */
1477#ifdef XFree86Server
1478      /* NOT_NEEDED */
1479#else
1480      XSynchronize( display, 1 );
1481#endif
1482   }
1483
1484   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
1485   if (!v) {
1486      return NULL;
1487   }
1488
1489   /*
1490    * In the X server, NULL is passed in for the display.  It will have
1491    * to be set before using this visual.  See XMesaSetVisualDisplay()
1492    * below.
1493    */
1494   v->display = display;
1495
1496   /* Save a copy of the XVisualInfo struct because the user may XFREE()
1497    * the struct but we may need some of the information contained in it
1498    * at a later time.
1499    */
1500#ifdef XFree86Server
1501   v->visinfo = visinfo;
1502#else
1503   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
1504   if(!v->visinfo) {
1505      FREE(v);
1506      return NULL;
1507   }
1508   MEMCPY(v->visinfo, visinfo, sizeof(*visinfo));
1509
1510   /* Save a copy of the pointer now so we can find this visual again
1511    * if we need to search for it in find_glx_visual().
1512    */
1513   v->vishandle = visinfo;
1514#endif
1515
1516#ifdef XFree86Server
1517   /* Initialize the depth of the screen */
1518   {
1519       PixmapFormatRec *format;
1520
1521       for (format = screenInfo.formats;
1522	    format->depth != display->rootDepth;
1523	    format++)
1524	   ;
1525       v->screen_depth = format->bitsPerPixel;
1526   }
1527#endif
1528
1529   /* check for MESA_GAMMA environment variable */
1530   gamma = getenv("MESA_GAMMA");
1531   if (gamma) {
1532      v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
1533      sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
1534      if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
1535      if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
1536      if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
1537   }
1538   else {
1539      v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
1540   }
1541
1542   v->ximage_flag = ximage_flag;
1543   v->level = level;
1544   v->VisualCaveat = visualCaveat;
1545
1546   (void) initialize_visual_and_buffer( 0, v, NULL, rgb_flag, 0, 0 );
1547
1548   {
1549      int xclass;
1550      xclass = GET_VISUAL_CLASS(v);
1551      if (xclass==TrueColor || xclass==DirectColor) {
1552         red_bits   = bitcount(GET_REDMASK(v));
1553         green_bits = bitcount(GET_GREENMASK(v));
1554         blue_bits  = bitcount(GET_BLUEMASK(v));
1555         alpha_bits = 0;
1556      }
1557      else {
1558         /* this is an approximation */
1559         int depth;
1560         depth = GET_VISUAL_DEPTH(v);
1561         red_bits = depth / 3;
1562         depth -= red_bits;
1563         green_bits = depth / 2;
1564         depth -= green_bits;
1565         blue_bits = depth;
1566         alpha_bits = 0;
1567         assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
1568      }
1569   }
1570
1571   if (alpha_flag && alpha_bits == 0)
1572      alpha_bits = 8;
1573
1574   _mesa_initialize_visual( &v->mesa_visual,
1575                            rgb_flag, db_flag, stereo_flag,
1576                            red_bits, green_bits,
1577                            blue_bits, alpha_bits,
1578                            v->index_bits,
1579                            depth_size,
1580                            stencil_size,
1581                            accum_red_size, accum_green_size,
1582                            accum_blue_size, accum_alpha_size,
1583                            0 );
1584   return v;
1585}
1586
1587
1588void XMesaSetVisualDisplay( XMesaDisplay *dpy, XMesaVisual v )
1589{
1590    v->display = dpy;
1591}
1592
1593
1594void XMesaDestroyVisual( XMesaVisual v )
1595{
1596#ifndef XFree86Server
1597   FREE(v->visinfo);
1598#endif
1599   FREE(v);
1600}
1601
1602
1603
1604/*
1605 * Create a new XMesaContext.
1606 * Input:  v - XMesaVisual
1607 *         share_list - another XMesaContext with which to share display
1608 *                      lists or NULL if no sharing is wanted.
1609 * Return:  an XMesaContext or NULL if error.
1610 */
1611XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
1612{
1613   XMesaContext c;
1614   GLcontext *ctx;
1615   GLboolean direct = GL_TRUE; /* XXXX */
1616   /* NOT_DONE: should this be GL_FALSE??? */
1617   static GLboolean firstTime = GL_TRUE;
1618
1619   if (firstTime) {
1620      _glthread_INIT_MUTEX(_xmesa_lock);
1621      firstTime = GL_FALSE;
1622   }
1623
1624   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
1625   if (!c) {
1626      return NULL;
1627   }
1628
1629   ctx = c->gl_ctx = _mesa_create_context( &v->mesa_visual,
1630                      share_list ? share_list->gl_ctx : (GLcontext *) NULL,
1631                      (void *) c, direct );
1632   if (!c->gl_ctx) {
1633      FREE(c);
1634      return NULL;
1635   }
1636
1637   _mesa_enable_sw_extensions(ctx);
1638   _mesa_enable_1_3_extensions(ctx);
1639   ctx->Driver.BaseCompressedTexFormat = _mesa_base_compressed_texformat;
1640   ctx->Driver.CompressedTextureSize = _mesa_compressed_texture_size;
1641   ctx->Driver.GetCompressedTexImage = _mesa_get_compressed_teximage;
1642
1643   if (CHECK_BYTE_ORDER(v)) {
1644      c->swapbytes = GL_FALSE;
1645   }
1646   else {
1647      c->swapbytes = GL_TRUE;
1648   }
1649
1650   c->xm_visual = v;
1651   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
1652   c->display = v->display;
1653   c->pixelformat = v->dithered_pf;      /* Dithering is enabled by default */
1654
1655   ctx->Driver.UpdateState = xmesa_update_state;
1656
1657   /* Initialize the software rasterizer and helper modules.
1658    */
1659   _swrast_CreateContext( ctx );
1660   _ac_CreateContext( ctx );
1661   _tnl_CreateContext( ctx );
1662   _swsetup_CreateContext( ctx );
1663
1664   xmesa_register_swrast_functions( ctx );
1665
1666   /* Set up some constant pointers:
1667    */
1668   xmesa_init_pointers( ctx );
1669
1670
1671   /* Run the config file
1672    */
1673   _mesa_read_config_file( ctx );
1674
1675
1676   return c;
1677}
1678
1679
1680
1681
1682void XMesaDestroyContext( XMesaContext c )
1683{
1684#ifdef FX
1685   if (c->xm_buffer && c->xm_buffer->FXctx)
1686      fxMesaDestroyContext(c->xm_buffer->FXctx);
1687#endif
1688   if (c->gl_ctx) {
1689      _swsetup_DestroyContext( c->gl_ctx );
1690      _swrast_DestroyContext( c->gl_ctx );
1691      _tnl_DestroyContext( c->gl_ctx );
1692      _ac_DestroyContext( c->gl_ctx );
1693      _mesa_destroy_context( c->gl_ctx );
1694   }
1695
1696   /*
1697    * XXX This code should really go away because the ancilliary data
1698    * associated with a window/pixmap should not go away just because
1699    * a context is destroyed.
1700    */
1701#if 0
1702   /* Destroy any buffers which are using this context.  If we don't
1703    * we may have dangling references.  Hmm, maybe we should just
1704    * set the buffer's context pointer to NULL instead of deleting it?
1705    * Let's see if we get any bug reports...
1706    * This contributed by Doug Rabson <dfr@calcaphon.com>
1707    */
1708   {
1709      XMesaBuffer b, next;
1710      for (b = XMesaBufferList; b; b = next) {
1711         next = b->Next;
1712         if (!b->pixmap_flag) {
1713#ifndef XFree86Server
1714            XSync(b->display, False);
1715#endif
1716            if (b->xm_context == c) {
1717               /* found a context created for this context */
1718               XMesaDestroyBuffer( b );
1719            }
1720         }
1721      }
1722   }
1723#endif
1724
1725   FREE( c );
1726}
1727
1728
1729
1730/*
1731 * XXX this isn't a public function!  It's a hack for the 3Dfx driver.
1732 * Create a new XMesaBuffer from an X window.
1733 * Input:  v - the XMesaVisual
1734 *         w - the window
1735 *         c - the context
1736 * Return:  new XMesaBuffer or NULL if error
1737 */
1738XMesaBuffer XMesaCreateWindowBuffer2( XMesaVisual v, XMesaWindow w,
1739                                      XMesaContext c )
1740{
1741#ifndef XFree86Server
1742   XWindowAttributes attr;
1743#endif
1744#ifdef FX
1745   char *fxEnvVar;
1746#endif
1747   int client = 0;
1748
1749   XMesaBuffer b = alloc_xmesa_buffer();
1750   if (!b) {
1751      return NULL;
1752   }
1753
1754   (void) c;
1755
1756#ifdef XFree86Server
1757   client = CLIENT_ID(((XMesaDrawable)w)->id);
1758#endif
1759
1760   assert(v);
1761
1762#ifdef XFree86Server
1763   if (GET_VISUAL_DEPTH(v) != ((XMesaDrawable)w)->depth) {
1764#else
1765   XGetWindowAttributes( v->display, w, &attr );
1766
1767   if (GET_VISUAL_DEPTH(v) != attr.depth) {
1768#endif
1769      if (getenv("MESA_DEBUG")) {
1770         fprintf(stderr, "XMesaCreateWindowBuffer: depth mismatch between visual and window!\n");
1771      }
1772      return NULL;
1773   }
1774
1775   b->xm_context = NULL; /* Associate no context with this buffer */
1776
1777   b->xm_visual = v;
1778   b->pixmap_flag = GL_FALSE;
1779   b->display = v->display;
1780#ifdef XFree86Server
1781   b->cmap = (ColormapPtr)LookupIDByType(wColormap(w), RT_COLORMAP);
1782#else
1783   if (attr.colormap) {
1784      b->cmap = attr.colormap;
1785   }
1786   else {
1787      if (getenv("MESA_DEBUG")) {
1788         fprintf(stderr, "Window %u has no colormap!\n", (unsigned int) w);
1789      }
1790      /* this is weird, a window w/out a colormap!? */
1791      /* OK, let's just allocate a new one and hope for the best */
1792      b->cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
1793   }
1794#endif
1795
1796   /* determine back buffer implementation */
1797   if (v->mesa_visual.doubleBufferMode) {
1798      if (v->ximage_flag) {
1799	 b->db_state = BACK_XIMAGE;
1800      }
1801      else {
1802	 b->db_state = BACK_PIXMAP;
1803      }
1804   }
1805   else {
1806      b->db_state = 0;
1807   }
1808
1809   _mesa_initialize_framebuffer(&b->mesa_buffer,
1810                                &v->mesa_visual,
1811                                v->mesa_visual.depthBits > 0,
1812                                v->mesa_visual.stencilBits > 0,
1813                                v->mesa_visual.accumRedBits > 0,
1814                                v->mesa_visual.alphaBits > 0 );
1815
1816   if (!initialize_visual_and_buffer( client, v, b, v->mesa_visual.rgbMode,
1817                                      (XMesaDrawable)w, b->cmap )) {
1818      free_xmesa_buffer(client, b);
1819      return NULL;
1820   }
1821
1822#ifdef FX
1823   fxEnvVar = getenv("MESA_GLX_FX");
1824   if (fxEnvVar) {
1825     if (fxEnvVar[0]!='d') {
1826       int attribs[100];
1827       int numAttribs = 0;
1828       int hw;
1829       if (v->mesa_visual.depthBits > 0) {
1830	 attribs[numAttribs++] = FXMESA_DEPTH_SIZE;
1831	 attribs[numAttribs++] = 1;
1832       }
1833       if (v->mesa_visual.doubleBufferMode) {
1834	 attribs[numAttribs++] = FXMESA_DOUBLEBUFFER;
1835       }
1836       if (v->mesa_visual.accumRedBits > 0) {
1837	 attribs[numAttribs++] = FXMESA_ACCUM_SIZE;
1838	 attribs[numAttribs++] = v->mesa_visual.accumRedBits;
1839       }
1840       if (v->mesa_visual.stencilBits > 0) {
1841         attribs[numAttribs++] = FXMESA_STENCIL_SIZE;
1842         attribs[numAttribs++] = v->mesa_visual.stencilBits;
1843       }
1844       if (v->mesa_visual.alphaBits > 0) {
1845         attribs[numAttribs++] = FXMESA_ALPHA_SIZE;
1846         attribs[numAttribs++] = 1;
1847       }
1848       if (c->gl_ctx) {
1849#define FXMESA_SHARE_CONTEXT 990099  /* keep in sync with fxapi.c! */
1850         attribs[numAttribs++] = FXMESA_SHARE_CONTEXT;
1851         attribs[numAttribs++] = (int) c->gl_ctx;
1852       }
1853       attribs[numAttribs++] = FXMESA_NONE;
1854
1855       if ((hw = fxQueryHardware())==GR_SSTTYPE_VOODOO) {
1856         b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1857         if ((v->undithered_pf!=PF_INDEX) && (b->backimage)) {
1858	   b->FXisHackUsable = b->FXctx ? GL_TRUE : GL_FALSE;
1859	   if (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')
1860	     b->FXwindowHack = b->FXctx ? GL_TRUE : GL_FALSE;
1861	   else
1862	     b->FXwindowHack = GL_FALSE;
1863         }
1864       }
1865       else {
1866         if (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')
1867	   b->FXctx = fxMesaCreateContext(w, GR_RESOLUTION_NONE,
1868					  GR_REFRESH_75Hz, attribs);
1869         else
1870	   b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1871         b->FXisHackUsable = GL_FALSE;
1872         b->FXwindowHack = GL_FALSE;
1873       }
1874       /*
1875       fprintf(stderr,
1876               "voodoo %d, wid %d height %d hack: usable %d active %d\n",
1877               hw, b->width, b->height, b->FXisHackUsable, b->FXwindowHack);
1878       */
1879     }
1880   }
1881   else {
1882      fprintf(stderr,"WARNING: This Mesa Library includes the Glide driver but\n");
1883      fprintf(stderr,"         you have not defined the MESA_GLX_FX env. var.\n");
1884      fprintf(stderr,"         (check the README.3DFX file for more information).\n\n");
1885      fprintf(stderr,"         you can disable this message with a 'export MESA_GLX_FX=disable'.\n");
1886   }
1887#endif
1888
1889   return b;
1890}
1891
1892
1893XMesaBuffer XMesaCreateWindowBuffer( XMesaVisual v, XMesaWindow w )
1894{
1895   return XMesaCreateWindowBuffer2( v, w, NULL );
1896}
1897
1898
1899/*
1900 * Create a new XMesaBuffer from an X pixmap.
1901 * Input:  v - the XMesaVisual
1902 *         p - the pixmap
1903 *         cmap - the colormap, may be 0 if using a TrueColor or DirectColor
1904 *                visual for the pixmap
1905 * Return:  new XMesaBuffer or NULL if error
1906 */
1907XMesaBuffer XMesaCreatePixmapBuffer( XMesaVisual v,
1908				     XMesaPixmap p, XMesaColormap cmap )
1909{
1910   int client = 0;
1911   XMesaBuffer b = alloc_xmesa_buffer();
1912   if (!b) {
1913      return NULL;
1914   }
1915
1916
1917#ifdef XFree86Server
1918   client = CLIENT_ID(((XMesaDrawable)p)->id);
1919#endif
1920
1921   assert(v);
1922
1923   b->xm_context = NULL; /* Associate no context with this buffer */
1924
1925   b->xm_visual = v;
1926   b->pixmap_flag = GL_TRUE;
1927   b->display = v->display;
1928   b->cmap = cmap;
1929
1930   /* determine back buffer implementation */
1931   if (v->mesa_visual.doubleBufferMode) {
1932      if (v->ximage_flag) {
1933	 b->db_state = BACK_XIMAGE;
1934      }
1935      else {
1936	 b->db_state = BACK_PIXMAP;
1937      }
1938   }
1939   else {
1940      b->db_state = 0;
1941   }
1942
1943   _mesa_initialize_framebuffer(&b->mesa_buffer,
1944                                &v->mesa_visual,
1945                                v->mesa_visual.depthBits > 0,
1946                                v->mesa_visual.stencilBits > 0,
1947                                v->mesa_visual.accumRedBits +
1948                                v->mesa_visual.accumGreenBits +
1949                                v->mesa_visual.accumBlueBits > 0,
1950                                v->mesa_visual.alphaBits > 0 );
1951
1952   if (!initialize_visual_and_buffer(client, v, b, v->mesa_visual.rgbMode,
1953				     (XMesaDrawable)p, cmap)) {
1954      free_xmesa_buffer(client, b);
1955      return NULL;
1956   }
1957
1958   return b;
1959}
1960
1961
1962
1963#if 0 /* not done */
1964XMesaBuffer XMesaCreatePBuffer( XMesaVisual v, XMesaColormap cmap,
1965                                unsigned int width, unsigned int height )
1966{
1967   int client = 0;
1968   XMesaBuffer b = alloc_xmesa_buffer();
1969   if (!b) {
1970      return NULL;
1971   }
1972
1973   b->xm_context = NULL; /* Associate no context with this buffer */
1974
1975   b->xm_visual = v;
1976   b->pbuffer_flag = GL_TRUE;
1977   b->display = v->display;
1978   b->cmap = cmap;
1979
1980   /* determine back buffer implementation */
1981   if (v->mesa_visual.doubleBufferMode) {
1982      if (v->ximage_flag) {
1983	 b->db_state = BACK_XIMAGE;
1984      }
1985      else {
1986	 b->db_state = BACK_PIXMAP;
1987      }
1988   }
1989   else {
1990      b->db_state = 0;
1991   }
1992
1993   _mesa_initialize_framebuffer(&b->mesa_buffer,
1994                                &v->mesa_visual,
1995                                v->mesa_visual.depthBits > 0,
1996                                v->mesa_visual.stencilBits > 0,
1997                                v->mesa_visual.accumRedBits +
1998                                v->mesa_visual.accumGreenBits +
1999                                v->mesa_visual.accumBlueBits > 0,
2000                                v->mesa_visual.alphaBits > 0 );
2001
2002   if (!initialize_visual_and_buffer(client, v, b, v->mesa_visual.rgbMode,
2003				     0, cmap)) {
2004      free_xmesa_buffer(client, b);
2005      return NULL;
2006   }
2007
2008   return b;
2009}
2010#endif
2011
2012
2013
2014/*
2015 * Deallocate an XMesaBuffer structure and all related info.
2016 */
2017void XMesaDestroyBuffer( XMesaBuffer b )
2018{
2019   int client = 0;
2020
2021#ifdef XFree86Server
2022   if (b->frontbuffer)
2023       client = CLIENT_ID(b->frontbuffer->id);
2024#endif
2025
2026   if (b->gc)  XMesaFreeGC( b->xm_visual->display, b->gc );
2027   if (b->cleargc)  XMesaFreeGC( b->xm_visual->display, b->cleargc );
2028
2029   if (b->backimage) {
2030#if defined(USE_XSHM) && !defined(XFree86Server)
2031       if (b->shm) {
2032	   XShmDetach( b->xm_visual->display, &b->shminfo );
2033	   XDestroyImage( b->backimage );
2034	   shmdt( b->shminfo.shmaddr );
2035       }
2036       else
2037#endif
2038	   XMesaDestroyImage( b->backimage );
2039   }
2040   if (b->backpixmap) {
2041      XMesaFreePixmap( b->xm_visual->display, b->backpixmap );
2042      if (b->xm_visual->hpcr_clear_flag) {
2043	XMesaFreePixmap( b->xm_visual->display,
2044			 b->xm_visual->hpcr_clear_pixmap );
2045	XMesaDestroyImage( b->xm_visual->hpcr_clear_ximage );
2046      }
2047   }
2048   if (b->rowimage) {
2049      FREE( b->rowimage->data );
2050      b->rowimage->data = NULL;
2051      XMesaDestroyImage( b->rowimage );
2052   }
2053
2054   if (b->xm_context)
2055      b->xm_context->xm_buffer = NULL;
2056
2057   free_xmesa_buffer(client, b);
2058}
2059
2060
2061
2062/*
2063 * Bind buffer b to context c and make c the current rendering context.
2064 */
2065GLboolean XMesaMakeCurrent( XMesaContext c, XMesaBuffer b )
2066{
2067   return XMesaMakeCurrent2( c, b, b );
2068}
2069
2070
2071/*
2072 * Bind buffer b to context c and make c the current rendering context.
2073 */
2074GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
2075                             XMesaBuffer readBuffer )
2076{
2077   if (c) {
2078      if (!drawBuffer || !readBuffer)
2079         return GL_FALSE;  /* must specify buffers! */
2080
2081#ifdef FX
2082      if (drawBuffer->FXctx) {
2083         fxMesaMakeCurrent(drawBuffer->FXctx);
2084
2085         /* Disassociate drawBuffer's current context from drawBuffer */
2086         if (drawBuffer->xm_context)
2087            drawBuffer->xm_context->xm_buffer = NULL;
2088
2089         /* Disassociate old buffer from this context */
2090         if (c->xm_buffer)
2091            c->xm_buffer->xm_context = NULL;
2092
2093         /* Associate the context with this buffer */
2094         drawBuffer->xm_context = c;
2095
2096         c->xm_buffer = drawBuffer;
2097         c->xm_read_buffer = readBuffer;
2098         c->use_read_buffer = (drawBuffer != readBuffer);
2099
2100         return GL_TRUE;
2101      }
2102#endif
2103      if (c->gl_ctx == _mesa_get_current_context()
2104          && c->xm_buffer == drawBuffer
2105          && c->xm_read_buffer == readBuffer
2106          && c->xm_buffer->wasCurrent) {
2107         /* same context and buffer, do nothing */
2108         return GL_TRUE;
2109      }
2110
2111      /* Disassociate drawBuffer's current context from drawBuffer */
2112      if (drawBuffer->xm_context)
2113         drawBuffer->xm_context->xm_buffer = NULL;
2114
2115      /* Disassociate old buffer with this context */
2116      if (c->xm_buffer)
2117	  c->xm_buffer->xm_context = NULL;
2118
2119      drawBuffer->xm_context = c; /* Associate the context with this buffer */
2120
2121      c->xm_buffer = drawBuffer;
2122      c->xm_read_buffer = readBuffer;
2123      c->use_read_buffer = (drawBuffer != readBuffer);
2124
2125      _mesa_make_current2(c->gl_ctx,
2126                          &drawBuffer->mesa_buffer,
2127                          &readBuffer->mesa_buffer);
2128
2129      if (c->gl_ctx->Viewport.Width == 0) {
2130	 /* initialize viewport to window size */
2131	 _mesa_Viewport( 0, 0, drawBuffer->width, drawBuffer->height );
2132	 c->gl_ctx->Scissor.Width = drawBuffer->width;
2133	 c->gl_ctx->Scissor.Height = drawBuffer->height;
2134      }
2135
2136      if (c->xm_visual->mesa_visual.rgbMode) {
2137         /*
2138          * Must recompute and set these pixel values because colormap
2139          * can be different for different windows.
2140          */
2141         c->clearpixel = xmesa_color_to_pixel( c,
2142                                               c->clearcolor[0],
2143                                               c->clearcolor[1],
2144                                               c->clearcolor[2],
2145                                               c->clearcolor[3],
2146                                               c->xm_visual->undithered_pf);
2147         XMesaSetForeground(c->display, c->xm_buffer->cleargc, c->clearpixel);
2148      }
2149
2150      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
2151      c->xm_buffer->wasCurrent = GL_TRUE;
2152   }
2153   else {
2154      /* Detach */
2155      _mesa_make_current2( NULL, NULL, NULL );
2156   }
2157   return GL_TRUE;
2158}
2159
2160
2161/*
2162 * Unbind the context c from its buffer.
2163 */
2164GLboolean XMesaUnbindContext( XMesaContext c )
2165{
2166   /* A no-op for XFree86 integration purposes */
2167   return GL_TRUE;
2168}
2169
2170
2171XMesaContext XMesaGetCurrentContext( void )
2172{
2173   GET_CURRENT_CONTEXT(ctx);
2174   if (ctx) {
2175      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2176      return xmesa;
2177   }
2178   else {
2179      return 0;
2180   }
2181}
2182
2183
2184XMesaBuffer XMesaGetCurrentBuffer( void )
2185{
2186   GET_CURRENT_CONTEXT(ctx);
2187   if (ctx) {
2188      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2189      return xmesa->xm_buffer;
2190   }
2191   else {
2192      return 0;
2193   }
2194}
2195
2196
2197/* New in Mesa 3.1 */
2198XMesaBuffer XMesaGetCurrentReadBuffer( void )
2199{
2200   GET_CURRENT_CONTEXT(ctx);
2201   if (ctx) {
2202      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2203      return xmesa->xm_buffer;
2204   }
2205   else {
2206      return 0;
2207   }
2208}
2209
2210
2211GLboolean XMesaForceCurrent(XMesaContext c)
2212{
2213   if (c) {
2214      if (c->gl_ctx != _mesa_get_current_context()) {
2215	 _mesa_make_current(c->gl_ctx, &c->xm_buffer->mesa_buffer);
2216      }
2217   }
2218   else {
2219      _mesa_make_current(NULL, NULL);
2220   }
2221   return GL_TRUE;
2222}
2223
2224
2225GLboolean XMesaLoseCurrent(XMesaContext c)
2226{
2227   (void) c;
2228   _mesa_make_current(NULL, NULL);
2229   return GL_TRUE;
2230}
2231
2232
2233/*
2234 * Switch 3Dfx support hack between window and full-screen mode.
2235 */
2236GLboolean XMesaSetFXmode( GLint mode )
2237{
2238#ifdef FX
2239   const char *fx = getenv("MESA_GLX_FX");
2240   if (fx && fx[0] != 'd') {
2241      GET_CURRENT_CONTEXT(ctx);
2242      GrHwConfiguration hw;
2243      if (!FX_grSstQueryHardware(&hw)) {
2244         /*fprintf(stderr, "!grSstQueryHardware\n");*/
2245         return GL_FALSE;
2246      }
2247      if (hw.num_sst < 1) {
2248         /*fprintf(stderr, "hw.num_sst < 1\n");*/
2249         return GL_FALSE;
2250      }
2251      if (ctx) {
2252         XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2253         if (mode == XMESA_FX_WINDOW) {
2254	    if (xmesa->xm_buffer->FXisHackUsable) {
2255	       FX_grSstControl(GR_CONTROL_DEACTIVATE);
2256	       xmesa->xm_buffer->FXwindowHack = GL_TRUE;
2257	       return GL_TRUE;
2258	    }
2259	 }
2260	 else if (mode == XMESA_FX_FULLSCREEN) {
2261	    FX_grSstControl(GR_CONTROL_ACTIVATE);
2262	    xmesa->xm_buffer->FXwindowHack = GL_FALSE;
2263	    return GL_TRUE;
2264	 }
2265	 else {
2266	    /* Error: Bad mode value */
2267	 }
2268      }
2269   }
2270   /*fprintf(stderr, "fallthrough\n");*/
2271#else
2272   (void) mode;
2273#endif
2274   return GL_FALSE;
2275}
2276
2277
2278
2279#ifdef FX
2280/*
2281 * Read image from VooDoo frame buffer into X/Mesa's back XImage.
2282 */
2283static void FXgetImage( XMesaBuffer b )
2284{
2285   static unsigned short pixbuf[MAX_WIDTH];
2286   GLuint x, y;
2287   int xpos, ypos;
2288   XMesaWindow root;
2289   unsigned int bw, depth, width, height;
2290   XMesaContext xmesa = (XMesaContext) b->xm_context->gl_ctx->DriverCtx;
2291
2292   assert(xmesa->xm_buffer->FXctx);
2293
2294#ifdef XFree86Server
2295   x = b->frontbuffer->x;
2296   y = b->frontbuffer->y;
2297   width = b->frontbuffer->width;
2298   height = b->frontbuffer->height;
2299   depth = b->frontbuffer->depth;
2300#else
2301   XGetGeometry( xmesa->xm_visual->display, b->frontbuffer,
2302                 &root, &xpos, &ypos, &width, &height, &bw, &depth);
2303#endif
2304   if (b->width != width || b->height != height) {
2305      b->width = MIN2((int)width, xmesa->xm_buffer->FXctx->width);
2306      b->height = MIN2((int)height, xmesa->xm_buffer->FXctx->height);
2307      if (b->width & 1)
2308         b->width--;  /* prevent odd width */
2309      xmesa_alloc_back_buffer( b );
2310   }
2311
2312   grLfbWriteColorFormat(GR_COLORFORMAT_ARGB);
2313   if (xmesa->xm_visual->undithered_pf==PF_5R6G5B) {
2314      /* Special case: 16bpp RGB */
2315      grLfbReadRegion( GR_BUFFER_FRONTBUFFER,       /* src buffer */
2316                       0, xmesa->xm_buffer->FXctx->height - b->height,  /*pos*/
2317                       b->width, b->height,         /* size */
2318                       b->width * sizeof(GLushort), /* stride */
2319                       b->backimage->data);         /* dest buffer */
2320   }
2321   else if (xmesa->xm_visual->dithered_pf==PF_DITHER
2322	    && GET_VISUAL_DEPTH(xmesa->xm_visual)==8) {
2323      /* Special case: 8bpp RGB */
2324      for (y=0;y<b->height;y++) {
2325         GLubyte *ptr = (GLubyte*) xmesa->xm_buffer->backimage->data
2326                        + xmesa->xm_buffer->backimage->bytes_per_line * y;
2327         XDITHER_SETUP(y);
2328
2329         /* read row from 3Dfx frame buffer */
2330         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2331                          0, xmesa->xm_buffer->FXctx->height-(b->height-y),
2332                          b->width, 1,
2333                          0,
2334                          pixbuf );
2335
2336         /* write to XImage back buffer */
2337         for (x=0;x<b->width;x++) {
2338            GLubyte r = (pixbuf[x] & 0xf800) >> 8;
2339            GLubyte g = (pixbuf[x] & 0x07e0) >> 3;
2340            GLubyte b = (pixbuf[x] & 0x001f) << 3;
2341            *ptr++ = XDITHER( x, r, g, b);
2342         }
2343      }
2344   }
2345   else {
2346      /* General case: slow! */
2347      for (y=0;y<b->height;y++) {
2348         /* read row from 3Dfx frame buffer */
2349         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2350                          0, xmesa->xm_buffer->FXctx->height-(b->height-y),
2351                          b->width, 1,
2352                          0,
2353                          pixbuf );
2354
2355         /* write to XImage back buffer */
2356         for (x=0;x<b->width;x++) {
2357            XMesaPutPixel(b->backimage,x,y,
2358			  xmesa_color_to_pixel(xmesa,
2359					       (pixbuf[x] & 0xf800) >> 8,
2360					       (pixbuf[x] & 0x07e0) >> 3,
2361					       (pixbuf[x] & 0x001f) << 3,
2362					       0xff, xmesa->pixelformat));
2363         }
2364      }
2365   }
2366   grLfbWriteColorFormat(GR_COLORFORMAT_ABGR);
2367}
2368#endif
2369
2370
2371/*
2372 * Copy the back buffer to the front buffer.  If there's no back buffer
2373 * this is a no-op.
2374 */
2375void XMesaSwapBuffers( XMesaBuffer b )
2376{
2377   GET_CURRENT_CONTEXT(ctx);
2378
2379   /* If we're swapping the buffer associated with the current context
2380    * we have to flush any pending rendering commands first.
2381    */
2382   if (b->xm_context && b->xm_context->gl_ctx == ctx)
2383      _mesa_swapbuffers(ctx);
2384
2385   if (b->db_state) {
2386#ifdef FX
2387      if (b->FXctx) {
2388         fxMesaSwapBuffers();
2389
2390         if (b->FXwindowHack)
2391            FXgetImage(b);
2392         else
2393            return;
2394      }
2395#endif
2396     if (b->backimage) {
2397	 /* Copy Ximage from host's memory to server's window */
2398#if defined(USE_XSHM) && !defined(XFree86Server)
2399	 if (b->shm) {
2400            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2401	    XShmPutImage( b->xm_visual->display, b->frontbuffer,
2402			  b->cleargc,
2403			  b->backimage, 0, 0,
2404			  0, 0, b->width, b->height, False );
2405            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2406	 }
2407	 else
2408#endif
2409         {
2410            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2411            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2412			   b->cleargc,
2413			   b->backimage, 0, 0,
2414			   0, 0, b->width, b->height );
2415            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2416         }
2417      }
2418      else {
2419	 /* Copy pixmap to window on server */
2420         /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2421	 XMesaCopyArea( b->xm_visual->display,
2422			b->backpixmap,   /* source drawable */
2423			b->frontbuffer,  /* dest. drawable */
2424			b->cleargc,
2425			0, 0, b->width, b->height,  /* source region */
2426			0, 0                 /* dest region */
2427		      );
2428         /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2429      }
2430   }
2431#if !defined(XFree86Server)
2432   XSync( b->xm_visual->display, False );
2433#endif
2434}
2435
2436
2437
2438/*
2439 * Copy sub-region of back buffer to front buffer
2440 */
2441void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
2442{
2443   GET_CURRENT_CONTEXT(ctx);
2444
2445   /* If we're swapping the buffer associated with the current context
2446    * we have to flush any pending rendering commands first.
2447    */
2448   if (b->xm_context->gl_ctx == ctx)
2449      _mesa_swapbuffers(ctx);
2450
2451   if (b->db_state) {
2452      int yTop = b->height - y - height;
2453#ifdef FX
2454      if (b->FXctx) {
2455         fxMesaSwapBuffers();
2456         if (b->FXwindowHack)
2457            FXgetImage(b);
2458         else
2459            return;
2460      }
2461#endif
2462      if (b->backimage) {
2463         /* Copy Ximage from host's memory to server's window */
2464#if defined(USE_XSHM) && !defined(XFree86Server)
2465         if (b->shm) {
2466            /* XXX assuming width and height aren't too large! */
2467            XShmPutImage( b->xm_visual->display, b->frontbuffer,
2468                          b->cleargc,
2469                          b->backimage, x, yTop,
2470                          x, yTop, width, height, False );
2471            /* wait for finished event??? */
2472         }
2473         else
2474#endif
2475         {
2476            /* XXX assuming width and height aren't too large! */
2477            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2478			   b->cleargc,
2479			   b->backimage, x, yTop,
2480			   x, yTop, width, height );
2481         }
2482      }
2483      else {
2484         /* Copy pixmap to window on server */
2485         XMesaCopyArea( b->xm_visual->display,
2486			b->backpixmap,           /* source drawable */
2487			b->frontbuffer,          /* dest. drawable */
2488			b->cleargc,
2489			x, yTop, width, height,  /* source region */
2490			x, yTop                  /* dest region */
2491                      );
2492      }
2493   }
2494}
2495
2496
2497/*
2498 * Return a pointer to the XMesa backbuffer Pixmap or XImage.  This function
2499 * is a way to get "under the hood" of X/Mesa so one can manipulate the
2500 * back buffer directly.
2501 * Output:  pixmap - pointer to back buffer's Pixmap, or 0
2502 *          ximage - pointer to back buffer's XImage, or NULL
2503 * Return:  GL_TRUE = context is double buffered
2504 *          GL_FALSE = context is single buffered
2505 */
2506GLboolean XMesaGetBackBuffer( XMesaBuffer b,
2507                              XMesaPixmap *pixmap,
2508                              XMesaImage **ximage )
2509{
2510   if (b->db_state) {
2511      if (pixmap)  *pixmap = b->backpixmap;
2512      if (ximage)  *ximage = b->backimage;
2513      return GL_TRUE;
2514   }
2515   else {
2516      *pixmap = 0;
2517      *ximage = NULL;
2518      return GL_FALSE;
2519   }
2520}
2521
2522
2523/*
2524 * Return the depth buffer associated with an XMesaBuffer.
2525 * Input:  b - the XMesa buffer handle
2526 * Output:  width, height - size of buffer in pixels
2527 *          bytesPerValue - bytes per depth value (2 or 4)
2528 *          buffer - pointer to depth buffer values
2529 * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
2530 */
2531GLboolean XMesaGetDepthBuffer( XMesaBuffer b, GLint *width, GLint *height,
2532                               GLint *bytesPerValue, void **buffer )
2533{
2534   if (!b->mesa_buffer.DepthBuffer) {
2535      *width = 0;
2536      *height = 0;
2537      *bytesPerValue = 0;
2538      *buffer = 0;
2539      return GL_FALSE;
2540   }
2541   else {
2542      *width = b->mesa_buffer.Width;
2543      *height = b->mesa_buffer.Height;
2544      *bytesPerValue = sizeof(GLdepth);
2545      *buffer = b->mesa_buffer.DepthBuffer;
2546      return GL_TRUE;
2547   }
2548}
2549
2550
2551void XMesaFlush( XMesaContext c )
2552{
2553   if (c && c->xm_visual) {
2554#ifdef XFree86Server
2555      /* NOT_NEEDED */
2556#else
2557      XSync( c->xm_visual->display, False );
2558#endif
2559   }
2560}
2561
2562
2563
2564const char *XMesaGetString( XMesaContext c, int name )
2565{
2566   (void) c;
2567   if (name==XMESA_VERSION) {
2568      return "3.5";
2569   }
2570   else if (name==XMESA_EXTENSIONS) {
2571      return "";
2572   }
2573   else {
2574      return NULL;
2575   }
2576}
2577
2578
2579
2580XMesaBuffer XMesaFindBuffer( XMesaDisplay *dpy, XMesaDrawable d )
2581{
2582   XMesaBuffer b;
2583   for (b=XMesaBufferList; b; b=b->Next) {
2584      if (b->frontbuffer==d && b->display==dpy) {
2585         return b;
2586      }
2587   }
2588   return NULL;
2589}
2590
2591
2592
2593/*
2594 * Look for XMesaBuffers whose X window has been destroyed.
2595 * Deallocate any such XMesaBuffers.
2596 */
2597void XMesaGarbageCollect( void )
2598{
2599   XMesaBuffer b, next;
2600   for (b=XMesaBufferList; b; b=next) {
2601      next = b->Next;
2602      if (!b->pixmap_flag) {
2603#ifdef XFree86Server
2604	 /* NOT_NEEDED */
2605#else
2606         XSync(b->display, False);
2607         if (!window_exists( b->display, b->frontbuffer )) {
2608            /* found a dead window, free the ancillary info */
2609            XMesaDestroyBuffer( b );
2610         }
2611#endif
2612      }
2613   }
2614}
2615
2616
2617void XMesaReset( void )
2618{
2619    while (XMesaBufferList)
2620	XMesaDestroyBuffer(XMesaBufferList);
2621
2622    XMesaBufferList = NULL;
2623}
2624
2625
2626unsigned long XMesaDitherColor( XMesaContext xmesa, GLint x, GLint y,
2627                                GLfloat red, GLfloat green,
2628                                GLfloat blue, GLfloat alpha )
2629{
2630   GLint r = (GLint) (red   * 255.0F);
2631   GLint g = (GLint) (green * 255.0F);
2632   GLint b = (GLint) (blue  * 255.0F);
2633   GLint a = (GLint) (alpha * 255.0F);
2634
2635   switch (xmesa->pixelformat) {
2636      case PF_INDEX:
2637         return 0;
2638      case PF_TRUECOLOR:
2639         {
2640            unsigned long p;
2641            PACK_TRUECOLOR( p, r, g, b );
2642            return p;
2643         }
2644      case PF_8A8B8G8R:
2645         return PACK_8A8B8G8R( r, g, b, a );
2646      case PF_8R8G8B:
2647         return PACK_8R8G8B( r, g, b );
2648      case PF_5R6G5B:
2649         return PACK_5R6G5B( r, g, b );
2650      case PF_DITHER:
2651         {
2652            DITHER_SETUP;
2653            return DITHER( x, y, r, g, b );
2654         }
2655      case PF_1BIT:
2656         /* 382 = (3*255)/2 */
2657         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
2658      case PF_HPCR:
2659         return DITHER_HPCR(x, y, r, g, b);
2660      case PF_LOOKUP:
2661         {
2662            LOOKUP_SETUP;
2663            return LOOKUP( r, g, b );
2664         }
2665      case PF_GRAYSCALE:
2666         return GRAY_RGB( r, g, b );
2667      case PF_DITHER_5R6G5B:
2668         /* fall through */
2669      case PF_TRUEDITHER:
2670         {
2671            unsigned long p;
2672            PACK_TRUEDITHER(p, x, y, r, g, b);
2673            return p;
2674         }
2675      default:
2676         _mesa_problem(NULL, "Bad pixel format in XMesaDitherColor");
2677   }
2678   return 0;
2679}
2680
2681
2682