xm_api.c revision f7830dc3916b355452f656dba955804fd7535544
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/*****                Linked list of XMesaBuffers                 *****/
324/**********************************************************************/
325
326XMesaBuffer XMesaBufferList = NULL;
327
328
329/**
330 * Allocate a new XMesaBuffer object which corresponds to the given drawable.
331 * Note that XMesaBuffer is derived from GLframebuffer.
332 * The new XMesaBuffer will not have any size (Width=Height=0).
333 *
334 * \param d  the corresponding X drawable (window or pixmap)
335 * \param type  either WINDOW, PIXMAP or PBUFFER, describing d
336 * \param vis  the buffer's visual
337 * \param cmap  the window's colormap, if known.
338 * \return new XMesaBuffer or NULL if any problem
339 */
340static XMesaBuffer
341create_xmesa_buffer(Drawable d, BufferType type,
342                    XMesaVisual vis, Colormap cmap)
343{
344   XMesaBuffer b;
345   GLframebuffer *fb;
346   enum pipe_format colorFormat, depthFormat, stencilFormat;
347   uint width, height;
348
349   ASSERT(type == WINDOW || type == PIXMAP || type == PBUFFER);
350
351   b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
352   if (!b)
353      return NULL;
354
355   b->drawable = d;
356
357   b->xm_visual = vis;
358   b->type = type;
359   b->cmap = cmap;
360
361   /* determine PIPE_FORMATs for buffers */
362   colorFormat = choose_pixel_format(vis);
363
364   if (vis->mesa_visual.depthBits == 0)
365      depthFormat = PIPE_FORMAT_NONE;
366#ifdef GALLIUM_CELL /* XXX temporary for Cell! */
367   else
368      depthFormat = PIPE_FORMAT_S8Z24_UNORM;
369#else
370   else if (vis->mesa_visual.depthBits <= 16)
371      depthFormat = PIPE_FORMAT_Z16_UNORM;
372   else if (vis->mesa_visual.depthBits <= 24)
373      depthFormat = PIPE_FORMAT_S8Z24_UNORM;
374   else
375      depthFormat = PIPE_FORMAT_Z32_UNORM;
376#endif
377
378   if (vis->mesa_visual.stencilBits == 8) {
379      if (depthFormat == PIPE_FORMAT_S8Z24_UNORM ||
380          depthFormat == PIPE_FORMAT_Z24S8_UNORM)
381         stencilFormat = depthFormat;
382      else
383         stencilFormat = PIPE_FORMAT_S8_UNORM;
384   }
385   else {
386      /* no stencil */
387      stencilFormat = PIPE_FORMAT_NONE;
388      if (depthFormat == PIPE_FORMAT_S8Z24_UNORM) {
389         /* use 24-bit Z, undefined stencil channel */
390         depthFormat = PIPE_FORMAT_X8Z24_UNORM;
391      }
392      else if (depthFormat == PIPE_FORMAT_Z24S8_UNORM) {
393         /* use 24-bit Z, undefined stencil channel */
394         depthFormat = PIPE_FORMAT_Z24X8_UNORM;
395      }
396   }
397
398
399   get_drawable_size(vis->display, d, &width, &height);
400
401   /*
402    * Create framebuffer, but we'll plug in our own renderbuffers below.
403    */
404   b->stfb = st_create_framebuffer(&vis->mesa_visual,
405                                   colorFormat, depthFormat, stencilFormat,
406                                   width, height,
407                                   (void *) b);
408   fb = &b->stfb->Base;
409
410   /*
411    * Create scratch XImage for xmesa_display_surface()
412    */
413   b->tempImage = XCreateImage(vis->display,
414                               vis->visinfo->visual,
415                               vis->visinfo->depth,
416                               ZPixmap, 0,   /* format, offset */
417                               NULL,         /* data */
418                               0, 0,         /* size */
419                               32,           /* bitmap_pad */
420                               0);           /* bytes_per_line */
421
422   /* GLX_EXT_texture_from_pixmap */
423   b->TextureTarget = 0;
424   b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;
425   b->TextureMipmap = 0;
426
427   /* insert buffer into linked list */
428   b->Next = XMesaBufferList;
429   XMesaBufferList = b;
430
431   return b;
432}
433
434
435/**
436 * Find an XMesaBuffer by matching X display and colormap but NOT matching
437 * the notThis buffer.
438 */
439XMesaBuffer
440xmesa_find_buffer(Display *dpy, Colormap cmap, XMesaBuffer notThis)
441{
442   XMesaBuffer b;
443   for (b = XMesaBufferList; b; b = b->Next) {
444      if (b->xm_visual->display == dpy &&
445          b->cmap == cmap &&
446          b != notThis) {
447         return b;
448      }
449   }
450   return NULL;
451}
452
453
454/**
455 * Remove buffer from linked list, delete if no longer referenced.
456 */
457static void
458xmesa_free_buffer(XMesaBuffer buffer)
459{
460   XMesaBuffer prev = NULL, b;
461
462   for (b = XMesaBufferList; b; b = b->Next) {
463      if (b == buffer) {
464         struct gl_framebuffer *fb = &buffer->stfb->Base;
465
466         /* unlink buffer from list */
467         if (prev)
468            prev->Next = buffer->Next;
469         else
470            XMesaBufferList = buffer->Next;
471
472         /* mark as delete pending */
473         fb->DeletePending = GL_TRUE;
474
475         /* Since the X window for the XMesaBuffer is going away, we don't
476          * want to dereference this pointer in the future.
477          */
478         b->drawable = 0;
479
480         buffer->tempImage->data = NULL;
481         XDestroyImage(buffer->tempImage);
482
483         /* Unreference.  If count = zero we'll really delete the buffer */
484         _mesa_reference_framebuffer(&fb, NULL);
485
486         XFreeGC(b->xm_visual->display, b->gc);
487
488         free(buffer);
489
490         return;
491      }
492      /* continue search */
493      prev = b;
494   }
495   /* buffer not found in XMesaBufferList */
496   _mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");
497}
498
499
500
501/**********************************************************************/
502/*****                   Misc Private Functions                   *****/
503/**********************************************************************/
504
505
506/**
507 * When a context is bound for the first time, we can finally finish
508 * initializing the context's visual and buffer information.
509 * \param v  the XMesaVisual to initialize
510 * \param b  the XMesaBuffer to initialize (may be NULL)
511 * \param rgb_flag  TRUE = RGBA mode, FALSE = color index mode
512 * \param window  the window/pixmap we're rendering into
513 * \param cmap  the colormap associated with the window/pixmap
514 * \return GL_TRUE=success, GL_FALSE=failure
515 */
516static GLboolean
517initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,
518                             GLboolean rgb_flag, Drawable window,
519                             Colormap cmap)
520{
521   ASSERT(!b || b->xm_visual == v);
522
523   /* Save true bits/pixel */
524   v->BitsPerPixel = bits_per_pixel(v);
525   assert(v->BitsPerPixel > 0);
526
527   if (rgb_flag == GL_FALSE) {
528      /* COLOR-INDEXED WINDOW: not supported*/
529      return GL_FALSE;
530   }
531   else {
532      /* RGB WINDOW:
533       * We support RGB rendering into almost any kind of visual.
534       */
535      const int xclass = v->mesa_visual.visualType;
536      if (xclass != GLX_TRUE_COLOR && xclass == !GLX_DIRECT_COLOR) {
537	 _mesa_warning(NULL,
538            "XMesa: RGB mode rendering not supported in given visual.\n");
539	 return GL_FALSE;
540      }
541      v->mesa_visual.indexBits = 0;
542
543      if (v->BitsPerPixel == 32) {
544         /* We use XImages for all front/back buffers.  If an X Window or
545          * X Pixmap is 32bpp, there's no guarantee that the alpha channel
546          * will be preserved.  For XImages we're in luck.
547          */
548         v->mesa_visual.alphaBits = 8;
549      }
550   }
551
552   /*
553    * If MESA_INFO env var is set print out some debugging info
554    * which can help Brian figure out what's going on when a user
555    * reports bugs.
556    */
557   if (_mesa_getenv("MESA_INFO")) {
558      printf("X/Mesa visual = %p\n", (void *) v);
559      printf("X/Mesa level = %d\n", v->mesa_visual.level);
560      printf("X/Mesa depth = %d\n", v->visinfo->depth);
561      printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
562   }
563
564   if (b && window) {
565      /* these should have been set in create_xmesa_buffer */
566      ASSERT(b->drawable == window);
567
568      /* Setup for single/double buffering */
569      if (v->mesa_visual.doubleBufferMode) {
570         /* Double buffered */
571         b->shm = xmesa_check_for_xshm( v->display );
572      }
573
574      /* X11 graphics context */
575      b->gc = XCreateGC( v->display, window, 0, NULL );
576      XSetFunction( v->display, b->gc, GXcopy );
577   }
578
579   return GL_TRUE;
580}
581
582
583
584#define NUM_VISUAL_TYPES   6
585
586/**
587 * Convert an X visual type to a GLX visual type.
588 *
589 * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
590 *        to be converted.
591 * \return If \c visualType is a valid X visual type, a GLX visual type will
592 *         be returned.  Otherwise \c GLX_NONE will be returned.
593 *
594 * \note
595 * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
596 * DRI CVS tree.
597 */
598static GLint
599xmesa_convert_from_x_visual_type( int visualType )
600{
601    static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
602	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
603	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
604	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
605    };
606
607    return ( (unsigned) visualType < NUM_VISUAL_TYPES )
608	? glx_visual_types[ visualType ] : GLX_NONE;
609}
610
611
612/**********************************************************************/
613/*****                       Public Functions                     *****/
614/**********************************************************************/
615
616
617/*
618 * Create a new X/Mesa visual.
619 * Input:  display - X11 display
620 *         visinfo - an XVisualInfo pointer
621 *         rgb_flag - GL_TRUE = RGB mode,
622 *                    GL_FALSE = color index mode
623 *         alpha_flag - alpha buffer requested?
624 *         db_flag - GL_TRUE = double-buffered,
625 *                   GL_FALSE = single buffered
626 *         stereo_flag - stereo visual?
627 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
628 *                       GL_FALSE = use an off-screen pixmap for back buffer
629 *         depth_size - requested bits/depth values, or zero
630 *         stencil_size - requested bits/stencil values, or zero
631 *         accum_red_size - requested bits/red accum values, or zero
632 *         accum_green_size - requested bits/green accum values, or zero
633 *         accum_blue_size - requested bits/blue accum values, or zero
634 *         accum_alpha_size - requested bits/alpha accum values, or zero
635 *         num_samples - number of samples/pixel if multisampling, or zero
636 *         level - visual level, usually 0
637 *         visualCaveat - ala the GLX extension, usually GLX_NONE
638 * Return;  a new XMesaVisual or 0 if error.
639 */
640PUBLIC
641XMesaVisual XMesaCreateVisual( Display *display,
642                               XVisualInfo * visinfo,
643                               GLboolean rgb_flag,
644                               GLboolean alpha_flag,
645                               GLboolean db_flag,
646                               GLboolean stereo_flag,
647                               GLboolean ximage_flag,
648                               GLint depth_size,
649                               GLint stencil_size,
650                               GLint accum_red_size,
651                               GLint accum_green_size,
652                               GLint accum_blue_size,
653                               GLint accum_alpha_size,
654                               GLint num_samples,
655                               GLint level,
656                               GLint visualCaveat )
657{
658   XMesaVisual v;
659   GLint red_bits, green_bits, blue_bits, alpha_bits;
660
661   /* For debugging only */
662   if (_mesa_getenv("MESA_XSYNC")) {
663      /* This makes debugging X easier.
664       * In your debugger, set a breakpoint on _XError to stop when an
665       * X protocol error is generated.
666       */
667      XSynchronize( display, 1 );
668   }
669
670   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
671   if (!v) {
672      return NULL;
673   }
674
675   v->display = display;
676
677   /* Save a copy of the XVisualInfo struct because the user may Xfree()
678    * the struct but we may need some of the information contained in it
679    * at a later time.
680    */
681   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
682   if (!v->visinfo) {
683      free(v);
684      return NULL;
685   }
686   memcpy(v->visinfo, visinfo, sizeof(*visinfo));
687
688   v->ximage_flag = ximage_flag;
689
690   v->mesa_visual.redMask = visinfo->red_mask;
691   v->mesa_visual.greenMask = visinfo->green_mask;
692   v->mesa_visual.blueMask = visinfo->blue_mask;
693   v->mesa_visual.visualID = visinfo->visualid;
694   v->mesa_visual.screen = visinfo->screen;
695
696#if !(defined(__cplusplus) || defined(c_plusplus))
697   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->class);
698#else
699   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
700#endif
701
702   v->mesa_visual.visualRating = visualCaveat;
703
704   if (alpha_flag)
705      v->mesa_visual.alphaBits = 8;
706
707   (void) initialize_visual_and_buffer( v, NULL, rgb_flag, 0, 0 );
708
709   {
710      const int xclass = v->mesa_visual.visualType;
711      if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
712         red_bits   = _mesa_bitcount(GET_REDMASK(v));
713         green_bits = _mesa_bitcount(GET_GREENMASK(v));
714         blue_bits  = _mesa_bitcount(GET_BLUEMASK(v));
715      }
716      else {
717         /* this is an approximation */
718         int depth;
719         depth = v->visinfo->depth;
720         red_bits = depth / 3;
721         depth -= red_bits;
722         green_bits = depth / 2;
723         depth -= green_bits;
724         blue_bits = depth;
725         alpha_bits = 0;
726         assert( red_bits + green_bits + blue_bits == v->visinfo->depth );
727      }
728      alpha_bits = v->mesa_visual.alphaBits;
729   }
730
731   _mesa_initialize_visual( &v->mesa_visual,
732                            rgb_flag, db_flag, stereo_flag,
733                            red_bits, green_bits,
734                            blue_bits, alpha_bits,
735                            v->mesa_visual.indexBits,
736                            depth_size,
737                            stencil_size,
738                            accum_red_size, accum_green_size,
739                            accum_blue_size, accum_alpha_size,
740                            0 );
741
742   /* XXX minor hack */
743   v->mesa_visual.level = level;
744   return v;
745}
746
747
748PUBLIC
749void XMesaDestroyVisual( XMesaVisual v )
750{
751   free(v->visinfo);
752   free(v);
753}
754
755
756
757/**
758 * Create a new XMesaContext.
759 * \param v  the XMesaVisual
760 * \param share_list  another XMesaContext with which to share display
761 *                    lists or NULL if no sharing is wanted.
762 * \return an XMesaContext or NULL if error.
763 */
764PUBLIC
765XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
766{
767   static GLboolean firstTime = GL_TRUE;
768   struct pipe_context *pipe = NULL;
769   XMesaContext c;
770   GLcontext *mesaCtx;
771   uint pf;
772
773   if (firstTime) {
774      pipe_mutex_init(_xmesa_lock);
775      _screen = driver.create_pipe_screen();
776      screen = trace_screen_create( _screen );
777      firstTime = GL_FALSE;
778   }
779
780   /* Note: the XMesaContext contains a Mesa GLcontext struct (inheritance) */
781   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
782   if (!c)
783      return NULL;
784
785   pf = choose_pixel_format(v);
786   assert(pf);
787
788   c->xm_visual = v;
789   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
790   c->xm_read_buffer = NULL;
791
792   if (screen == NULL)
793      goto fail;
794
795   /* Trace screen knows how to properly wrap context creation in the
796    * wrapped screen, so nothing special to do here:
797    */
798   pipe = screen->context_create(screen, (void *) c);
799   if (pipe == NULL)
800      goto fail;
801
802   c->st = st_create_context(pipe,
803                             &v->mesa_visual,
804                             share_list ? share_list->st : NULL);
805   if (c->st == NULL)
806      goto fail;
807
808   mesaCtx = c->st->ctx;
809   c->st->ctx->DriverCtx = c;
810
811   return c;
812
813fail:
814   if (c->st)
815      st_destroy_context(c->st);
816   else if (pipe)
817      pipe->destroy(pipe);
818
819   free(c);
820   return NULL;
821}
822
823
824
825PUBLIC
826void XMesaDestroyContext( XMesaContext c )
827{
828   st_destroy_context(c->st);
829
830   /* FIXME: We should destroy the screen here, but if we do so, surfaces may
831    * outlive it, causing segfaults
832   struct pipe_screen *screen = c->st->pipe->screen;
833   screen->destroy(screen);
834   */
835
836   free(c);
837}
838
839
840
841/**
842 * Private function for creating an XMesaBuffer which corresponds to an
843 * X window or pixmap.
844 * \param v  the window's XMesaVisual
845 * \param w  the window we're wrapping
846 * \return  new XMesaBuffer or NULL if error
847 */
848PUBLIC XMesaBuffer
849XMesaCreateWindowBuffer(XMesaVisual v, Window w)
850{
851   XWindowAttributes attr;
852   XMesaBuffer b;
853   Colormap cmap;
854   int depth;
855
856   assert(v);
857   assert(w);
858
859   /* Check that window depth matches visual depth */
860   XGetWindowAttributes( v->display, w, &attr );
861   depth = attr.depth;
862   if (v->visinfo->depth != depth) {
863      _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",
864                    v->visinfo->depth, depth);
865      return NULL;
866   }
867
868   /* Find colormap */
869   if (attr.colormap) {
870      cmap = attr.colormap;
871   }
872   else {
873      _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
874      /* this is weird, a window w/out a colormap!? */
875      /* OK, let's just allocate a new one and hope for the best */
876      cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
877   }
878
879   b = create_xmesa_buffer((Drawable) w, WINDOW, v, cmap);
880   if (!b)
881      return NULL;
882
883   if (!initialize_visual_and_buffer( v, b, v->mesa_visual.rgbMode,
884                                      (Drawable) w, cmap )) {
885      xmesa_free_buffer(b);
886      return NULL;
887   }
888
889   return b;
890}
891
892
893
894/**
895 * Create a new XMesaBuffer from an X pixmap.
896 *
897 * \param v    the XMesaVisual
898 * \param p    the pixmap
899 * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
900 *             \c GLX_DIRECT_COLOR visual for the pixmap
901 * \returns new XMesaBuffer or NULL if error
902 */
903PUBLIC XMesaBuffer
904XMesaCreatePixmapBuffer(XMesaVisual v, Pixmap p, Colormap cmap)
905{
906   XMesaBuffer b;
907
908   assert(v);
909
910   b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
911   if (!b)
912      return NULL;
913
914   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
915				     (Drawable) p, cmap)) {
916      xmesa_free_buffer(b);
917      return NULL;
918   }
919
920   return b;
921}
922
923
924/**
925 * For GLX_EXT_texture_from_pixmap
926 */
927XMesaBuffer
928XMesaCreatePixmapTextureBuffer(XMesaVisual v, Pixmap p,
929                               Colormap cmap,
930                               int format, int target, int mipmap)
931{
932   GET_CURRENT_CONTEXT(ctx);
933   XMesaBuffer b;
934   GLuint width, height;
935
936   assert(v);
937
938   b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
939   if (!b)
940      return NULL;
941
942   /* get pixmap size, update framebuffer/renderbuffer dims */
943   xmesa_get_window_size(v->display, b, &width, &height);
944   _mesa_resize_framebuffer(NULL, &(b->stfb->Base), width, height);
945
946   if (target == 0) {
947      /* examine dims */
948      if (ctx->Extensions.ARB_texture_non_power_of_two) {
949         target = GLX_TEXTURE_2D_EXT;
950      }
951      else if (   _mesa_bitcount(width)  == 1
952               && _mesa_bitcount(height) == 1) {
953         /* power of two size */
954         if (height == 1) {
955            target = GLX_TEXTURE_1D_EXT;
956         }
957         else {
958            target = GLX_TEXTURE_2D_EXT;
959         }
960      }
961      else if (ctx->Extensions.NV_texture_rectangle) {
962         target = GLX_TEXTURE_RECTANGLE_EXT;
963      }
964      else {
965         /* non power of two textures not supported */
966         XMesaDestroyBuffer(b);
967         return 0;
968      }
969   }
970
971   b->TextureTarget = target;
972   b->TextureFormat = format;
973   b->TextureMipmap = mipmap;
974
975   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
976				     (Drawable) p, cmap)) {
977      xmesa_free_buffer(b);
978      return NULL;
979   }
980
981   return b;
982}
983
984
985
986XMesaBuffer
987XMesaCreatePBuffer(XMesaVisual v, Colormap cmap,
988                   unsigned int width, unsigned int height)
989{
990   Window root;
991   Drawable drawable;  /* X Pixmap Drawable */
992   XMesaBuffer b;
993
994   /* allocate pixmap for front buffer */
995   root = RootWindow( v->display, v->visinfo->screen );
996   drawable = XCreatePixmap(v->display, root, width, height,
997                            v->visinfo->depth);
998   if (!drawable)
999      return NULL;
1000
1001   b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);
1002   if (!b)
1003      return NULL;
1004
1005   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
1006				     drawable, cmap)) {
1007      xmesa_free_buffer(b);
1008      return NULL;
1009   }
1010
1011   return b;
1012}
1013
1014
1015
1016/*
1017 * Deallocate an XMesaBuffer structure and all related info.
1018 */
1019PUBLIC void
1020XMesaDestroyBuffer(XMesaBuffer b)
1021{
1022   xmesa_free_buffer(b);
1023}
1024
1025
1026/**
1027 * Query the current window size and update the corresponding GLframebuffer
1028 * and all attached renderbuffers.
1029 * Called when:
1030 *  1. the first time a buffer is bound to a context.
1031 *  2. SwapBuffers.  XXX probabaly from xm_flush_frontbuffer() too...
1032 * Note: it's possible (and legal) for xmctx to be NULL.  That can happen
1033 * when resizing a buffer when no rendering context is bound.
1034 */
1035void
1036xmesa_check_and_update_buffer_size(XMesaContext xmctx, XMesaBuffer drawBuffer)
1037{
1038   GLuint width, height;
1039   xmesa_get_window_size(drawBuffer->xm_visual->display, drawBuffer, &width, &height);
1040   st_resize_framebuffer(drawBuffer->stfb, width, height);
1041}
1042
1043
1044
1045
1046/*
1047 * Bind buffer b to context c and make c the current rendering context.
1048 */
1049PUBLIC
1050GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
1051                             XMesaBuffer readBuffer )
1052{
1053   XMesaContext old_ctx = XMesaGetCurrentContext();
1054
1055   if (old_ctx && old_ctx != c) {
1056      XMesaFlush(old_ctx);
1057      old_ctx->xm_buffer = NULL;
1058      old_ctx->xm_read_buffer = NULL;
1059   }
1060
1061   if (c) {
1062      if (!drawBuffer || !readBuffer)
1063         return GL_FALSE;  /* must specify buffers! */
1064
1065      if (c == old_ctx &&
1066	  c->xm_buffer == drawBuffer &&
1067	  c->xm_read_buffer == readBuffer)
1068	 return GL_TRUE;
1069
1070      c->xm_buffer = drawBuffer;
1071      c->xm_read_buffer = readBuffer;
1072
1073      st_make_current(c->st, drawBuffer->stfb, readBuffer->stfb);
1074
1075      xmesa_check_and_update_buffer_size(c, drawBuffer);
1076      if (readBuffer != drawBuffer)
1077         xmesa_check_and_update_buffer_size(c, readBuffer);
1078
1079      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
1080      drawBuffer->wasCurrent = GL_TRUE;
1081   }
1082   else {
1083      /* Detach */
1084      st_make_current( NULL, NULL, NULL );
1085
1086   }
1087   return GL_TRUE;
1088}
1089
1090
1091/*
1092 * Unbind the context c from its buffer.
1093 */
1094GLboolean XMesaUnbindContext( XMesaContext c )
1095{
1096   /* A no-op for XFree86 integration purposes */
1097   return GL_TRUE;
1098}
1099
1100
1101XMesaContext XMesaGetCurrentContext( void )
1102{
1103   GET_CURRENT_CONTEXT(ctx);
1104   if (ctx) {
1105      XMesaContext xmesa = xmesa_context(ctx);
1106      return xmesa;
1107   }
1108   else {
1109      return 0;
1110   }
1111}
1112
1113
1114
1115/**
1116 * Swap front and back color buffers and have winsys display front buffer.
1117 * If there's no front color buffer no swap actually occurs.
1118 */
1119PUBLIC
1120void XMesaSwapBuffers( XMesaBuffer b )
1121{
1122   struct pipe_surface *frontLeftSurf;
1123
1124   st_swapbuffers(b->stfb, &frontLeftSurf, NULL);
1125
1126   if (frontLeftSurf) {
1127      if (_screen != screen) {
1128         struct trace_surface *tr_surf = trace_surface( frontLeftSurf );
1129         struct pipe_surface *surf = tr_surf->surface;
1130         frontLeftSurf = surf;
1131      }
1132
1133      driver.display_surface(b, frontLeftSurf);
1134   }
1135
1136   xmesa_check_and_update_buffer_size(NULL, b);
1137}
1138
1139
1140
1141/*
1142 * Copy sub-region of back buffer to front buffer
1143 */
1144void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
1145{
1146   struct pipe_surface *surf_front;
1147   struct pipe_surface *surf_back;
1148   struct pipe_context *pipe = NULL; /* XXX fix */
1149
1150   st_get_framebuffer_surface(b->stfb, ST_SURFACE_FRONT_LEFT, &surf_front);
1151   st_get_framebuffer_surface(b->stfb, ST_SURFACE_BACK_LEFT, &surf_back);
1152
1153   if (!surf_front || !surf_back)
1154      return;
1155
1156   assert(pipe);
1157   pipe->surface_copy(pipe,
1158                      surf_front, x, y,  /* dest */
1159                      surf_back, x, y,   /* src */
1160                      width, height);
1161}
1162
1163
1164
1165void XMesaFlush( XMesaContext c )
1166{
1167   if (c && c->xm_visual->display) {
1168      st_finish(c->st);
1169      XSync( c->xm_visual->display, False );
1170   }
1171}
1172
1173
1174
1175
1176
1177XMesaBuffer XMesaFindBuffer( Display *dpy, Drawable d )
1178{
1179   XMesaBuffer b;
1180   for (b = XMesaBufferList; b; b = b->Next) {
1181      if (b->drawable == d && b->xm_visual->display == dpy) {
1182         return b;
1183      }
1184   }
1185   return NULL;
1186}
1187
1188
1189/**
1190 * Free/destroy all XMesaBuffers associated with given display.
1191 */
1192void xmesa_destroy_buffers_on_display(Display *dpy)
1193{
1194   XMesaBuffer b, next;
1195   for (b = XMesaBufferList; b; b = next) {
1196      next = b->Next;
1197      if (b->xm_visual->display == dpy) {
1198         xmesa_free_buffer(b);
1199      }
1200   }
1201}
1202
1203
1204/*
1205 * Look for XMesaBuffers whose X window has been destroyed.
1206 * Deallocate any such XMesaBuffers.
1207 */
1208void XMesaGarbageCollect( void )
1209{
1210   XMesaBuffer b, next;
1211   for (b=XMesaBufferList; b; b=next) {
1212      next = b->Next;
1213      if (b->xm_visual &&
1214          b->xm_visual->display &&
1215          b->drawable &&
1216          b->type == WINDOW) {
1217         XSync(b->xm_visual->display, False);
1218         if (!window_exists( b->xm_visual->display, b->drawable )) {
1219            /* found a dead window, free the ancillary info */
1220            XMesaDestroyBuffer( b );
1221         }
1222      }
1223   }
1224}
1225
1226
1227
1228
1229PUBLIC void
1230XMesaBindTexImage(Display *dpy, XMesaBuffer drawable, int buffer,
1231                  const int *attrib_list)
1232{
1233}
1234
1235
1236
1237PUBLIC void
1238XMesaReleaseTexImage(Display *dpy, XMesaBuffer drawable, int buffer)
1239{
1240}
1241
1242