xm_api.c revision a84575cdc0c8193b2c7858734e2ec6b1ec4511b2
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.
52 *
53 */
54
55#ifdef __CYGWIN__
56#undef WIN32
57#undef __WIN32__
58#endif
59
60#include "xm_api.h"
61#include "main/context.h"
62#include "main/framebuffer.h"
63
64#include "state_tracker/st_public.h"
65#include "state_tracker/st_context.h"
66#include "pipe/p_defines.h"
67#include "pipe/p_screen.h"
68#include "pipe/p_context.h"
69
70#include "trace/tr_screen.h"
71#include "trace/tr_context.h"
72#include "trace/tr_texture.h"
73
74#include "xm_winsys.h"
75#include <GL/glx.h>
76
77
78/* Driver interface routines, set up by xlib backend on library
79 * _init().  These are global in the same way that function names are
80 * global.
81 */
82static struct xm_driver driver;
83
84void xmesa_set_driver( const struct xm_driver *templ )
85{
86   driver = *templ;
87}
88
89/**
90 * Global X driver lock
91 */
92pipe_mutex _xmesa_lock;
93
94static struct pipe_screen *_screen = NULL;
95static struct pipe_screen *screen = NULL;
96
97
98/**********************************************************************/
99/*****                     X Utility Functions                    *****/
100/**********************************************************************/
101
102
103/**
104 * Return the host's byte order as LSBFirst or MSBFirst ala X.
105 */
106static int host_byte_order( void )
107{
108   int i = 1;
109   char *cptr = (char *) &i;
110   return (*cptr==1) ? LSBFirst : MSBFirst;
111}
112
113
114/**
115 * Check if the X Shared Memory extension is available.
116 * Return:  0 = not available
117 *          1 = shared XImage support available
118 *          2 = shared Pixmap support available also
119 */
120int xmesa_check_for_xshm( Display *display )
121{
122#if defined(USE_XSHM)
123   int major, minor, ignore;
124   Bool pixmaps;
125
126   if (getenv("SP_NO_RAST"))
127      return 0;
128
129   if (getenv("MESA_NOSHM")) {
130      return 0;
131   }
132
133   if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
134      if (XShmQueryVersion( display, &major, &minor, &pixmaps )==True) {
135	 return (pixmaps==True) ? 2 : 1;
136      }
137      else {
138	 return 0;
139      }
140   }
141   else {
142      return 0;
143   }
144#else
145   /* No  XSHM support */
146   return 0;
147#endif
148}
149
150
151/**
152 * Return the true number of bits per pixel for XImages.
153 * For example, if we request a 24-bit deep visual we may actually need/get
154 * 32bpp XImages.  This function returns the appropriate bpp.
155 * Input:  dpy - the X display
156 *         visinfo - desribes the visual to be used for XImages
157 * Return:  true number of bits per pixel for XImages
158 */
159static int
160bits_per_pixel( XMesaVisual xmv )
161{
162   Display *dpy = xmv->display;
163   XVisualInfo * visinfo = xmv->visinfo;
164   XImage *img;
165   int bitsPerPixel;
166   /* Create a temporary XImage */
167   img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
168		       ZPixmap, 0,           /*format, offset*/
169		       (char*) MALLOC(8),    /*data*/
170		       1, 1,                 /*width, height*/
171		       32,                   /*bitmap_pad*/
172		       0                     /*bytes_per_line*/
173                     );
174   assert(img);
175   /* grab the bits/pixel value */
176   bitsPerPixel = img->bits_per_pixel;
177   /* free the XImage */
178   free( img->data );
179   img->data = NULL;
180   XDestroyImage( img );
181   return bitsPerPixel;
182}
183
184
185
186/*
187 * Determine if a given X window ID is valid (window exists).
188 * Do this by calling XGetWindowAttributes() for the window and
189 * checking if we catch an X error.
190 * Input:  dpy - the display
191 *         win - the window to check for existance
192 * Return:  GL_TRUE - window exists
193 *          GL_FALSE - window doesn't exist
194 */
195static GLboolean WindowExistsFlag;
196
197static int window_exists_err_handler( Display* dpy, XErrorEvent* xerr )
198{
199   (void) dpy;
200   if (xerr->error_code == BadWindow) {
201      WindowExistsFlag = GL_FALSE;
202   }
203   return 0;
204}
205
206static GLboolean window_exists( Display *dpy, Window win )
207{
208   XWindowAttributes wa;
209   int (*old_handler)( Display*, XErrorEvent* );
210   WindowExistsFlag = GL_TRUE;
211   old_handler = XSetErrorHandler(window_exists_err_handler);
212   XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
213   XSetErrorHandler(old_handler);
214   return WindowExistsFlag;
215}
216
217static Status
218get_drawable_size( Display *dpy, Drawable d, uint *width, uint *height )
219{
220   Window root;
221   Status stat;
222   int xpos, ypos;
223   unsigned int w, h, bw, depth;
224   stat = XGetGeometry(dpy, d, &root, &xpos, &ypos, &w, &h, &bw, &depth);
225   *width = w;
226   *height = h;
227   return stat;
228}
229
230
231/**
232 * Return the size of the window (or pixmap) that corresponds to the
233 * given XMesaBuffer.
234 * \param width  returns width in pixels
235 * \param height  returns height in pixels
236 */
237void
238xmesa_get_window_size(Display *dpy, XMesaBuffer b,
239                      GLuint *width, GLuint *height)
240{
241   Status stat;
242
243   pipe_mutex_lock(_xmesa_lock);
244   XSync(b->xm_visual->display, 0); /* added for Chromium */
245   stat = get_drawable_size(dpy, b->drawable, width, height);
246   pipe_mutex_unlock(_xmesa_lock);
247
248   if (!stat) {
249      /* probably querying a window that's recently been destroyed */
250      _mesa_warning(NULL, "XGetGeometry failed!\n");
251      *width = *height = 1;
252   }
253}
254
255#define GET_REDMASK(__v)        __v->mesa_visual.redMask
256#define GET_GREENMASK(__v)      __v->mesa_visual.greenMask
257#define GET_BLUEMASK(__v)       __v->mesa_visual.blueMask
258
259
260/**
261 * Choose the pixel format for the given visual.
262 * This will tell the gallium driver how to pack pixel data into
263 * drawing surfaces.
264 */
265static GLuint
266choose_pixel_format(XMesaVisual v)
267{
268   boolean native_byte_order = (host_byte_order() ==
269                                ImageByteOrder(v->display));
270
271   if (   GET_REDMASK(v)   == 0x0000ff
272       && GET_GREENMASK(v) == 0x00ff00
273       && GET_BLUEMASK(v)  == 0xff0000
274       && v->BitsPerPixel == 32) {
275      if (native_byte_order) {
276         /* no byteswapping needed */
277         return 0 /* PIXEL_FORMAT_U_A8_B8_G8_R8 */;
278      }
279      else {
280         return PIPE_FORMAT_R8G8B8A8_UNORM;
281      }
282   }
283   else if (   GET_REDMASK(v)   == 0xff0000
284            && GET_GREENMASK(v) == 0x00ff00
285            && GET_BLUEMASK(v)  == 0x0000ff
286            && v->BitsPerPixel == 32) {
287      if (native_byte_order) {
288         /* no byteswapping needed */
289         return PIPE_FORMAT_A8R8G8B8_UNORM;
290      }
291      else {
292         return PIPE_FORMAT_B8G8R8A8_UNORM;
293      }
294   }
295   else if (   GET_REDMASK(v)   == 0x0000ff00
296            && GET_GREENMASK(v) == 0x00ff0000
297            && GET_BLUEMASK(v)  == 0xff000000
298            && v->BitsPerPixel == 32) {
299      if (native_byte_order) {
300         /* no byteswapping needed */
301         return PIPE_FORMAT_B8G8R8A8_UNORM;
302      }
303      else {
304         return PIPE_FORMAT_A8R8G8B8_UNORM;
305      }
306   }
307   else if (   GET_REDMASK(v)   == 0xf800
308            && GET_GREENMASK(v) == 0x07e0
309            && GET_BLUEMASK(v)  == 0x001f
310            && native_byte_order
311            && v->BitsPerPixel == 16) {
312      /* 5-6-5 RGB */
313      return PIPE_FORMAT_R5G6B5_UNORM;
314   }
315
316   assert(0);
317   return 0;
318}
319
320
321
322/**
323 * Query the default gallium screen for a Z/Stencil format that
324 * at least matches the given depthBits and stencilBits.
325 */
326static void
327xmesa_choose_z_stencil_format(int depthBits, int stencilBits,
328                              enum pipe_format *depthFormat,
329                              enum pipe_format *stencilFormat)
330{
331   const enum pipe_texture_target target = PIPE_TEXTURE_2D;
332   const unsigned tex_usage = PIPE_TEXTURE_USAGE_DEPTH_STENCIL;
333   const unsigned geom_flags = (PIPE_TEXTURE_GEOM_NON_SQUARE |
334                                PIPE_TEXTURE_GEOM_NON_POWER_OF_TWO);
335   static enum pipe_format formats[] = {
336      PIPE_FORMAT_Z24S8_UNORM,
337      PIPE_FORMAT_S8Z24_UNORM,
338      PIPE_FORMAT_Z16_UNORM,
339      PIPE_FORMAT_Z32_UNORM
340   };
341   int i;
342
343   assert(screen);
344
345   *depthFormat = *stencilFormat = PIPE_FORMAT_NONE;
346
347   /* search for supported format */
348   for (i = 0; i < Elements(formats); i++) {
349      if (screen->is_format_supported(screen, formats[i],
350                                      target, tex_usage, geom_flags)) {
351         *depthFormat = formats[i];
352         break;
353      }
354   }
355
356   if (stencilBits) {
357      *stencilFormat = *depthFormat;
358   }
359
360   /* XXX we should check that he chosen format has at least as many bits
361    * as what was requested.
362    */
363}
364
365
366
367/**********************************************************************/
368/*****                Linked list of XMesaBuffers                 *****/
369/**********************************************************************/
370
371XMesaBuffer XMesaBufferList = NULL;
372
373
374/**
375 * Allocate a new XMesaBuffer object which corresponds to the given drawable.
376 * Note that XMesaBuffer is derived from GLframebuffer.
377 * The new XMesaBuffer will not have any size (Width=Height=0).
378 *
379 * \param d  the corresponding X drawable (window or pixmap)
380 * \param type  either WINDOW, PIXMAP or PBUFFER, describing d
381 * \param vis  the buffer's visual
382 * \param cmap  the window's colormap, if known.
383 * \return new XMesaBuffer or NULL if any problem
384 */
385static XMesaBuffer
386create_xmesa_buffer(Drawable d, BufferType type,
387                    XMesaVisual vis, Colormap cmap)
388{
389   XMesaBuffer b;
390   GLframebuffer *fb;
391   enum pipe_format colorFormat, depthFormat, stencilFormat;
392   uint width, height;
393
394   ASSERT(type == WINDOW || type == PIXMAP || type == PBUFFER);
395
396   b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
397   if (!b)
398      return NULL;
399
400   b->drawable = d;
401
402   b->xm_visual = vis;
403   b->type = type;
404   b->cmap = cmap;
405
406   /* determine PIPE_FORMATs for buffers */
407   colorFormat = choose_pixel_format(vis);
408
409   xmesa_choose_z_stencil_format(vis->mesa_visual.depthBits,
410                                 vis->mesa_visual.stencilBits,
411                                 &depthFormat, &stencilFormat);
412
413
414   get_drawable_size(vis->display, d, &width, &height);
415
416   /*
417    * Create framebuffer, but we'll plug in our own renderbuffers below.
418    */
419   b->stfb = st_create_framebuffer(&vis->mesa_visual,
420                                   colorFormat, depthFormat, stencilFormat,
421                                   width, height,
422                                   (void *) b);
423   fb = &b->stfb->Base;
424
425   /*
426    * Create scratch XImage for xmesa_display_surface()
427    */
428   b->tempImage = XCreateImage(vis->display,
429                               vis->visinfo->visual,
430                               vis->visinfo->depth,
431                               ZPixmap, 0,   /* format, offset */
432                               NULL,         /* data */
433                               0, 0,         /* size */
434                               32,           /* bitmap_pad */
435                               0);           /* bytes_per_line */
436
437   /* GLX_EXT_texture_from_pixmap */
438   b->TextureTarget = 0;
439   b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;
440   b->TextureMipmap = 0;
441
442   /* insert buffer into linked list */
443   b->Next = XMesaBufferList;
444   XMesaBufferList = b;
445
446   return b;
447}
448
449
450/**
451 * Find an XMesaBuffer by matching X display and colormap but NOT matching
452 * the notThis buffer.
453 */
454XMesaBuffer
455xmesa_find_buffer(Display *dpy, Colormap cmap, XMesaBuffer notThis)
456{
457   XMesaBuffer b;
458   for (b = XMesaBufferList; b; b = b->Next) {
459      if (b->xm_visual->display == dpy &&
460          b->cmap == cmap &&
461          b != notThis) {
462         return b;
463      }
464   }
465   return NULL;
466}
467
468
469/**
470 * Remove buffer from linked list, delete if no longer referenced.
471 */
472static void
473xmesa_free_buffer(XMesaBuffer buffer)
474{
475   XMesaBuffer prev = NULL, b;
476
477   for (b = XMesaBufferList; b; b = b->Next) {
478      if (b == buffer) {
479         struct gl_framebuffer *fb = &buffer->stfb->Base;
480
481         /* unlink buffer from list */
482         if (prev)
483            prev->Next = buffer->Next;
484         else
485            XMesaBufferList = buffer->Next;
486
487         /* mark as delete pending */
488         fb->DeletePending = GL_TRUE;
489
490         /* Since the X window for the XMesaBuffer is going away, we don't
491          * want to dereference this pointer in the future.
492          */
493         b->drawable = 0;
494
495         buffer->tempImage->data = NULL;
496         XDestroyImage(buffer->tempImage);
497
498         /* Unreference.  If count = zero we'll really delete the buffer */
499         _mesa_reference_framebuffer(&fb, NULL);
500
501         XFreeGC(b->xm_visual->display, b->gc);
502
503         free(buffer);
504
505         return;
506      }
507      /* continue search */
508      prev = b;
509   }
510   /* buffer not found in XMesaBufferList */
511   _mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");
512}
513
514
515
516/**********************************************************************/
517/*****                   Misc Private Functions                   *****/
518/**********************************************************************/
519
520
521/**
522 * When a context is bound for the first time, we can finally finish
523 * initializing the context's visual and buffer information.
524 * \param v  the XMesaVisual to initialize
525 * \param b  the XMesaBuffer to initialize (may be NULL)
526 * \param rgb_flag  TRUE = RGBA mode, FALSE = color index mode
527 * \param window  the window/pixmap we're rendering into
528 * \param cmap  the colormap associated with the window/pixmap
529 * \return GL_TRUE=success, GL_FALSE=failure
530 */
531static GLboolean
532initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,
533                             GLboolean rgb_flag, Drawable window,
534                             Colormap cmap)
535{
536   ASSERT(!b || b->xm_visual == v);
537
538   /* Save true bits/pixel */
539   v->BitsPerPixel = bits_per_pixel(v);
540   assert(v->BitsPerPixel > 0);
541
542   if (rgb_flag == GL_FALSE) {
543      /* COLOR-INDEXED WINDOW: not supported*/
544      return GL_FALSE;
545   }
546   else {
547      /* RGB WINDOW:
548       * We support RGB rendering into almost any kind of visual.
549       */
550      const int xclass = v->mesa_visual.visualType;
551      if (xclass != GLX_TRUE_COLOR && xclass == !GLX_DIRECT_COLOR) {
552	 _mesa_warning(NULL,
553            "XMesa: RGB mode rendering not supported in given visual.\n");
554	 return GL_FALSE;
555      }
556      v->mesa_visual.indexBits = 0;
557
558      if (v->BitsPerPixel == 32) {
559         /* We use XImages for all front/back buffers.  If an X Window or
560          * X Pixmap is 32bpp, there's no guarantee that the alpha channel
561          * will be preserved.  For XImages we're in luck.
562          */
563         v->mesa_visual.alphaBits = 8;
564      }
565   }
566
567   /*
568    * If MESA_INFO env var is set print out some debugging info
569    * which can help Brian figure out what's going on when a user
570    * reports bugs.
571    */
572   if (_mesa_getenv("MESA_INFO")) {
573      printf("X/Mesa visual = %p\n", (void *) v);
574      printf("X/Mesa level = %d\n", v->mesa_visual.level);
575      printf("X/Mesa depth = %d\n", v->visinfo->depth);
576      printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
577   }
578
579   if (b && window) {
580      /* these should have been set in create_xmesa_buffer */
581      ASSERT(b->drawable == window);
582
583      /* Setup for single/double buffering */
584      if (v->mesa_visual.doubleBufferMode) {
585         /* Double buffered */
586         b->shm = xmesa_check_for_xshm( v->display );
587      }
588
589      /* X11 graphics context */
590      b->gc = XCreateGC( v->display, window, 0, NULL );
591      XSetFunction( v->display, b->gc, GXcopy );
592   }
593
594   return GL_TRUE;
595}
596
597
598
599#define NUM_VISUAL_TYPES   6
600
601/**
602 * Convert an X visual type to a GLX visual type.
603 *
604 * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
605 *        to be converted.
606 * \return If \c visualType is a valid X visual type, a GLX visual type will
607 *         be returned.  Otherwise \c GLX_NONE will be returned.
608 *
609 * \note
610 * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
611 * DRI CVS tree.
612 */
613static GLint
614xmesa_convert_from_x_visual_type( int visualType )
615{
616    static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
617	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
618	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
619	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
620    };
621
622    return ( (unsigned) visualType < NUM_VISUAL_TYPES )
623	? glx_visual_types[ visualType ] : GLX_NONE;
624}
625
626
627/**********************************************************************/
628/*****                       Public Functions                     *****/
629/**********************************************************************/
630
631
632/*
633 * Create a new X/Mesa visual.
634 * Input:  display - X11 display
635 *         visinfo - an XVisualInfo pointer
636 *         rgb_flag - GL_TRUE = RGB mode,
637 *                    GL_FALSE = color index mode
638 *         alpha_flag - alpha buffer requested?
639 *         db_flag - GL_TRUE = double-buffered,
640 *                   GL_FALSE = single buffered
641 *         stereo_flag - stereo visual?
642 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
643 *                       GL_FALSE = use an off-screen pixmap for back buffer
644 *         depth_size - requested bits/depth values, or zero
645 *         stencil_size - requested bits/stencil values, or zero
646 *         accum_red_size - requested bits/red accum values, or zero
647 *         accum_green_size - requested bits/green accum values, or zero
648 *         accum_blue_size - requested bits/blue accum values, or zero
649 *         accum_alpha_size - requested bits/alpha accum values, or zero
650 *         num_samples - number of samples/pixel if multisampling, or zero
651 *         level - visual level, usually 0
652 *         visualCaveat - ala the GLX extension, usually GLX_NONE
653 * Return;  a new XMesaVisual or 0 if error.
654 */
655PUBLIC
656XMesaVisual XMesaCreateVisual( Display *display,
657                               XVisualInfo * visinfo,
658                               GLboolean rgb_flag,
659                               GLboolean alpha_flag,
660                               GLboolean db_flag,
661                               GLboolean stereo_flag,
662                               GLboolean ximage_flag,
663                               GLint depth_size,
664                               GLint stencil_size,
665                               GLint accum_red_size,
666                               GLint accum_green_size,
667                               GLint accum_blue_size,
668                               GLint accum_alpha_size,
669                               GLint num_samples,
670                               GLint level,
671                               GLint visualCaveat )
672{
673   XMesaVisual v;
674   GLint red_bits, green_bits, blue_bits, alpha_bits;
675
676   xmesa_init();
677
678   /* For debugging only */
679   if (_mesa_getenv("MESA_XSYNC")) {
680      /* This makes debugging X easier.
681       * In your debugger, set a breakpoint on _XError to stop when an
682       * X protocol error is generated.
683       */
684      XSynchronize( display, 1 );
685   }
686
687   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
688   if (!v) {
689      return NULL;
690   }
691
692   v->display = display;
693
694   /* Save a copy of the XVisualInfo struct because the user may Xfree()
695    * the struct but we may need some of the information contained in it
696    * at a later time.
697    */
698   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
699   if (!v->visinfo) {
700      free(v);
701      return NULL;
702   }
703   memcpy(v->visinfo, visinfo, sizeof(*visinfo));
704
705   v->ximage_flag = ximage_flag;
706
707   v->mesa_visual.redMask = visinfo->red_mask;
708   v->mesa_visual.greenMask = visinfo->green_mask;
709   v->mesa_visual.blueMask = visinfo->blue_mask;
710   v->mesa_visual.visualID = visinfo->visualid;
711   v->mesa_visual.screen = visinfo->screen;
712
713#if !(defined(__cplusplus) || defined(c_plusplus))
714   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->class);
715#else
716   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
717#endif
718
719   v->mesa_visual.visualRating = visualCaveat;
720
721   if (alpha_flag)
722      v->mesa_visual.alphaBits = 8;
723
724   (void) initialize_visual_and_buffer( v, NULL, rgb_flag, 0, 0 );
725
726   {
727      const int xclass = v->mesa_visual.visualType;
728      if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
729         red_bits   = _mesa_bitcount(GET_REDMASK(v));
730         green_bits = _mesa_bitcount(GET_GREENMASK(v));
731         blue_bits  = _mesa_bitcount(GET_BLUEMASK(v));
732      }
733      else {
734         /* this is an approximation */
735         int depth;
736         depth = v->visinfo->depth;
737         red_bits = depth / 3;
738         depth -= red_bits;
739         green_bits = depth / 2;
740         depth -= green_bits;
741         blue_bits = depth;
742         alpha_bits = 0;
743         assert( red_bits + green_bits + blue_bits == v->visinfo->depth );
744      }
745      alpha_bits = v->mesa_visual.alphaBits;
746   }
747
748   _mesa_initialize_visual( &v->mesa_visual,
749                            rgb_flag, db_flag, stereo_flag,
750                            red_bits, green_bits,
751                            blue_bits, alpha_bits,
752                            v->mesa_visual.indexBits,
753                            depth_size,
754                            stencil_size,
755                            accum_red_size, accum_green_size,
756                            accum_blue_size, accum_alpha_size,
757                            0 );
758
759   /* XXX minor hack */
760   v->mesa_visual.level = level;
761   return v;
762}
763
764
765PUBLIC
766void XMesaDestroyVisual( XMesaVisual v )
767{
768   free(v->visinfo);
769   free(v);
770}
771
772
773/**
774 * Do one-time initializations.
775 */
776void
777xmesa_init(void)
778{
779   static GLboolean firstTime = GL_TRUE;
780   if (firstTime) {
781      pipe_mutex_init(_xmesa_lock);
782      _screen = driver.create_pipe_screen();
783      screen = trace_screen_create( _screen );
784      firstTime = GL_FALSE;
785   }
786}
787
788
789/**
790 * Create a new XMesaContext.
791 * \param v  the XMesaVisual
792 * \param share_list  another XMesaContext with which to share display
793 *                    lists or NULL if no sharing is wanted.
794 * \return an XMesaContext or NULL if error.
795 */
796PUBLIC
797XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
798{
799   struct pipe_context *pipe = NULL;
800   XMesaContext c;
801   GLcontext *mesaCtx;
802   uint pf;
803
804   xmesa_init();
805
806   /* Note: the XMesaContext contains a Mesa GLcontext struct (inheritance) */
807   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
808   if (!c)
809      return NULL;
810
811   pf = choose_pixel_format(v);
812   assert(pf);
813
814   c->xm_visual = v;
815   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
816   c->xm_read_buffer = NULL;
817
818   if (screen == NULL)
819      goto fail;
820
821   /* Trace screen knows how to properly wrap context creation in the
822    * wrapped screen, so nothing special to do here:
823    */
824   pipe = screen->context_create(screen, (void *) c);
825   if (pipe == NULL)
826      goto fail;
827
828   c->st = st_create_context(pipe,
829                             &v->mesa_visual,
830                             share_list ? share_list->st : NULL);
831   if (c->st == NULL)
832      goto fail;
833
834   mesaCtx = c->st->ctx;
835   c->st->ctx->DriverCtx = c;
836
837   return c;
838
839fail:
840   if (c->st)
841      st_destroy_context(c->st);
842   else if (pipe)
843      pipe->destroy(pipe);
844
845   free(c);
846   return NULL;
847}
848
849
850
851PUBLIC
852void XMesaDestroyContext( XMesaContext c )
853{
854   st_destroy_context(c->st);
855
856   /* FIXME: We should destroy the screen here, but if we do so, surfaces may
857    * outlive it, causing segfaults
858   struct pipe_screen *screen = c->st->pipe->screen;
859   screen->destroy(screen);
860   */
861
862   free(c);
863}
864
865
866
867/**
868 * Private function for creating an XMesaBuffer which corresponds to an
869 * X window or pixmap.
870 * \param v  the window's XMesaVisual
871 * \param w  the window we're wrapping
872 * \return  new XMesaBuffer or NULL if error
873 */
874PUBLIC XMesaBuffer
875XMesaCreateWindowBuffer(XMesaVisual v, Window w)
876{
877   XWindowAttributes attr;
878   XMesaBuffer b;
879   Colormap cmap;
880   int depth;
881
882   assert(v);
883   assert(w);
884
885   /* Check that window depth matches visual depth */
886   XGetWindowAttributes( v->display, w, &attr );
887   depth = attr.depth;
888   if (v->visinfo->depth != depth) {
889      _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",
890                    v->visinfo->depth, depth);
891      return NULL;
892   }
893
894   /* Find colormap */
895   if (attr.colormap) {
896      cmap = attr.colormap;
897   }
898   else {
899      _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
900      /* this is weird, a window w/out a colormap!? */
901      /* OK, let's just allocate a new one and hope for the best */
902      cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
903   }
904
905   b = create_xmesa_buffer((Drawable) w, WINDOW, v, cmap);
906   if (!b)
907      return NULL;
908
909   if (!initialize_visual_and_buffer( v, b, v->mesa_visual.rgbMode,
910                                      (Drawable) w, cmap )) {
911      xmesa_free_buffer(b);
912      return NULL;
913   }
914
915   return b;
916}
917
918
919
920/**
921 * Create a new XMesaBuffer from an X pixmap.
922 *
923 * \param v    the XMesaVisual
924 * \param p    the pixmap
925 * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
926 *             \c GLX_DIRECT_COLOR visual for the pixmap
927 * \returns new XMesaBuffer or NULL if error
928 */
929PUBLIC XMesaBuffer
930XMesaCreatePixmapBuffer(XMesaVisual v, Pixmap p, Colormap cmap)
931{
932   XMesaBuffer b;
933
934   assert(v);
935
936   b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
937   if (!b)
938      return NULL;
939
940   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
941				     (Drawable) p, cmap)) {
942      xmesa_free_buffer(b);
943      return NULL;
944   }
945
946   return b;
947}
948
949
950/**
951 * For GLX_EXT_texture_from_pixmap
952 */
953XMesaBuffer
954XMesaCreatePixmapTextureBuffer(XMesaVisual v, Pixmap p,
955                               Colormap cmap,
956                               int format, int target, int mipmap)
957{
958   GET_CURRENT_CONTEXT(ctx);
959   XMesaBuffer b;
960   GLuint width, height;
961
962   assert(v);
963
964   b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
965   if (!b)
966      return NULL;
967
968   /* get pixmap size, update framebuffer/renderbuffer dims */
969   xmesa_get_window_size(v->display, b, &width, &height);
970   _mesa_resize_framebuffer(NULL, &(b->stfb->Base), width, height);
971
972   if (target == 0) {
973      /* examine dims */
974      if (ctx->Extensions.ARB_texture_non_power_of_two) {
975         target = GLX_TEXTURE_2D_EXT;
976      }
977      else if (   _mesa_bitcount(width)  == 1
978               && _mesa_bitcount(height) == 1) {
979         /* power of two size */
980         if (height == 1) {
981            target = GLX_TEXTURE_1D_EXT;
982         }
983         else {
984            target = GLX_TEXTURE_2D_EXT;
985         }
986      }
987      else if (ctx->Extensions.NV_texture_rectangle) {
988         target = GLX_TEXTURE_RECTANGLE_EXT;
989      }
990      else {
991         /* non power of two textures not supported */
992         XMesaDestroyBuffer(b);
993         return 0;
994      }
995   }
996
997   b->TextureTarget = target;
998   b->TextureFormat = format;
999   b->TextureMipmap = mipmap;
1000
1001   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
1002				     (Drawable) p, cmap)) {
1003      xmesa_free_buffer(b);
1004      return NULL;
1005   }
1006
1007   return b;
1008}
1009
1010
1011
1012XMesaBuffer
1013XMesaCreatePBuffer(XMesaVisual v, Colormap cmap,
1014                   unsigned int width, unsigned int height)
1015{
1016   Window root;
1017   Drawable drawable;  /* X Pixmap Drawable */
1018   XMesaBuffer b;
1019
1020   /* allocate pixmap for front buffer */
1021   root = RootWindow( v->display, v->visinfo->screen );
1022   drawable = XCreatePixmap(v->display, root, width, height,
1023                            v->visinfo->depth);
1024   if (!drawable)
1025      return NULL;
1026
1027   b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);
1028   if (!b)
1029      return NULL;
1030
1031   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
1032				     drawable, cmap)) {
1033      xmesa_free_buffer(b);
1034      return NULL;
1035   }
1036
1037   return b;
1038}
1039
1040
1041
1042/*
1043 * Deallocate an XMesaBuffer structure and all related info.
1044 */
1045PUBLIC void
1046XMesaDestroyBuffer(XMesaBuffer b)
1047{
1048   xmesa_free_buffer(b);
1049}
1050
1051
1052/**
1053 * Query the current window size and update the corresponding GLframebuffer
1054 * and all attached renderbuffers.
1055 * Called when:
1056 *  1. the first time a buffer is bound to a context.
1057 *  2. SwapBuffers.  XXX probabaly from xm_flush_frontbuffer() too...
1058 * Note: it's possible (and legal) for xmctx to be NULL.  That can happen
1059 * when resizing a buffer when no rendering context is bound.
1060 */
1061void
1062xmesa_check_and_update_buffer_size(XMesaContext xmctx, XMesaBuffer drawBuffer)
1063{
1064   GLuint width, height;
1065   xmesa_get_window_size(drawBuffer->xm_visual->display, drawBuffer, &width, &height);
1066   st_resize_framebuffer(drawBuffer->stfb, width, height);
1067}
1068
1069
1070
1071
1072/*
1073 * Bind buffer b to context c and make c the current rendering context.
1074 */
1075PUBLIC
1076GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
1077                             XMesaBuffer readBuffer )
1078{
1079   XMesaContext old_ctx = XMesaGetCurrentContext();
1080
1081   if (old_ctx && old_ctx != c) {
1082      XMesaFlush(old_ctx);
1083      old_ctx->xm_buffer = NULL;
1084      old_ctx->xm_read_buffer = NULL;
1085   }
1086
1087   if (c) {
1088      if (!drawBuffer || !readBuffer)
1089         return GL_FALSE;  /* must specify buffers! */
1090
1091      if (c == old_ctx &&
1092	  c->xm_buffer == drawBuffer &&
1093	  c->xm_read_buffer == readBuffer)
1094	 return GL_TRUE;
1095
1096      c->xm_buffer = drawBuffer;
1097      c->xm_read_buffer = readBuffer;
1098
1099      st_make_current(c->st, drawBuffer->stfb, readBuffer->stfb);
1100
1101      xmesa_check_and_update_buffer_size(c, drawBuffer);
1102      if (readBuffer != drawBuffer)
1103         xmesa_check_and_update_buffer_size(c, readBuffer);
1104
1105      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
1106      drawBuffer->wasCurrent = GL_TRUE;
1107   }
1108   else {
1109      /* Detach */
1110      st_make_current( NULL, NULL, NULL );
1111
1112   }
1113   return GL_TRUE;
1114}
1115
1116
1117/*
1118 * Unbind the context c from its buffer.
1119 */
1120GLboolean XMesaUnbindContext( XMesaContext c )
1121{
1122   /* A no-op for XFree86 integration purposes */
1123   return GL_TRUE;
1124}
1125
1126
1127XMesaContext XMesaGetCurrentContext( void )
1128{
1129   GET_CURRENT_CONTEXT(ctx);
1130   if (ctx) {
1131      XMesaContext xmesa = xmesa_context(ctx);
1132      return xmesa;
1133   }
1134   else {
1135      return 0;
1136   }
1137}
1138
1139
1140
1141/**
1142 * Swap front and back color buffers and have winsys display front buffer.
1143 * If there's no front color buffer no swap actually occurs.
1144 */
1145PUBLIC
1146void XMesaSwapBuffers( XMesaBuffer b )
1147{
1148   struct pipe_surface *frontLeftSurf;
1149
1150   st_swapbuffers(b->stfb, &frontLeftSurf, NULL);
1151
1152   if (frontLeftSurf) {
1153      if (_screen != screen) {
1154         struct trace_surface *tr_surf = trace_surface( frontLeftSurf );
1155         struct pipe_surface *surf = tr_surf->surface;
1156         frontLeftSurf = surf;
1157      }
1158
1159      driver.display_surface(b, frontLeftSurf);
1160   }
1161
1162   xmesa_check_and_update_buffer_size(NULL, b);
1163}
1164
1165
1166
1167/*
1168 * Copy sub-region of back buffer to front buffer
1169 */
1170void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
1171{
1172   struct pipe_surface *surf_front;
1173   struct pipe_surface *surf_back;
1174   struct pipe_context *pipe = NULL; /* XXX fix */
1175
1176   st_get_framebuffer_surface(b->stfb, ST_SURFACE_FRONT_LEFT, &surf_front);
1177   st_get_framebuffer_surface(b->stfb, ST_SURFACE_BACK_LEFT, &surf_back);
1178
1179   if (!surf_front || !surf_back)
1180      return;
1181
1182   assert(pipe);
1183   pipe->surface_copy(pipe,
1184                      surf_front, x, y,  /* dest */
1185                      surf_back, x, y,   /* src */
1186                      width, height);
1187}
1188
1189
1190
1191void XMesaFlush( XMesaContext c )
1192{
1193   if (c && c->xm_visual->display) {
1194      st_finish(c->st);
1195      XSync( c->xm_visual->display, False );
1196   }
1197}
1198
1199
1200
1201
1202
1203XMesaBuffer XMesaFindBuffer( Display *dpy, Drawable d )
1204{
1205   XMesaBuffer b;
1206   for (b = XMesaBufferList; b; b = b->Next) {
1207      if (b->drawable == d && b->xm_visual->display == dpy) {
1208         return b;
1209      }
1210   }
1211   return NULL;
1212}
1213
1214
1215/**
1216 * Free/destroy all XMesaBuffers associated with given display.
1217 */
1218void xmesa_destroy_buffers_on_display(Display *dpy)
1219{
1220   XMesaBuffer b, next;
1221   for (b = XMesaBufferList; b; b = next) {
1222      next = b->Next;
1223      if (b->xm_visual->display == dpy) {
1224         xmesa_free_buffer(b);
1225      }
1226   }
1227}
1228
1229
1230/*
1231 * Look for XMesaBuffers whose X window has been destroyed.
1232 * Deallocate any such XMesaBuffers.
1233 */
1234void XMesaGarbageCollect( void )
1235{
1236   XMesaBuffer b, next;
1237   for (b=XMesaBufferList; b; b=next) {
1238      next = b->Next;
1239      if (b->xm_visual &&
1240          b->xm_visual->display &&
1241          b->drawable &&
1242          b->type == WINDOW) {
1243         XSync(b->xm_visual->display, False);
1244         if (!window_exists( b->xm_visual->display, b->drawable )) {
1245            /* found a dead window, free the ancillary info */
1246            XMesaDestroyBuffer( b );
1247         }
1248      }
1249   }
1250}
1251
1252
1253
1254
1255PUBLIC void
1256XMesaBindTexImage(Display *dpy, XMesaBuffer drawable, int buffer,
1257                  const int *attrib_list)
1258{
1259}
1260
1261
1262
1263PUBLIC void
1264XMesaReleaseTexImage(Display *dpy, XMesaBuffer drawable, int buffer)
1265{
1266}
1267
1268