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