xm_api.c revision 0a20051e6da99e91b7bf589ea457c77a8b618f26
1/*
2 * Mesa 3-D graphics library
3 * Version:  7.1
4 *
5 * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25/**
26 * \file xm_api.c
27 *
28 * All the XMesa* API functions.
29 *
30 *
31 * NOTES:
32 *
33 * The window coordinate system origin (0,0) is in the lower-left corner
34 * of the window.  X11's window coordinate origin is in the upper-left
35 * corner of the window.  Therefore, most drawing functions in this
36 * file have to flip Y coordinates.
37 *
38 * Define USE_XSHM in the Makefile with -DUSE_XSHM if you want to compile
39 * in support for the MIT Shared Memory extension.  If enabled, when you
40 * use an Ximage for the back buffer in double buffered mode, the "swap"
41 * operation will be faster.  You must also link with -lXext.
42 *
43 * Byte swapping:  If the Mesa host and the X display use a different
44 * byte order then there's some trickiness to be aware of when using
45 * XImages.  The byte ordering used for the XImage is that of the X
46 * display, not the Mesa host.
47 * The color-to-pixel encoding for True/DirectColor must be done
48 * according to the display's visual red_mask, green_mask, and blue_mask.
49 * If XPutPixel is used to put a pixel into an XImage then XPutPixel will
50 * do byte swapping if needed.  If one wants to directly "poke" the pixel
51 * into the XImage's buffer then the pixel must be byte swapped first.  In
52 * Mesa, when byte swapping is needed we use the PF_TRUECOLOR pixel format
53 * and use XPutPixel everywhere except in the implementation of
54 * glClear(GL_COLOR_BUFFER_BIT).  We want this function to be fast so
55 * instead of using XPutPixel we "poke" our values after byte-swapping
56 * the clear pixel value if needed.
57 *
58 */
59
60#ifdef __CYGWIN__
61#undef WIN32
62#undef __WIN32__
63#endif
64
65#include "glxheader.h"
66#include "xmesaP.h"
67#include "main/context.h"
68#include "main/extensions.h"
69#include "main/framebuffer.h"
70#include "main/imports.h"
71#include "main/macros.h"
72#include "main/renderbuffer.h"
73#include "main/teximage.h"
74#include "glapi/glthread.h"
75#include "swrast/swrast.h"
76#include "swrast/s_renderbuffer.h"
77#include "swrast_setup/swrast_setup.h"
78#include "vbo/vbo.h"
79#include "tnl/tnl.h"
80#include "tnl/t_context.h"
81#include "tnl/t_pipeline.h"
82#include "drivers/common/driverfuncs.h"
83#include "drivers/common/meta.h"
84
85/**
86 * Global X driver lock
87 */
88_glthread_Mutex _xmesa_lock;
89
90
91
92/**********************************************************************/
93/*****                     X Utility Functions                    *****/
94/**********************************************************************/
95
96
97/**
98 * Return the host's byte order as LSBFirst or MSBFirst ala X.
99 */
100static int host_byte_order( void )
101{
102   int i = 1;
103   char *cptr = (char *) &i;
104   return (*cptr==1) ? LSBFirst : MSBFirst;
105}
106
107
108/**
109 * Check if the X Shared Memory extension is available.
110 * Return:  0 = not available
111 *          1 = shared XImage support available
112 *          2 = shared Pixmap support available also
113 */
114static int check_for_xshm( XMesaDisplay *display )
115{
116#if defined(USE_XSHM)
117   int ignore;
118
119   if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
120      /* Note: we're no longer calling XShmQueryVersion() here.  It seems
121       * to be flakey (triggers a spurious X protocol error when we close
122       * one display connection and start using a new one.  XShm has been
123       * around a long time and hasn't changed so if MIT_SHM is supported
124       * we assume we're good to go.
125       */
126      return 2;
127   }
128   else {
129      return 0;
130   }
131#else
132   /* No  XSHM support */
133   return 0;
134#endif
135}
136
137
138/**
139 * Apply gamma correction to an intensity value in [0..max].  Return the
140 * new intensity value.
141 */
142static GLint
143gamma_adjust( GLfloat gamma, GLint value, GLint max )
144{
145   if (gamma == 1.0) {
146      return value;
147   }
148   else {
149      double x = (double) value / (double) max;
150      return IROUND_POS((GLfloat) max * pow(x, 1.0F/gamma));
151   }
152}
153
154
155
156/**
157 * Return the true number of bits per pixel for XImages.
158 * For example, if we request a 24-bit deep visual we may actually need/get
159 * 32bpp XImages.  This function returns the appropriate bpp.
160 * Input:  dpy - the X display
161 *         visinfo - desribes the visual to be used for XImages
162 * Return:  true number of bits per pixel for XImages
163 */
164static int
165bits_per_pixel( XMesaVisual xmv )
166{
167   XMesaDisplay *dpy = xmv->display;
168   XMesaVisualInfo visinfo = xmv->visinfo;
169   XMesaImage *img;
170   int bitsPerPixel;
171   /* Create a temporary XImage */
172   img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
173		       ZPixmap, 0,           /*format, offset*/
174		       (char*) MALLOC(8),    /*data*/
175		       1, 1,                 /*width, height*/
176		       32,                   /*bitmap_pad*/
177		       0                     /*bytes_per_line*/
178                     );
179   assert(img);
180   /* grab the bits/pixel value */
181   bitsPerPixel = img->bits_per_pixel;
182   /* free the XImage */
183   free( img->data );
184   img->data = NULL;
185   XMesaDestroyImage( img );
186   return bitsPerPixel;
187}
188
189
190
191/*
192 * Determine if a given X window ID is valid (window exists).
193 * Do this by calling XGetWindowAttributes() for the window and
194 * checking if we catch an X error.
195 * Input:  dpy - the display
196 *         win - the window to check for existance
197 * Return:  GL_TRUE - window exists
198 *          GL_FALSE - window doesn't exist
199 */
200static GLboolean WindowExistsFlag;
201
202static int window_exists_err_handler( XMesaDisplay* dpy, XErrorEvent* xerr )
203{
204   (void) dpy;
205   if (xerr->error_code == BadWindow) {
206      WindowExistsFlag = GL_FALSE;
207   }
208   return 0;
209}
210
211static GLboolean window_exists( XMesaDisplay *dpy, Window win )
212{
213   XWindowAttributes wa;
214   int (*old_handler)( XMesaDisplay*, XErrorEvent* );
215   WindowExistsFlag = GL_TRUE;
216   old_handler = XSetErrorHandler(window_exists_err_handler);
217   XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
218   XSetErrorHandler(old_handler);
219   return WindowExistsFlag;
220}
221
222static Status
223get_drawable_size( XMesaDisplay *dpy, Drawable d, GLuint *width, GLuint *height )
224{
225   Window root;
226   Status stat;
227   int xpos, ypos;
228   unsigned int w, h, bw, depth;
229   stat = XGetGeometry(dpy, d, &root, &xpos, &ypos, &w, &h, &bw, &depth);
230   *width = w;
231   *height = h;
232   return stat;
233}
234
235
236/**
237 * Return the size of the window (or pixmap) that corresponds to the
238 * given XMesaBuffer.
239 * \param width  returns width in pixels
240 * \param height  returns height in pixels
241 */
242void
243xmesa_get_window_size(XMesaDisplay *dpy, XMesaBuffer b,
244                      GLuint *width, GLuint *height)
245{
246   Status stat;
247
248   _glthread_LOCK_MUTEX(_xmesa_lock);
249   XSync(b->xm_visual->display, 0); /* added for Chromium */
250   stat = get_drawable_size(dpy, b->frontxrb->pixmap, width, height);
251   _glthread_UNLOCK_MUTEX(_xmesa_lock);
252
253   if (!stat) {
254      /* probably querying a window that's recently been destroyed */
255      _mesa_warning(NULL, "XGetGeometry failed!\n");
256      *width = *height = 1;
257   }
258}
259
260
261
262/**********************************************************************/
263/*****                Linked list of XMesaBuffers                 *****/
264/**********************************************************************/
265
266XMesaBuffer XMesaBufferList = NULL;
267
268
269/**
270 * Allocate a new XMesaBuffer object which corresponds to the given drawable.
271 * Note that XMesaBuffer is derived from struct gl_framebuffer.
272 * The new XMesaBuffer will not have any size (Width=Height=0).
273 *
274 * \param d  the corresponding X drawable (window or pixmap)
275 * \param type  either WINDOW, PIXMAP or PBUFFER, describing d
276 * \param vis  the buffer's visual
277 * \param cmap  the window's colormap, if known.
278 * \return new XMesaBuffer or NULL if any problem
279 */
280static XMesaBuffer
281create_xmesa_buffer(XMesaDrawable d, BufferType type,
282                    XMesaVisual vis, XMesaColormap cmap)
283{
284   XMesaBuffer b;
285
286   ASSERT(type == WINDOW || type == PIXMAP || type == PBUFFER);
287
288   b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
289   if (!b)
290      return NULL;
291
292   b->display = vis->display;
293   b->xm_visual = vis;
294   b->type = type;
295   b->cmap = cmap;
296
297   _mesa_initialize_window_framebuffer(&b->mesa_buffer, &vis->mesa_visual);
298   b->mesa_buffer.Delete = xmesa_delete_framebuffer;
299
300   /*
301    * Front renderbuffer
302    */
303   b->frontxrb = xmesa_new_renderbuffer(NULL, 0, vis, GL_FALSE);
304   if (!b->frontxrb) {
305      free(b);
306      return NULL;
307   }
308   b->frontxrb->Parent = b;
309   b->frontxrb->drawable = d;
310   b->frontxrb->pixmap = (XMesaPixmap) d;
311   _mesa_add_renderbuffer(&b->mesa_buffer, BUFFER_FRONT_LEFT,
312                          &b->frontxrb->Base);
313
314   /*
315    * Back renderbuffer
316    */
317   if (vis->mesa_visual.doubleBufferMode) {
318      b->backxrb = xmesa_new_renderbuffer(NULL, 0, vis, GL_TRUE);
319      if (!b->backxrb) {
320         /* XXX free front xrb too */
321         free(b);
322         return NULL;
323      }
324      b->backxrb->Parent = b;
325      /* determine back buffer implementation */
326      b->db_mode = vis->ximage_flag ? BACK_XIMAGE : BACK_PIXMAP;
327
328      _mesa_add_renderbuffer(&b->mesa_buffer, BUFFER_BACK_LEFT,
329                             &b->backxrb->Base);
330   }
331
332   /*
333    * Other renderbuffer (depth, stencil, etc)
334    */
335   _swrast_add_soft_renderbuffers(&b->mesa_buffer,
336                                  GL_FALSE,  /* color */
337                                  vis->mesa_visual.haveDepthBuffer,
338                                  vis->mesa_visual.haveStencilBuffer,
339                                  vis->mesa_visual.haveAccumBuffer,
340                                  GL_FALSE,  /* software alpha buffer */
341                                  vis->mesa_visual.numAuxBuffers > 0 );
342
343   /* GLX_EXT_texture_from_pixmap */
344   b->TextureTarget = 0;
345   b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;
346   b->TextureMipmap = 0;
347
348   /* insert buffer into linked list */
349   b->Next = XMesaBufferList;
350   XMesaBufferList = b;
351
352   return b;
353}
354
355
356/**
357 * Find an XMesaBuffer by matching X display and colormap but NOT matching
358 * the notThis buffer.
359 */
360XMesaBuffer
361xmesa_find_buffer(XMesaDisplay *dpy, XMesaColormap cmap, XMesaBuffer notThis)
362{
363   XMesaBuffer b;
364   for (b=XMesaBufferList; b; b=b->Next) {
365      if (b->display==dpy && b->cmap==cmap && b!=notThis) {
366         return b;
367      }
368   }
369   return NULL;
370}
371
372
373/**
374 * Remove buffer from linked list, delete if no longer referenced.
375 */
376static void
377xmesa_free_buffer(XMesaBuffer buffer)
378{
379   XMesaBuffer prev = NULL, b;
380
381   for (b = XMesaBufferList; b; b = b->Next) {
382      if (b == buffer) {
383         struct gl_framebuffer *fb = &buffer->mesa_buffer;
384
385         /* unlink buffer from list */
386         if (prev)
387            prev->Next = buffer->Next;
388         else
389            XMesaBufferList = buffer->Next;
390
391         /* mark as delete pending */
392         fb->DeletePending = GL_TRUE;
393
394         /* Since the X window for the XMesaBuffer is going away, we don't
395          * want to dereference this pointer in the future.
396          */
397         b->frontxrb->drawable = 0;
398
399         /* Unreference.  If count = zero we'll really delete the buffer */
400         _mesa_reference_framebuffer(&fb, NULL);
401
402         return;
403      }
404      /* continue search */
405      prev = b;
406   }
407   /* buffer not found in XMesaBufferList */
408   _mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");
409}
410
411
412
413
414/**********************************************************************/
415/*****                   Misc Private Functions                   *****/
416/**********************************************************************/
417
418
419/**
420 * Setup RGB rendering for a window with a True/DirectColor visual.
421 */
422static void
423setup_truecolor(XMesaVisual v, XMesaBuffer buffer, XMesaColormap cmap)
424{
425   unsigned long rmask, gmask, bmask;
426   (void) buffer;
427   (void) cmap;
428
429   /* Compute red multiplier (mask) and bit shift */
430   v->rshift = 0;
431   rmask = GET_REDMASK(v);
432   while ((rmask & 1)==0) {
433      v->rshift++;
434      rmask = rmask >> 1;
435   }
436
437   /* Compute green multiplier (mask) and bit shift */
438   v->gshift = 0;
439   gmask = GET_GREENMASK(v);
440   while ((gmask & 1)==0) {
441      v->gshift++;
442      gmask = gmask >> 1;
443   }
444
445   /* Compute blue multiplier (mask) and bit shift */
446   v->bshift = 0;
447   bmask = GET_BLUEMASK(v);
448   while ((bmask & 1)==0) {
449      v->bshift++;
450      bmask = bmask >> 1;
451   }
452
453   /*
454    * Compute component-to-pixel lookup tables and dithering kernel
455    */
456   {
457      static GLubyte kernel[16] = {
458          0*16,  8*16,  2*16, 10*16,
459         12*16,  4*16, 14*16,  6*16,
460          3*16, 11*16,  1*16,  9*16,
461         15*16,  7*16, 13*16,  5*16,
462      };
463      GLint rBits = _mesa_bitcount(rmask);
464      GLint gBits = _mesa_bitcount(gmask);
465      GLint bBits = _mesa_bitcount(bmask);
466      GLint maxBits;
467      GLuint i;
468
469      /* convert pixel components in [0,_mask] to RGB values in [0,255] */
470      for (i=0; i<=rmask; i++)
471         v->PixelToR[i] = (unsigned char) ((i * 255) / rmask);
472      for (i=0; i<=gmask; i++)
473         v->PixelToG[i] = (unsigned char) ((i * 255) / gmask);
474      for (i=0; i<=bmask; i++)
475         v->PixelToB[i] = (unsigned char) ((i * 255) / bmask);
476
477      /* convert RGB values from [0,255] to pixel components */
478
479      for (i=0;i<256;i++) {
480         GLint r = gamma_adjust(v->RedGamma,   i, 255);
481         GLint g = gamma_adjust(v->GreenGamma, i, 255);
482         GLint b = gamma_adjust(v->BlueGamma,  i, 255);
483         v->RtoPixel[i] = (r >> (8-rBits)) << v->rshift;
484         v->GtoPixel[i] = (g >> (8-gBits)) << v->gshift;
485         v->BtoPixel[i] = (b >> (8-bBits)) << v->bshift;
486      }
487      /* overflow protection */
488      for (i=256;i<512;i++) {
489         v->RtoPixel[i] = v->RtoPixel[255];
490         v->GtoPixel[i] = v->GtoPixel[255];
491         v->BtoPixel[i] = v->BtoPixel[255];
492      }
493
494      /* setup dithering kernel */
495      maxBits = rBits;
496      if (gBits > maxBits)  maxBits = gBits;
497      if (bBits > maxBits)  maxBits = bBits;
498      for (i=0;i<16;i++) {
499         v->Kernel[i] = kernel[i] >> maxBits;
500      }
501
502      v->undithered_pf = PF_Truecolor;
503      v->dithered_pf = (GET_VISUAL_DEPTH(v)<24) ? PF_Dither_True : PF_Truecolor;
504   }
505
506   /*
507    * Now check for TrueColor visuals which we can optimize.
508    */
509   if (   GET_REDMASK(v)  ==0x0000ff
510       && GET_GREENMASK(v)==0x00ff00
511       && GET_BLUEMASK(v) ==0xff0000
512       && CHECK_BYTE_ORDER(v)
513       && v->BitsPerPixel==32
514       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
515      /* common 32 bpp config used on SGI, Sun */
516      v->undithered_pf = v->dithered_pf = PF_8A8B8G8R; /* ABGR */
517   }
518   else if (GET_REDMASK(v)  == 0xff0000
519         && GET_GREENMASK(v)== 0x00ff00
520         && GET_BLUEMASK(v) == 0x0000ff
521         && CHECK_BYTE_ORDER(v)
522         && v->RedGamma == 1.0 && v->GreenGamma == 1.0 && v->BlueGamma == 1.0){
523      if (v->BitsPerPixel==32) {
524         /* if 32 bpp, and visual indicates 8 bpp alpha channel */
525         if (GET_VISUAL_DEPTH(v) == 32 && v->mesa_visual.alphaBits == 8)
526            v->undithered_pf = v->dithered_pf = PF_8A8R8G8B; /* ARGB */
527         else
528            v->undithered_pf = v->dithered_pf = PF_8R8G8B; /* xRGB */
529      }
530      else if (v->BitsPerPixel == 24) {
531         v->undithered_pf = v->dithered_pf = PF_8R8G8B24; /* RGB */
532      }
533   }
534   else if (GET_REDMASK(v)  ==0xf800
535       &&   GET_GREENMASK(v)==0x07e0
536       &&   GET_BLUEMASK(v) ==0x001f
537       && CHECK_BYTE_ORDER(v)
538       && v->BitsPerPixel==16
539       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
540      /* 5-6-5 RGB */
541      v->undithered_pf = PF_5R6G5B;
542      v->dithered_pf = PF_Dither_5R6G5B;
543   }
544}
545
546
547/**
548 * When a context is bound for the first time, we can finally finish
549 * initializing the context's visual and buffer information.
550 * \param v  the XMesaVisual to initialize
551 * \param b  the XMesaBuffer to initialize (may be NULL)
552 * \param rgb_flag  TRUE = RGBA mode, FALSE = color index mode
553 * \param window  the window/pixmap we're rendering into
554 * \param cmap  the colormap associated with the window/pixmap
555 * \return GL_TRUE=success, GL_FALSE=failure
556 */
557static GLboolean
558initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,
559                             XMesaDrawable window,
560                             XMesaColormap cmap)
561{
562   const int xclass = v->visualType;
563
564
565   ASSERT(!b || b->xm_visual == v);
566
567   /* Save true bits/pixel */
568   v->BitsPerPixel = bits_per_pixel(v);
569   assert(v->BitsPerPixel > 0);
570
571   /* RGB WINDOW:
572    * We support RGB rendering into almost any kind of visual.
573    */
574   if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
575      setup_truecolor( v, b, cmap );
576   }
577   else {
578      _mesa_warning(NULL, "XMesa: RGB mode rendering not supported in given visual.\n");
579      return GL_FALSE;
580   }
581   v->mesa_visual.indexBits = 0;
582
583   if (_mesa_getenv("MESA_NO_DITHER")) {
584      v->dithered_pf = v->undithered_pf;
585   }
586
587
588   /*
589    * If MESA_INFO env var is set print out some debugging info
590    * which can help Brian figure out what's going on when a user
591    * reports bugs.
592    */
593   if (_mesa_getenv("MESA_INFO")) {
594      printf("X/Mesa visual = %p\n", (void *) v);
595      printf("X/Mesa dithered pf = %u\n", v->dithered_pf);
596      printf("X/Mesa undithered pf = %u\n", v->undithered_pf);
597      printf("X/Mesa level = %d\n", v->mesa_visual.level);
598      printf("X/Mesa depth = %d\n", GET_VISUAL_DEPTH(v));
599      printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
600   }
601
602   if (b && window) {
603      char *data;
604
605      /* Do window-specific initializations */
606
607      /* these should have been set in create_xmesa_buffer */
608      ASSERT(b->frontxrb->drawable == window);
609      ASSERT(b->frontxrb->pixmap == (XMesaPixmap) window);
610
611      /* Setup for single/double buffering */
612      if (v->mesa_visual.doubleBufferMode) {
613         /* Double buffered */
614         b->shm = check_for_xshm( v->display );
615      }
616
617      /* X11 graphics contexts */
618      b->gc = XCreateGC( v->display, window, 0, NULL );
619      XMesaSetFunction( v->display, b->gc, GXcopy );
620
621      /* cleargc - for glClear() */
622      b->cleargc = XCreateGC( v->display, window, 0, NULL );
623      XMesaSetFunction( v->display, b->cleargc, GXcopy );
624
625      /*
626       * Don't generate Graphics Expose/NoExpose events in swapbuffers().
627       * Patch contributed by Michael Pichler May 15, 1995.
628       */
629      {
630         XGCValues gcvalues;
631         gcvalues.graphics_exposures = False;
632         b->swapgc = XCreateGC(v->display, window,
633                               GCGraphicsExposures, &gcvalues);
634      }
635      XMesaSetFunction( v->display, b->swapgc, GXcopy );
636
637      /* Initialize the row buffer XImage for use in write_color_span() */
638      data = (char*) MALLOC(MAX_WIDTH*4);
639      b->rowimage = XCreateImage( v->display,
640                                  v->visinfo->visual,
641                                  v->visinfo->depth,
642                                  ZPixmap, 0,           /*format, offset*/
643                                  data,                 /*data*/
644                                  MAX_WIDTH, 1,         /*width, height*/
645                                  32,                   /*bitmap_pad*/
646                                  0                     /*bytes_per_line*/ );
647      if (!b->rowimage)
648         return GL_FALSE;
649   }
650
651   return GL_TRUE;
652}
653
654
655
656/*
657 * Convert an RGBA color to a pixel value.
658 */
659unsigned long
660xmesa_color_to_pixel(struct gl_context *ctx,
661                     GLubyte r, GLubyte g, GLubyte b, GLubyte a,
662                     GLuint pixelFormat)
663{
664   XMesaContext xmesa = XMESA_CONTEXT(ctx);
665   switch (pixelFormat) {
666      case PF_Truecolor:
667         {
668            unsigned long p;
669            PACK_TRUECOLOR( p, r, g, b );
670            return p;
671         }
672      case PF_8A8B8G8R:
673         return PACK_8A8B8G8R( r, g, b, a );
674      case PF_8A8R8G8B:
675         return PACK_8A8R8G8B( r, g, b, a );
676      case PF_8R8G8B:
677         /* fall through */
678      case PF_8R8G8B24:
679         return PACK_8R8G8B( r, g, b );
680      case PF_5R6G5B:
681         return PACK_5R6G5B( r, g, b );
682      case PF_Dither_True:
683         /* fall through */
684      case PF_Dither_5R6G5B:
685         {
686            unsigned long p;
687            PACK_TRUEDITHER(p, 1, 0, r, g, b);
688            return p;
689         }
690      default:
691         _mesa_problem(ctx, "Bad pixel format in xmesa_color_to_pixel");
692   }
693   return 0;
694}
695
696
697#define NUM_VISUAL_TYPES   6
698
699/**
700 * Convert an X visual type to a GLX visual type.
701 *
702 * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
703 *        to be converted.
704 * \return If \c visualType is a valid X visual type, a GLX visual type will
705 *         be returned.  Otherwise \c GLX_NONE will be returned.
706 *
707 * \note
708 * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
709 * DRI CVS tree.
710 */
711static GLint
712xmesa_convert_from_x_visual_type( int visualType )
713{
714    static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
715	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
716	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
717	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
718    };
719
720    return ( (unsigned) visualType < NUM_VISUAL_TYPES )
721	? glx_visual_types[ visualType ] : GLX_NONE;
722}
723
724
725/**********************************************************************/
726/*****                       Public Functions                     *****/
727/**********************************************************************/
728
729
730/*
731 * Create a new X/Mesa visual.
732 * Input:  display - X11 display
733 *         visinfo - an XVisualInfo pointer
734 *         rgb_flag - GL_TRUE = RGB mode,
735 *                    GL_FALSE = color index mode
736 *         alpha_flag - alpha buffer requested?
737 *         db_flag - GL_TRUE = double-buffered,
738 *                   GL_FALSE = single buffered
739 *         stereo_flag - stereo visual?
740 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
741 *                       GL_FALSE = use an off-screen pixmap for back buffer
742 *         depth_size - requested bits/depth values, or zero
743 *         stencil_size - requested bits/stencil values, or zero
744 *         accum_red_size - requested bits/red accum values, or zero
745 *         accum_green_size - requested bits/green accum values, or zero
746 *         accum_blue_size - requested bits/blue accum values, or zero
747 *         accum_alpha_size - requested bits/alpha accum values, or zero
748 *         num_samples - number of samples/pixel if multisampling, or zero
749 *         level - visual level, usually 0
750 *         visualCaveat - ala the GLX extension, usually GLX_NONE
751 * Return;  a new XMesaVisual or 0 if error.
752 */
753PUBLIC
754XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
755                               XMesaVisualInfo visinfo,
756                               GLboolean rgb_flag,
757                               GLboolean alpha_flag,
758                               GLboolean db_flag,
759                               GLboolean stereo_flag,
760                               GLboolean ximage_flag,
761                               GLint depth_size,
762                               GLint stencil_size,
763                               GLint accum_red_size,
764                               GLint accum_green_size,
765                               GLint accum_blue_size,
766                               GLint accum_alpha_size,
767                               GLint num_samples,
768                               GLint level,
769                               GLint visualCaveat )
770{
771   char *gamma;
772   XMesaVisual v;
773   GLint red_bits, green_bits, blue_bits, alpha_bits;
774
775   /* For debugging only */
776   if (_mesa_getenv("MESA_XSYNC")) {
777      /* This makes debugging X easier.
778       * In your debugger, set a breakpoint on _XError to stop when an
779       * X protocol error is generated.
780       */
781      XSynchronize( display, 1 );
782   }
783
784   /* Color-index rendering not supported. */
785   if (!rgb_flag)
786      return NULL;
787
788   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
789   if (!v) {
790      return NULL;
791   }
792
793   v->display = display;
794
795   /* Save a copy of the XVisualInfo struct because the user may Xfree()
796    * the struct but we may need some of the information contained in it
797    * at a later time.
798    */
799   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
800   if(!v->visinfo) {
801      free(v);
802      return NULL;
803   }
804   memcpy(v->visinfo, visinfo, sizeof(*visinfo));
805
806   /* check for MESA_GAMMA environment variable */
807   gamma = _mesa_getenv("MESA_GAMMA");
808   if (gamma) {
809      v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
810      sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
811      if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
812      if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
813      if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
814   }
815   else {
816      v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
817   }
818
819   v->ximage_flag = ximage_flag;
820
821   v->mesa_visual.redMask = visinfo->red_mask;
822   v->mesa_visual.greenMask = visinfo->green_mask;
823   v->mesa_visual.blueMask = visinfo->blue_mask;
824   v->visualID = visinfo->visualid;
825   v->screen = visinfo->screen;
826
827#if !(defined(__cplusplus) || defined(c_plusplus))
828   v->visualType = xmesa_convert_from_x_visual_type(visinfo->class);
829#else
830   v->visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
831#endif
832
833   v->mesa_visual.visualRating = visualCaveat;
834
835   if (alpha_flag)
836      v->mesa_visual.alphaBits = 8;
837
838   (void) initialize_visual_and_buffer( v, NULL, 0, 0 );
839
840   {
841      const int xclass = v->visualType;
842      if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
843         red_bits   = _mesa_bitcount(GET_REDMASK(v));
844         green_bits = _mesa_bitcount(GET_GREENMASK(v));
845         blue_bits  = _mesa_bitcount(GET_BLUEMASK(v));
846      }
847      else {
848         /* this is an approximation */
849         int depth;
850         depth = GET_VISUAL_DEPTH(v);
851         red_bits = depth / 3;
852         depth -= red_bits;
853         green_bits = depth / 2;
854         depth -= green_bits;
855         blue_bits = depth;
856         alpha_bits = 0;
857         assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
858      }
859      alpha_bits = v->mesa_visual.alphaBits;
860   }
861
862   _mesa_initialize_visual( &v->mesa_visual,
863                            db_flag, stereo_flag,
864                            red_bits, green_bits,
865                            blue_bits, alpha_bits,
866                            depth_size,
867                            stencil_size,
868                            accum_red_size, accum_green_size,
869                            accum_blue_size, accum_alpha_size,
870                            0 );
871
872   /* XXX minor hack */
873   v->mesa_visual.level = level;
874   return v;
875}
876
877
878PUBLIC
879void XMesaDestroyVisual( XMesaVisual v )
880{
881   free(v->visinfo);
882   free(v);
883}
884
885
886
887/**
888 * Create a new XMesaContext.
889 * \param v  the XMesaVisual
890 * \param share_list  another XMesaContext with which to share display
891 *                    lists or NULL if no sharing is wanted.
892 * \return an XMesaContext or NULL if error.
893 */
894PUBLIC
895XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
896{
897   static GLboolean firstTime = GL_TRUE;
898   XMesaContext c;
899   struct gl_context *mesaCtx;
900   struct dd_function_table functions;
901   TNLcontext *tnl;
902
903   if (firstTime) {
904      _glthread_INIT_MUTEX(_xmesa_lock);
905      firstTime = GL_FALSE;
906   }
907
908   /* Note: the XMesaContext contains a Mesa struct gl_context struct (inheritance) */
909   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
910   if (!c)
911      return NULL;
912
913   mesaCtx = &(c->mesa);
914
915   /* initialize with default driver functions, then plug in XMesa funcs */
916   _mesa_init_driver_functions(&functions);
917   xmesa_init_driver_functions(v, &functions);
918   if (!_mesa_initialize_context(mesaCtx, API_OPENGL, &v->mesa_visual,
919                      share_list ? &(share_list->mesa) : (struct gl_context *) NULL,
920                      &functions, (void *) c)) {
921      free(c);
922      return NULL;
923   }
924
925   /* Enable this to exercise fixed function -> shader translation
926    * with software rendering.
927    */
928   if (0) {
929      mesaCtx->VertexProgram._MaintainTnlProgram = GL_TRUE;
930      mesaCtx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
931   }
932
933   _mesa_enable_sw_extensions(mesaCtx);
934   _mesa_enable_1_3_extensions(mesaCtx);
935   _mesa_enable_1_4_extensions(mesaCtx);
936   _mesa_enable_1_5_extensions(mesaCtx);
937   _mesa_enable_2_0_extensions(mesaCtx);
938   _mesa_enable_2_1_extensions(mesaCtx);
939#if ENABLE_EXT_texure_compression_s3tc
940    if (mesaCtx->Mesa_DXTn) {
941       _mesa_enable_extension(mesaCtx, "GL_EXT_texture_compression_s3tc");
942       _mesa_enable_extension(mesaCtx, "GL_S3_s3tc");
943    }
944    _mesa_enable_extension(mesaCtx, "GL_3DFX_texture_compression_FXT1");
945#endif
946#if ENABLE_EXT_timer_query
947    _mesa_enable_extension(mesaCtx, "GL_EXT_timer_query");
948#endif
949
950
951   /* finish up xmesa context initializations */
952   c->swapbytes = CHECK_BYTE_ORDER(v) ? GL_FALSE : GL_TRUE;
953   c->xm_visual = v;
954   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
955   c->display = v->display;
956   c->pixelformat = v->dithered_pf;      /* Dithering is enabled by default */
957
958   /* Initialize the software rasterizer and helper modules.
959    */
960   if (!_swrast_CreateContext( mesaCtx ) ||
961       !_vbo_CreateContext( mesaCtx ) ||
962       !_tnl_CreateContext( mesaCtx ) ||
963       !_swsetup_CreateContext( mesaCtx )) {
964      _mesa_free_context_data(&c->mesa);
965      free(c);
966      return NULL;
967   }
968
969   /* tnl setup */
970   tnl = TNL_CONTEXT(mesaCtx);
971   tnl->Driver.RunPipeline = _tnl_run_pipeline;
972   /* swrast setup */
973   xmesa_register_swrast_functions( mesaCtx );
974   _swsetup_Wakeup(mesaCtx);
975
976   _mesa_meta_init(mesaCtx);
977
978   return c;
979}
980
981
982
983PUBLIC
984void XMesaDestroyContext( XMesaContext c )
985{
986   struct gl_context *mesaCtx = &c->mesa;
987
988   _mesa_meta_free( mesaCtx );
989
990   _swsetup_DestroyContext( mesaCtx );
991   _swrast_DestroyContext( mesaCtx );
992   _tnl_DestroyContext( mesaCtx );
993   _vbo_DestroyContext( mesaCtx );
994   _mesa_free_context_data( mesaCtx );
995   free( c );
996}
997
998
999
1000/**
1001 * Private function for creating an XMesaBuffer which corresponds to an
1002 * X window or pixmap.
1003 * \param v  the window's XMesaVisual
1004 * \param w  the window we're wrapping
1005 * \return  new XMesaBuffer or NULL if error
1006 */
1007PUBLIC XMesaBuffer
1008XMesaCreateWindowBuffer(XMesaVisual v, XMesaWindow w)
1009{
1010   XWindowAttributes attr;
1011   XMesaBuffer b;
1012   XMesaColormap cmap;
1013   int depth;
1014
1015   assert(v);
1016   assert(w);
1017
1018   /* Check that window depth matches visual depth */
1019   XGetWindowAttributes( v->display, w, &attr );
1020   depth = attr.depth;
1021   if (GET_VISUAL_DEPTH(v) != depth) {
1022      _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",
1023                    GET_VISUAL_DEPTH(v), depth);
1024      return NULL;
1025   }
1026
1027   /* Find colormap */
1028   if (attr.colormap) {
1029      cmap = attr.colormap;
1030   }
1031   else {
1032      _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
1033      /* this is weird, a window w/out a colormap!? */
1034      /* OK, let's just allocate a new one and hope for the best */
1035      cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
1036   }
1037
1038   b = create_xmesa_buffer((XMesaDrawable) w, WINDOW, v, cmap);
1039   if (!b)
1040      return NULL;
1041
1042   if (!initialize_visual_and_buffer( v, b, (XMesaDrawable) w, cmap )) {
1043      xmesa_free_buffer(b);
1044      return NULL;
1045   }
1046
1047   return b;
1048}
1049
1050
1051
1052/**
1053 * Create a new XMesaBuffer from an X pixmap.
1054 *
1055 * \param v    the XMesaVisual
1056 * \param p    the pixmap
1057 * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
1058 *             \c GLX_DIRECT_COLOR visual for the pixmap
1059 * \returns new XMesaBuffer or NULL if error
1060 */
1061PUBLIC XMesaBuffer
1062XMesaCreatePixmapBuffer(XMesaVisual v, XMesaPixmap p, XMesaColormap cmap)
1063{
1064   XMesaBuffer b;
1065
1066   assert(v);
1067
1068   b = create_xmesa_buffer((XMesaDrawable) p, PIXMAP, v, cmap);
1069   if (!b)
1070      return NULL;
1071
1072   if (!initialize_visual_and_buffer(v, b, (XMesaDrawable) p, cmap)) {
1073      xmesa_free_buffer(b);
1074      return NULL;
1075   }
1076
1077   return b;
1078}
1079
1080
1081/**
1082 * For GLX_EXT_texture_from_pixmap
1083 */
1084XMesaBuffer
1085XMesaCreatePixmapTextureBuffer(XMesaVisual v, XMesaPixmap p,
1086                               XMesaColormap cmap,
1087                               int format, int target, int mipmap)
1088{
1089   GET_CURRENT_CONTEXT(ctx);
1090   XMesaBuffer b;
1091   GLuint width, height;
1092
1093   assert(v);
1094
1095   b = create_xmesa_buffer((XMesaDrawable) p, PIXMAP, v, cmap);
1096   if (!b)
1097      return NULL;
1098
1099   /* get pixmap size, update framebuffer/renderbuffer dims */
1100   xmesa_get_window_size(v->display, b, &width, &height);
1101   _mesa_resize_framebuffer(NULL, &(b->mesa_buffer), width, height);
1102
1103   if (target == 0) {
1104      /* examine dims */
1105      if (ctx->Extensions.ARB_texture_non_power_of_two) {
1106         target = GLX_TEXTURE_2D_EXT;
1107      }
1108      else if (   _mesa_bitcount(width)  == 1
1109               && _mesa_bitcount(height) == 1) {
1110         /* power of two size */
1111         if (height == 1) {
1112            target = GLX_TEXTURE_1D_EXT;
1113         }
1114         else {
1115            target = GLX_TEXTURE_2D_EXT;
1116         }
1117      }
1118      else if (ctx->Extensions.NV_texture_rectangle) {
1119         target = GLX_TEXTURE_RECTANGLE_EXT;
1120      }
1121      else {
1122         /* non power of two textures not supported */
1123         XMesaDestroyBuffer(b);
1124         return 0;
1125      }
1126   }
1127
1128   b->TextureTarget = target;
1129   b->TextureFormat = format;
1130   b->TextureMipmap = mipmap;
1131
1132   if (!initialize_visual_and_buffer(v, b, (XMesaDrawable) p, cmap)) {
1133      xmesa_free_buffer(b);
1134      return NULL;
1135   }
1136
1137   return b;
1138}
1139
1140
1141
1142XMesaBuffer
1143XMesaCreatePBuffer(XMesaVisual v, XMesaColormap cmap,
1144                   unsigned int width, unsigned int height)
1145{
1146   XMesaWindow root;
1147   XMesaDrawable drawable;  /* X Pixmap Drawable */
1148   XMesaBuffer b;
1149
1150   /* allocate pixmap for front buffer */
1151   root = RootWindow( v->display, v->visinfo->screen );
1152   drawable = XCreatePixmap(v->display, root, width, height,
1153                            v->visinfo->depth);
1154   if (!drawable)
1155      return NULL;
1156
1157   b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);
1158   if (!b)
1159      return NULL;
1160
1161   if (!initialize_visual_and_buffer(v, b, drawable, cmap)) {
1162      xmesa_free_buffer(b);
1163      return NULL;
1164   }
1165
1166   return b;
1167}
1168
1169
1170
1171/*
1172 * Deallocate an XMesaBuffer structure and all related info.
1173 */
1174PUBLIC void
1175XMesaDestroyBuffer(XMesaBuffer b)
1176{
1177   xmesa_free_buffer(b);
1178}
1179
1180
1181/**
1182 * Query the current window size and update the corresponding struct gl_framebuffer
1183 * and all attached renderbuffers.
1184 * Called when:
1185 *  1. the first time a buffer is bound to a context.
1186 *  2. from glViewport to poll for window size changes
1187 *  3. from the XMesaResizeBuffers() API function.
1188 * Note: it's possible (and legal) for xmctx to be NULL.  That can happen
1189 * when resizing a buffer when no rendering context is bound.
1190 */
1191void
1192xmesa_check_and_update_buffer_size(XMesaContext xmctx, XMesaBuffer drawBuffer)
1193{
1194   GLuint width, height;
1195   xmesa_get_window_size(drawBuffer->display, drawBuffer, &width, &height);
1196   if (drawBuffer->mesa_buffer.Width != width ||
1197       drawBuffer->mesa_buffer.Height != height) {
1198      struct gl_context *ctx = xmctx ? &xmctx->mesa : NULL;
1199      _mesa_resize_framebuffer(ctx, &(drawBuffer->mesa_buffer), width, height);
1200   }
1201   drawBuffer->mesa_buffer.Initialized = GL_TRUE; /* XXX TEMPORARY? */
1202}
1203
1204
1205/*
1206 * Bind buffer b to context c and make c the current rendering context.
1207 */
1208GLboolean XMesaMakeCurrent( XMesaContext c, XMesaBuffer b )
1209{
1210   return XMesaMakeCurrent2( c, b, b );
1211}
1212
1213
1214/*
1215 * Bind buffer b to context c and make c the current rendering context.
1216 */
1217PUBLIC
1218GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
1219                             XMesaBuffer readBuffer )
1220{
1221   if (c) {
1222      if (!drawBuffer || !readBuffer)
1223         return GL_FALSE;  /* must specify buffers! */
1224
1225      if (&(c->mesa) == _mesa_get_current_context()
1226          && c->mesa.DrawBuffer == &drawBuffer->mesa_buffer
1227          && c->mesa.ReadBuffer == &readBuffer->mesa_buffer
1228          && XMESA_BUFFER(c->mesa.DrawBuffer)->wasCurrent) {
1229         /* same context and buffer, do nothing */
1230         return GL_TRUE;
1231      }
1232
1233      c->xm_buffer = drawBuffer;
1234
1235      /* Call this periodically to detect when the user has begun using
1236       * GL rendering from multiple threads.
1237       */
1238      _glapi_check_multithread();
1239
1240      xmesa_check_and_update_buffer_size(c, drawBuffer);
1241      if (readBuffer != drawBuffer)
1242         xmesa_check_and_update_buffer_size(c, readBuffer);
1243
1244      _mesa_make_current(&(c->mesa),
1245                         &drawBuffer->mesa_buffer,
1246                         &readBuffer->mesa_buffer);
1247
1248      /*
1249       * Must recompute and set these pixel values because colormap
1250       * can be different for different windows.
1251       */
1252      c->clearpixel = xmesa_color_to_pixel( &c->mesa,
1253					    c->clearcolor[0],
1254					    c->clearcolor[1],
1255					    c->clearcolor[2],
1256					    c->clearcolor[3],
1257					    c->xm_visual->undithered_pf);
1258      XMesaSetForeground(c->display, drawBuffer->cleargc, c->clearpixel);
1259
1260      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
1261      drawBuffer->wasCurrent = GL_TRUE;
1262   }
1263   else {
1264      /* Detach */
1265      _mesa_make_current( NULL, NULL, NULL );
1266   }
1267   return GL_TRUE;
1268}
1269
1270
1271/*
1272 * Unbind the context c from its buffer.
1273 */
1274GLboolean XMesaUnbindContext( XMesaContext c )
1275{
1276   /* A no-op for XFree86 integration purposes */
1277   return GL_TRUE;
1278}
1279
1280
1281XMesaContext XMesaGetCurrentContext( void )
1282{
1283   GET_CURRENT_CONTEXT(ctx);
1284   if (ctx) {
1285      XMesaContext xmesa = XMESA_CONTEXT(ctx);
1286      return xmesa;
1287   }
1288   else {
1289      return 0;
1290   }
1291}
1292
1293
1294XMesaBuffer XMesaGetCurrentBuffer( void )
1295{
1296   GET_CURRENT_CONTEXT(ctx);
1297   if (ctx) {
1298      XMesaBuffer xmbuf = XMESA_BUFFER(ctx->DrawBuffer);
1299      return xmbuf;
1300   }
1301   else {
1302      return 0;
1303   }
1304}
1305
1306
1307/* New in Mesa 3.1 */
1308XMesaBuffer XMesaGetCurrentReadBuffer( void )
1309{
1310   GET_CURRENT_CONTEXT(ctx);
1311   if (ctx) {
1312      return XMESA_BUFFER(ctx->ReadBuffer);
1313   }
1314   else {
1315      return 0;
1316   }
1317}
1318
1319
1320
1321GLboolean XMesaSetFXmode( GLint mode )
1322{
1323   (void) mode;
1324   return GL_FALSE;
1325}
1326
1327
1328
1329/*
1330 * Copy the back buffer to the front buffer.  If there's no back buffer
1331 * this is a no-op.
1332 */
1333PUBLIC
1334void XMesaSwapBuffers( XMesaBuffer b )
1335{
1336   GET_CURRENT_CONTEXT(ctx);
1337
1338   if (!b->backxrb) {
1339      /* single buffered */
1340      return;
1341   }
1342
1343   /* If we're swapping the buffer associated with the current context
1344    * we have to flush any pending rendering commands first.
1345    */
1346   if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
1347      _mesa_notifySwapBuffers(ctx);
1348
1349   if (b->db_mode) {
1350      if (b->backxrb->ximage) {
1351	 /* Copy Ximage (back buf) from client memory to server window */
1352#if defined(USE_XSHM)
1353	 if (b->shm) {
1354            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
1355	    XShmPutImage( b->xm_visual->display, b->frontxrb->drawable,
1356			  b->swapgc,
1357			  b->backxrb->ximage, 0, 0,
1358			  0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height,
1359                          False );
1360            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
1361	 }
1362	 else
1363#endif
1364         {
1365            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
1366            XMesaPutImage( b->xm_visual->display, b->frontxrb->drawable,
1367			   b->swapgc,
1368			   b->backxrb->ximage, 0, 0,
1369			   0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height );
1370            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
1371         }
1372      }
1373      else if (b->backxrb->pixmap) {
1374	 /* Copy pixmap (back buf) to window (front buf) on server */
1375         /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
1376	 XMesaCopyArea( b->xm_visual->display,
1377			b->backxrb->pixmap,   /* source drawable */
1378			b->frontxrb->drawable,  /* dest. drawable */
1379			b->swapgc,
1380			0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height,
1381			0, 0                 /* dest region */
1382		      );
1383         /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
1384      }
1385   }
1386   XSync( b->xm_visual->display, False );
1387}
1388
1389
1390
1391/*
1392 * Copy sub-region of back buffer to front buffer
1393 */
1394void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
1395{
1396   GET_CURRENT_CONTEXT(ctx);
1397
1398   /* If we're swapping the buffer associated with the current context
1399    * we have to flush any pending rendering commands first.
1400    */
1401   if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
1402      _mesa_notifySwapBuffers(ctx);
1403
1404   if (!b->backxrb) {
1405      /* single buffered */
1406      return;
1407   }
1408
1409   if (b->db_mode) {
1410      int yTop = b->mesa_buffer.Height - y - height;
1411      if (b->backxrb->ximage) {
1412         /* Copy Ximage from host's memory to server's window */
1413#if defined(USE_XSHM)
1414         if (b->shm) {
1415            /* XXX assuming width and height aren't too large! */
1416            XShmPutImage( b->xm_visual->display, b->frontxrb->drawable,
1417                          b->swapgc,
1418                          b->backxrb->ximage, x, yTop,
1419                          x, yTop, width, height, False );
1420            /* wait for finished event??? */
1421         }
1422         else
1423#endif
1424         {
1425            /* XXX assuming width and height aren't too large! */
1426            XMesaPutImage( b->xm_visual->display, b->frontxrb->drawable,
1427			   b->swapgc,
1428			   b->backxrb->ximage, x, yTop,
1429			   x, yTop, width, height );
1430         }
1431      }
1432      else {
1433         /* Copy pixmap to window on server */
1434         XMesaCopyArea( b->xm_visual->display,
1435			b->backxrb->pixmap,           /* source drawable */
1436			b->frontxrb->drawable,        /* dest. drawable */
1437			b->swapgc,
1438			x, yTop, width, height,  /* source region */
1439			x, yTop                  /* dest region */
1440                      );
1441      }
1442   }
1443}
1444
1445
1446/*
1447 * Return a pointer to the XMesa backbuffer Pixmap or XImage.  This function
1448 * is a way to get "under the hood" of X/Mesa so one can manipulate the
1449 * back buffer directly.
1450 * Output:  pixmap - pointer to back buffer's Pixmap, or 0
1451 *          ximage - pointer to back buffer's XImage, or NULL
1452 * Return:  GL_TRUE = context is double buffered
1453 *          GL_FALSE = context is single buffered
1454 */
1455GLboolean XMesaGetBackBuffer( XMesaBuffer b,
1456                              XMesaPixmap *pixmap,
1457                              XMesaImage **ximage )
1458{
1459   if (b->db_mode) {
1460      if (pixmap)
1461         *pixmap = b->backxrb->pixmap;
1462      if (ximage)
1463         *ximage = b->backxrb->ximage;
1464      return GL_TRUE;
1465   }
1466   else {
1467      *pixmap = 0;
1468      *ximage = NULL;
1469      return GL_FALSE;
1470   }
1471}
1472
1473
1474/*
1475 * Return the depth buffer associated with an XMesaBuffer.
1476 * Input:  b - the XMesa buffer handle
1477 * Output:  width, height - size of buffer in pixels
1478 *          bytesPerValue - bytes per depth value (2 or 4)
1479 *          buffer - pointer to depth buffer values
1480 * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
1481 */
1482GLboolean XMesaGetDepthBuffer( XMesaBuffer b, GLint *width, GLint *height,
1483                               GLint *bytesPerValue, void **buffer )
1484{
1485   struct gl_renderbuffer *rb
1486      = b->mesa_buffer.Attachment[BUFFER_DEPTH].Renderbuffer;
1487   if (!rb || !rb->Data) {
1488      *width = 0;
1489      *height = 0;
1490      *bytesPerValue = 0;
1491      *buffer = 0;
1492      return GL_FALSE;
1493   }
1494   else {
1495      *width = b->mesa_buffer.Width;
1496      *height = b->mesa_buffer.Height;
1497      *bytesPerValue = b->mesa_buffer.Visual.depthBits <= 16
1498         ? sizeof(GLushort) : sizeof(GLuint);
1499      *buffer = rb->Data;
1500      return GL_TRUE;
1501   }
1502}
1503
1504
1505void XMesaFlush( XMesaContext c )
1506{
1507   if (c && c->xm_visual) {
1508      XSync( c->xm_visual->display, False );
1509   }
1510}
1511
1512
1513
1514const char *XMesaGetString( XMesaContext c, int name )
1515{
1516   (void) c;
1517   if (name==XMESA_VERSION) {
1518      return "5.0";
1519   }
1520   else if (name==XMESA_EXTENSIONS) {
1521      return "";
1522   }
1523   else {
1524      return NULL;
1525   }
1526}
1527
1528
1529
1530XMesaBuffer XMesaFindBuffer( XMesaDisplay *dpy, XMesaDrawable d )
1531{
1532   XMesaBuffer b;
1533   for (b=XMesaBufferList; b; b=b->Next) {
1534      if (b->frontxrb->drawable == d && b->display == dpy) {
1535         return b;
1536      }
1537   }
1538   return NULL;
1539}
1540
1541
1542/**
1543 * Free/destroy all XMesaBuffers associated with given display.
1544 */
1545void xmesa_destroy_buffers_on_display(XMesaDisplay *dpy)
1546{
1547   XMesaBuffer b, next;
1548   for (b = XMesaBufferList; b; b = next) {
1549      next = b->Next;
1550      if (b->display == dpy) {
1551         xmesa_free_buffer(b);
1552      }
1553   }
1554}
1555
1556
1557/*
1558 * Look for XMesaBuffers whose X window has been destroyed.
1559 * Deallocate any such XMesaBuffers.
1560 */
1561void XMesaGarbageCollect( XMesaDisplay* dpy )
1562{
1563   XMesaBuffer b, next;
1564   for (b=XMesaBufferList; b; b=next) {
1565      next = b->Next;
1566      if (b->display && b->display == dpy && b->frontxrb->drawable && b->type == WINDOW) {
1567         XSync(b->display, False);
1568         if (!window_exists( b->display, b->frontxrb->drawable )) {
1569            /* found a dead window, free the ancillary info */
1570            XMesaDestroyBuffer( b );
1571         }
1572      }
1573   }
1574}
1575
1576
1577unsigned long XMesaDitherColor( XMesaContext xmesa, GLint x, GLint y,
1578                                GLfloat red, GLfloat green,
1579                                GLfloat blue, GLfloat alpha )
1580{
1581   GLint r = (GLint) (red   * 255.0F);
1582   GLint g = (GLint) (green * 255.0F);
1583   GLint b = (GLint) (blue  * 255.0F);
1584   GLint a = (GLint) (alpha * 255.0F);
1585
1586   switch (xmesa->pixelformat) {
1587      case PF_Truecolor:
1588         {
1589            unsigned long p;
1590            PACK_TRUECOLOR( p, r, g, b );
1591            return p;
1592         }
1593      case PF_8A8B8G8R:
1594         return PACK_8A8B8G8R( r, g, b, a );
1595      case PF_8A8R8G8B:
1596         return PACK_8A8R8G8B( r, g, b, a );
1597      case PF_8R8G8B:
1598         return PACK_8R8G8B( r, g, b );
1599      case PF_5R6G5B:
1600         return PACK_5R6G5B( r, g, b );
1601      case PF_Dither_5R6G5B:
1602         /* fall through */
1603      case PF_Dither_True:
1604         {
1605            unsigned long p;
1606            PACK_TRUEDITHER(p, x, y, r, g, b);
1607            return p;
1608         }
1609      default:
1610         _mesa_problem(NULL, "Bad pixel format in XMesaDitherColor");
1611   }
1612   return 0;
1613}
1614
1615
1616/*
1617 * This is typically called when the window size changes and we need
1618 * to reallocate the buffer's back/depth/stencil/accum buffers.
1619 */
1620PUBLIC void
1621XMesaResizeBuffers( XMesaBuffer b )
1622{
1623   GET_CURRENT_CONTEXT(ctx);
1624   XMesaContext xmctx = XMESA_CONTEXT(ctx);
1625   if (!xmctx)
1626      return;
1627   xmesa_check_and_update_buffer_size(xmctx, b);
1628}
1629
1630
1631static GLint
1632xbuffer_to_renderbuffer(int buffer)
1633{
1634   assert(MAX_AUX_BUFFERS <= 4);
1635
1636   switch (buffer) {
1637   case GLX_FRONT_LEFT_EXT:
1638      return BUFFER_FRONT_LEFT;
1639   case GLX_FRONT_RIGHT_EXT:
1640      return BUFFER_FRONT_RIGHT;
1641   case GLX_BACK_LEFT_EXT:
1642      return BUFFER_BACK_LEFT;
1643   case GLX_BACK_RIGHT_EXT:
1644      return BUFFER_BACK_RIGHT;
1645   case GLX_AUX0_EXT:
1646      return BUFFER_AUX0;
1647   case GLX_AUX1_EXT:
1648   case GLX_AUX2_EXT:
1649   case GLX_AUX3_EXT:
1650   case GLX_AUX4_EXT:
1651   case GLX_AUX5_EXT:
1652   case GLX_AUX6_EXT:
1653   case GLX_AUX7_EXT:
1654   case GLX_AUX8_EXT:
1655   case GLX_AUX9_EXT:
1656   default:
1657      /* BadValue error */
1658      return -1;
1659   }
1660}
1661
1662
1663PUBLIC void
1664XMesaBindTexImage(XMesaDisplay *dpy, XMesaBuffer drawable, int buffer,
1665                  const int *attrib_list)
1666{
1667#if 0
1668   GET_CURRENT_CONTEXT(ctx);
1669   const GLuint unit = ctx->Texture.CurrentUnit;
1670   struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
1671   struct gl_texture_object *texObj;
1672#endif
1673   struct gl_renderbuffer *rb;
1674   struct xmesa_renderbuffer *xrb;
1675   GLint b;
1676   XMesaImage *img = NULL;
1677   GLboolean freeImg = GL_FALSE;
1678
1679   b = xbuffer_to_renderbuffer(buffer);
1680   if (b < 0)
1681      return;
1682
1683   if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_NONE_EXT)
1684      return; /* BadMatch error */
1685
1686   rb = drawable->mesa_buffer.Attachment[b].Renderbuffer;
1687   if (!rb) {
1688      /* invalid buffer */
1689      return;
1690   }
1691   xrb = xmesa_renderbuffer(rb);
1692
1693#if 0
1694   switch (drawable->TextureTarget) {
1695   case GLX_TEXTURE_1D_EXT:
1696      texObj = texUnit->CurrentTex[TEXTURE_1D_INDEX];
1697      break;
1698   case GLX_TEXTURE_2D_EXT:
1699      texObj = texUnit->CurrentTex[TEXTURE_2D_INDEX];
1700      break;
1701   case GLX_TEXTURE_RECTANGLE_EXT:
1702      texObj = texUnit->CurrentTex[TEXTURE_RECT_INDEX];
1703      break;
1704   default:
1705      return; /* BadMatch error */
1706   }
1707#endif
1708
1709   /*
1710    * The following is a quick and simple way to implement
1711    * BindTexImage.  The better way is to write some new FetchTexel()
1712    * functions which would extract texels from XImages.  We'd still
1713    * need to use GetImage when texturing from a Pixmap (front buffer)
1714    * but texturing from a back buffer (XImage) would avoid an image
1715    * copy.
1716    */
1717
1718   /* get XImage */
1719   if (xrb->pixmap) {
1720      img = XMesaGetImage(dpy, xrb->pixmap, 0, 0, rb->Width, rb->Height, ~0L,
1721			  ZPixmap);
1722      freeImg = GL_TRUE;
1723   }
1724   else if (xrb->ximage) {
1725      img = xrb->ximage;
1726   }
1727
1728   /* store the XImage as a new texture image */
1729   if (img) {
1730      GLenum format, type, intFormat;
1731      if (img->bits_per_pixel == 32) {
1732         format = GL_BGRA;
1733         type = GL_UNSIGNED_BYTE;
1734         intFormat = GL_RGBA;
1735      }
1736      else if (img->bits_per_pixel == 24) {
1737         format = GL_BGR;
1738         type = GL_UNSIGNED_BYTE;
1739         intFormat = GL_RGB;
1740      }
1741      else if (img->bits_per_pixel == 16) {
1742         format = GL_BGR;
1743         type = GL_UNSIGNED_SHORT_5_6_5;
1744         intFormat = GL_RGB;
1745      }
1746      else {
1747         _mesa_problem(NULL, "Unexpected XImage format in XMesaBindTexImage");
1748         return;
1749      }
1750      if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_RGBA_EXT) {
1751         intFormat = GL_RGBA;
1752      }
1753      else if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_RGB_EXT) {
1754         intFormat = GL_RGB;
1755      }
1756
1757      _mesa_TexImage2D(GL_TEXTURE_2D, 0, intFormat, rb->Width, rb->Height, 0,
1758                       format, type, img->data);
1759
1760      if (freeImg) {
1761	 XMesaDestroyImage(img);
1762      }
1763   }
1764}
1765
1766
1767
1768PUBLIC void
1769XMesaReleaseTexImage(XMesaDisplay *dpy, XMesaBuffer drawable, int buffer)
1770{
1771   const GLint b = xbuffer_to_renderbuffer(buffer);
1772   if (b < 0)
1773      return;
1774
1775   /* no-op for now */
1776}
1777
1778