glxcmds.c revision 1add5354d0fbfb2d9b6a4a3fd6a39225bcadc098
1/*
2 * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
3 * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice including the dates of first publication and
13 * either this permission notice or a reference to
14 * http://oss.sgi.com/projects/FreeB/
15 * shall be included 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 * SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
22 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 *
25 * Except as contained in this notice, the name of Silicon Graphics, Inc.
26 * shall not be used in advertising or otherwise to promote the sale, use or
27 * other dealings in this Software without prior written authorization from
28 * Silicon Graphics, Inc.
29 */
30
31/**
32 * \file glxcmds.c
33 * Client-side GLX interface.
34 */
35
36#include "glxclient.h"
37#include "glapi.h"
38#include "glxextensions.h"
39#include "glcontextmodes.h"
40
41#ifdef GLX_DIRECT_RENDERING
42#include <sys/time.h>
43#include <X11/extensions/xf86vmode.h>
44#include "xf86dri.h"
45#define GC_IS_DIRECT(gc) ((gc)->driContext != NULL)
46#else
47#define GC_IS_DIRECT(gc) (0)
48#endif
49
50#if defined(USE_XCB)
51#include <X11/Xlib-xcb.h>
52#include <xcb/xcb.h>
53#include <xcb/glx.h>
54#endif
55
56static const char __glXGLXClientVendorName[] = "Mesa Project and SGI";
57static const char __glXGLXClientVersion[] = "1.4";
58
59
60/****************************************************************************/
61
62#ifdef GLX_DIRECT_RENDERING
63
64static Bool windowExistsFlag;
65static int
66windowExistsErrorHandler(Display * dpy, XErrorEvent * xerr)
67{
68   (void) dpy;
69
70   if (xerr->error_code == BadWindow) {
71      windowExistsFlag = GL_FALSE;
72   }
73   return 0;
74}
75
76/**
77 * Find drawables in the local hash that have been destroyed on the
78 * server.
79 *
80 * \param dpy    Display to destroy drawables for
81 * \param screen Screen number to destroy drawables for
82 */
83static void
84GarbageCollectDRIDrawables(Display * dpy, __GLXscreenConfigs * sc)
85{
86   XID draw;
87   __GLXDRIdrawable *pdraw;
88   XWindowAttributes xwa;
89   int (*oldXErrorHandler) (Display *, XErrorEvent *);
90
91   /* Set no-op error handler so Xlib doesn't bail out if the windows
92    * has alreay been destroyed on the server. */
93   XSync(dpy, GL_FALSE);
94   oldXErrorHandler = XSetErrorHandler(windowExistsErrorHandler);
95
96   if (__glxHashFirst(sc->drawHash, &draw, (void *) &pdraw) == 1) {
97      do {
98         windowExistsFlag = GL_TRUE;
99         XGetWindowAttributes(dpy, draw, &xwa); /* dummy request */
100         if (!windowExistsFlag) {
101            /* Destroy the local drawable data, if the drawable no
102               longer exists in the Xserver */
103            (*pdraw->destroyDrawable) (pdraw);
104            __glxHashDelete(sc->drawHash, draw);
105         }
106      } while (__glxHashNext(sc->drawHash, &draw, (void *) &pdraw) == 1);
107   }
108
109   XSync(dpy, GL_FALSE);
110   XSetErrorHandler(oldXErrorHandler);
111}
112
113extern __GLXDRIdrawable *GetGLXDRIDrawable(Display * dpy,
114                                           GLXDrawable drawable,
115                                           int *const scrn_num);
116
117/**
118 * Get the __DRIdrawable for the drawable associated with a GLXContext
119 *
120 * \param dpy       The display associated with \c drawable.
121 * \param drawable  GLXDrawable whose __DRIdrawable part is to be retrieved.
122 * \param scrn_num  If non-NULL, the drawables screen is stored there
123 * \returns  A pointer to the context's __DRIdrawable on success, or NULL if
124 *           the drawable is not associated with a direct-rendering context.
125 */
126_X_HIDDEN __GLXDRIdrawable *
127GetGLXDRIDrawable(Display * dpy, GLXDrawable drawable, int *const scrn_num)
128{
129   __GLXdisplayPrivate *priv = __glXInitialize(dpy);
130   __GLXDRIdrawable *pdraw;
131   const unsigned screen_count = ScreenCount(dpy);
132   unsigned i;
133   __GLXscreenConfigs *psc;
134
135   if (priv == NULL)
136      return NULL;
137
138   for (i = 0; i < screen_count; i++) {
139      psc = &priv->screenConfigs[i];
140      if (psc->drawHash == NULL)
141         continue;
142
143      if (__glxHashLookup(psc->drawHash, drawable, (void *) &pdraw) == 0) {
144         if (scrn_num != NULL)
145            *scrn_num = i;
146         return pdraw;
147      }
148   }
149
150   return NULL;
151}
152
153#endif
154
155
156/**
157 * Get the GLX per-screen data structure associated with a GLX context.
158 *
159 * \param dpy   Display for which the GLX per-screen information is to be
160 *              retrieved.
161 * \param scrn  Screen on \c dpy for which the GLX per-screen information is
162 *              to be retrieved.
163 * \returns A pointer to the GLX per-screen data if \c dpy and \c scrn
164 *          specify a valid GLX screen, or NULL otherwise.
165 *
166 * \todo Should this function validate that \c scrn is within the screen
167 *       number range for \c dpy?
168 */
169
170static __GLXscreenConfigs *
171GetGLXScreenConfigs(Display * dpy, int scrn)
172{
173   __GLXdisplayPrivate *const priv = __glXInitialize(dpy);
174
175   return (priv
176           && priv->screenConfigs !=
177           NULL) ? &priv->screenConfigs[scrn] : NULL;
178}
179
180
181static int
182GetGLXPrivScreenConfig(Display * dpy, int scrn, __GLXdisplayPrivate ** ppriv,
183                       __GLXscreenConfigs ** ppsc)
184{
185   /* Initialize the extension, if needed .  This has the added value
186    * of initializing/allocating the display private
187    */
188
189   if (dpy == NULL) {
190      return GLX_NO_EXTENSION;
191   }
192
193   *ppriv = __glXInitialize(dpy);
194   if (*ppriv == NULL) {
195      return GLX_NO_EXTENSION;
196   }
197
198   /* Check screen number to see if its valid */
199   if ((scrn < 0) || (scrn >= ScreenCount(dpy))) {
200      return GLX_BAD_SCREEN;
201   }
202
203   /* Check to see if the GL is supported on this screen */
204   *ppsc = &((*ppriv)->screenConfigs[scrn]);
205   if ((*ppsc)->configs == NULL) {
206      /* No support for GL on this screen regardless of visual */
207      return GLX_BAD_VISUAL;
208   }
209
210   return Success;
211}
212
213
214/**
215 * Determine if a \c GLXFBConfig supplied by the application is valid.
216 *
217 * \param dpy     Application supplied \c Display pointer.
218 * \param config  Application supplied \c GLXFBConfig.
219 *
220 * \returns If the \c GLXFBConfig is valid, the a pointer to the matching
221 *          \c __GLcontextModes structure is returned.  Otherwise, \c NULL
222 *          is returned.
223 */
224static __GLcontextModes *
225ValidateGLXFBConfig(Display * dpy, GLXFBConfig config)
226{
227   __GLXdisplayPrivate *const priv = __glXInitialize(dpy);
228   const unsigned num_screens = ScreenCount(dpy);
229   unsigned i;
230   const __GLcontextModes *modes;
231
232
233   if (priv != NULL) {
234      for (i = 0; i < num_screens; i++) {
235         for (modes = priv->screenConfigs[i].configs; modes != NULL;
236              modes = modes->next) {
237            if (modes == (__GLcontextModes *) config) {
238               return (__GLcontextModes *) config;
239            }
240         }
241      }
242   }
243
244   return NULL;
245}
246
247
248/**
249 * \todo It should be possible to move the allocate of \c client_state_private
250 * later in the function for direct-rendering contexts.  Direct-rendering
251 * contexts don't need to track client state, so they don't need that memory
252 * at all.
253 *
254 * \todo Eliminate \c __glXInitVertexArrayState.  Replace it with a new
255 * function called \c __glXAllocateClientState that allocates the memory and
256 * does all the initialization (including the pixel pack / unpack).
257 */
258static GLXContext
259AllocateGLXContext(Display * dpy)
260{
261   GLXContext gc;
262   int bufSize;
263   CARD8 opcode;
264   __GLXattribute *state;
265
266   if (!dpy)
267      return NULL;
268
269   opcode = __glXSetupForCommand(dpy);
270   if (!opcode) {
271      return NULL;
272   }
273
274   /* Allocate our context record */
275   gc = (GLXContext) Xmalloc(sizeof(struct __GLXcontextRec));
276   if (!gc) {
277      /* Out of memory */
278      return NULL;
279   }
280   memset(gc, 0, sizeof(struct __GLXcontextRec));
281
282   state = Xmalloc(sizeof(struct __GLXattributeRec));
283   if (state == NULL) {
284      /* Out of memory */
285      Xfree(gc);
286      return NULL;
287   }
288   gc->client_state_private = state;
289   memset(gc->client_state_private, 0, sizeof(struct __GLXattributeRec));
290   state->NoDrawArraysProtocol = (getenv("LIBGL_NO_DRAWARRAYS") != NULL);
291
292   /*
293    ** Create a temporary buffer to hold GLX rendering commands.  The size
294    ** of the buffer is selected so that the maximum number of GLX rendering
295    ** commands can fit in a single X packet and still have room in the X
296    ** packet for the GLXRenderReq header.
297    */
298
299   bufSize = (XMaxRequestSize(dpy) * 4) - sz_xGLXRenderReq;
300   gc->buf = (GLubyte *) Xmalloc(bufSize);
301   if (!gc->buf) {
302      Xfree(gc->client_state_private);
303      Xfree(gc);
304      return NULL;
305   }
306   gc->bufSize = bufSize;
307
308   /* Fill in the new context */
309   gc->renderMode = GL_RENDER;
310
311   state->storePack.alignment = 4;
312   state->storeUnpack.alignment = 4;
313
314   gc->attributes.stackPointer = &gc->attributes.stack[0];
315
316   /*
317    ** PERFORMANCE NOTE: A mode dependent fill image can speed things up.
318    ** Other code uses the fastImageUnpack bit, but it is never set
319    ** to GL_TRUE.
320    */
321   gc->fastImageUnpack = GL_FALSE;
322   gc->fillImage = __glFillImage;
323   gc->pc = gc->buf;
324   gc->bufEnd = gc->buf + bufSize;
325   gc->isDirect = GL_FALSE;
326   if (__glXDebug) {
327      /*
328       ** Set limit register so that there will be one command per packet
329       */
330      gc->limit = gc->buf;
331   }
332   else {
333      gc->limit = gc->buf + bufSize - __GLX_BUFFER_LIMIT_SIZE;
334   }
335   gc->createDpy = dpy;
336   gc->majorOpcode = opcode;
337
338   /*
339    ** Constrain the maximum drawing command size allowed to be
340    ** transfered using the X_GLXRender protocol request.  First
341    ** constrain by a software limit, then constrain by the protocl
342    ** limit.
343    */
344   if (bufSize > __GLX_RENDER_CMD_SIZE_LIMIT) {
345      bufSize = __GLX_RENDER_CMD_SIZE_LIMIT;
346   }
347   if (bufSize > __GLX_MAX_RENDER_CMD_SIZE) {
348      bufSize = __GLX_MAX_RENDER_CMD_SIZE;
349   }
350   gc->maxSmallRenderCommandSize = bufSize;
351   return gc;
352}
353
354
355/**
356 * Create a new context.  Exactly one of \c vis and \c fbconfig should be
357 * non-NULL.
358 *
359 * \param use_glx_1_3  For FBConfigs, should GLX 1.3 protocol or
360 *                     SGIX_fbconfig protocol be used?
361 * \param renderType   For FBConfigs, what is the rendering type?
362 */
363
364static GLXContext
365CreateContext(Display * dpy, XVisualInfo * vis,
366              const __GLcontextModes * const fbconfig,
367              GLXContext shareList,
368              Bool allowDirect, GLXContextID contextID,
369              Bool use_glx_1_3, int renderType)
370{
371   GLXContext gc;
372#ifdef GLX_DIRECT_RENDERING
373   int screen = (fbconfig == NULL) ? vis->screen : fbconfig->screen;
374   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
375#endif
376
377   if (dpy == NULL)
378      return NULL;
379
380   gc = AllocateGLXContext(dpy);
381   if (!gc)
382      return NULL;
383
384   if (None == contextID) {
385      if ((vis == NULL) && (fbconfig == NULL))
386         return NULL;
387
388#ifdef GLX_DIRECT_RENDERING
389      if (allowDirect && psc->driScreen) {
390         const __GLcontextModes *mode;
391
392         if (fbconfig == NULL) {
393            mode = _gl_context_modes_find_visual(psc->visuals, vis->visualid);
394            if (mode == NULL) {
395               xError error;
396
397               error.errorCode = BadValue;
398               error.resourceID = vis->visualid;
399               error.sequenceNumber = dpy->request;
400               error.type = X_Error;
401               error.majorCode = gc->majorOpcode;
402               error.minorCode = X_GLXCreateContext;
403               _XError(dpy, &error);
404               return None;
405            }
406            if (renderType == 0) {
407               /* Initialize renderType now */
408               renderType = mode->rgbMode ? GLX_RGBA_TYPE : GLX_COLOR_INDEX_TYPE;
409            }
410         }
411         else {
412            mode = fbconfig;
413         }
414
415         gc->driContext = psc->driScreen->createContext(psc, mode, gc,
416                                                        shareList,
417                                                        renderType);
418         if (gc->driContext != NULL) {
419            gc->screen = mode->screen;
420            gc->psc = psc;
421            gc->mode = mode;
422            gc->isDirect = GL_TRUE;
423         }
424      }
425#endif
426
427      LockDisplay(dpy);
428      if (fbconfig == NULL) {
429         xGLXCreateContextReq *req;
430
431         /* Send the glXCreateContext request */
432         GetReq(GLXCreateContext, req);
433         req->reqType = gc->majorOpcode;
434         req->glxCode = X_GLXCreateContext;
435         req->context = gc->xid = XAllocID(dpy);
436         req->visual = vis->visualid;
437         req->screen = vis->screen;
438         req->shareList = shareList ? shareList->xid : None;
439         req->isDirect = GC_IS_DIRECT(gc);
440      }
441      else if (use_glx_1_3) {
442         xGLXCreateNewContextReq *req;
443
444         /* Send the glXCreateNewContext request */
445         GetReq(GLXCreateNewContext, req);
446         req->reqType = gc->majorOpcode;
447         req->glxCode = X_GLXCreateNewContext;
448         req->context = gc->xid = XAllocID(dpy);
449         req->fbconfig = fbconfig->fbconfigID;
450         req->screen = fbconfig->screen;
451         req->renderType = renderType;
452         req->shareList = shareList ? shareList->xid : None;
453         req->isDirect = GC_IS_DIRECT(gc);
454      }
455      else {
456         xGLXVendorPrivateWithReplyReq *vpreq;
457         xGLXCreateContextWithConfigSGIXReq *req;
458
459         /* Send the glXCreateNewContext request */
460         GetReqExtra(GLXVendorPrivateWithReply,
461                     sz_xGLXCreateContextWithConfigSGIXReq -
462                     sz_xGLXVendorPrivateWithReplyReq, vpreq);
463         req = (xGLXCreateContextWithConfigSGIXReq *) vpreq;
464         req->reqType = gc->majorOpcode;
465         req->glxCode = X_GLXVendorPrivateWithReply;
466         req->vendorCode = X_GLXvop_CreateContextWithConfigSGIX;
467         req->context = gc->xid = XAllocID(dpy);
468         req->fbconfig = fbconfig->fbconfigID;
469         req->screen = fbconfig->screen;
470         req->renderType = renderType;
471         req->shareList = shareList ? shareList->xid : None;
472         req->isDirect = GC_IS_DIRECT(gc);
473      }
474
475      UnlockDisplay(dpy);
476      SyncHandle();
477      gc->imported = GL_FALSE;
478   }
479   else {
480      gc->xid = contextID;
481      gc->imported = GL_TRUE;
482   }
483
484   gc->renderType = renderType;
485
486   return gc;
487}
488
489PUBLIC GLXContext
490glXCreateContext(Display * dpy, XVisualInfo * vis,
491                 GLXContext shareList, Bool allowDirect)
492{
493   return CreateContext(dpy, vis, NULL, shareList, allowDirect, None,
494                        False, 0);
495}
496
497_X_HIDDEN void
498__glXFreeContext(__GLXcontext * gc)
499{
500   if (gc->vendor)
501      XFree((char *) gc->vendor);
502   if (gc->renderer)
503      XFree((char *) gc->renderer);
504   if (gc->version)
505      XFree((char *) gc->version);
506   if (gc->extensions)
507      XFree((char *) gc->extensions);
508   __glFreeAttributeState(gc);
509   XFree((char *) gc->buf);
510   Xfree((char *) gc->client_state_private);
511   XFree((char *) gc);
512
513}
514
515/*
516** Destroy the named context
517*/
518static void
519DestroyContext(Display * dpy, GLXContext gc)
520{
521   xGLXDestroyContextReq *req;
522   GLXContextID xid;
523   CARD8 opcode;
524   GLboolean imported;
525
526   opcode = __glXSetupForCommand(dpy);
527   if (!opcode || !gc) {
528      return;
529   }
530
531   __glXLock();
532   xid = gc->xid;
533   imported = gc->imported;
534   gc->xid = None;
535
536   if (gc->currentDpy) {
537      /* This context is bound to some thread.  According to the man page,
538       * we should not actually delete the context until it's unbound.
539       * Note that we set gc->xid = None above.  In MakeContextCurrent()
540       * we check for that and delete the context there.
541       */
542      __glXUnlock();
543      return;
544   }
545
546#ifdef GLX_DIRECT_RENDERING
547   /* Destroy the direct rendering context */
548   if (gc->driContext) {
549      (*gc->driContext->destroyContext) (gc->driContext, gc->psc, dpy);
550      gc->driContext = NULL;
551      GarbageCollectDRIDrawables(dpy, gc->psc);
552   }
553#endif
554
555   __glXFreeVertexArrayState(gc);
556
557   if (gc->currentDpy) {
558      /* Have to free later cuz it's in use now */
559      __glXUnlock();
560   }
561   else {
562      /* Destroy the handle if not current to anybody */
563      __glXUnlock();
564      __glXFreeContext(gc);
565   }
566
567   if (!imported) {
568      /*
569       ** This dpy also created the server side part of the context.
570       ** Send the glXDestroyContext request.
571       */
572      LockDisplay(dpy);
573      GetReq(GLXDestroyContext, req);
574      req->reqType = opcode;
575      req->glxCode = X_GLXDestroyContext;
576      req->context = xid;
577      UnlockDisplay(dpy);
578      SyncHandle();
579   }
580}
581
582PUBLIC void
583glXDestroyContext(Display * dpy, GLXContext gc)
584{
585   DestroyContext(dpy, gc);
586}
587
588/*
589** Return the major and minor version #s for the GLX extension
590*/
591PUBLIC Bool
592glXQueryVersion(Display * dpy, int *major, int *minor)
593{
594   __GLXdisplayPrivate *priv;
595
596   /* Init the extension.  This fetches the major and minor version. */
597   priv = __glXInitialize(dpy);
598   if (!priv)
599      return GL_FALSE;
600
601   if (major)
602      *major = priv->majorVersion;
603   if (minor)
604      *minor = priv->minorVersion;
605   return GL_TRUE;
606}
607
608/*
609** Query the existance of the GLX extension
610*/
611PUBLIC Bool
612glXQueryExtension(Display * dpy, int *errorBase, int *eventBase)
613{
614   int major_op, erb, evb;
615   Bool rv;
616
617   rv = XQueryExtension(dpy, GLX_EXTENSION_NAME, &major_op, &evb, &erb);
618   if (rv) {
619      if (errorBase)
620         *errorBase = erb;
621      if (eventBase)
622         *eventBase = evb;
623   }
624   return rv;
625}
626
627/*
628** Put a barrier in the token stream that forces the GL to finish its
629** work before X can proceed.
630*/
631PUBLIC void
632glXWaitGL(void)
633{
634   xGLXWaitGLReq *req;
635   GLXContext gc = __glXGetCurrentContext();
636   Display *dpy = gc->currentDpy;
637
638   if (!dpy)
639      return;
640
641   /* Flush any pending commands out */
642   __glXFlushRenderBuffer(gc, gc->pc);
643
644#ifdef GLX_DIRECT_RENDERING
645   if (gc->driContext) {
646      int screen;
647      __GLXDRIdrawable *pdraw =
648         GetGLXDRIDrawable(dpy, gc->currentDrawable, &screen);
649
650      if (pdraw != NULL) {
651         __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
652         glFlush();
653         if (psc->driScreen->waitGL != NULL)
654            (*psc->driScreen->waitGL) (pdraw);
655      }
656      return;
657   }
658#endif
659
660   /* Send the glXWaitGL request */
661   LockDisplay(dpy);
662   GetReq(GLXWaitGL, req);
663   req->reqType = gc->majorOpcode;
664   req->glxCode = X_GLXWaitGL;
665   req->contextTag = gc->currentContextTag;
666   UnlockDisplay(dpy);
667   SyncHandle();
668}
669
670/*
671** Put a barrier in the token stream that forces X to finish its
672** work before GL can proceed.
673*/
674PUBLIC void
675glXWaitX(void)
676{
677   xGLXWaitXReq *req;
678   GLXContext gc = __glXGetCurrentContext();
679   Display *dpy = gc->currentDpy;
680
681   if (!dpy)
682      return;
683
684   /* Flush any pending commands out */
685   __glXFlushRenderBuffer(gc, gc->pc);
686
687#ifdef GLX_DIRECT_RENDERING
688   if (gc->driContext) {
689      int screen;
690      __GLXDRIdrawable *pdraw =
691         GetGLXDRIDrawable(dpy, gc->currentDrawable, &screen);
692
693      if (pdraw != NULL) {
694         __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
695         if (psc->driScreen->waitX != NULL)
696            (*psc->driScreen->waitX) (pdraw);
697      }
698      else
699         XSync(dpy, False);
700      return;
701   }
702#endif
703
704   /*
705    ** Send the glXWaitX request.
706    */
707   LockDisplay(dpy);
708   GetReq(GLXWaitX, req);
709   req->reqType = gc->majorOpcode;
710   req->glxCode = X_GLXWaitX;
711   req->contextTag = gc->currentContextTag;
712   UnlockDisplay(dpy);
713   SyncHandle();
714}
715
716PUBLIC void
717glXUseXFont(Font font, int first, int count, int listBase)
718{
719   xGLXUseXFontReq *req;
720   GLXContext gc = __glXGetCurrentContext();
721   Display *dpy = gc->currentDpy;
722
723   if (!dpy)
724      return;
725
726   /* Flush any pending commands out */
727   (void) __glXFlushRenderBuffer(gc, gc->pc);
728
729#ifdef GLX_DIRECT_RENDERING
730   if (gc->driContext) {
731      DRI_glXUseXFont(font, first, count, listBase);
732      return;
733   }
734#endif
735
736   /* Send the glXUseFont request */
737   LockDisplay(dpy);
738   GetReq(GLXUseXFont, req);
739   req->reqType = gc->majorOpcode;
740   req->glxCode = X_GLXUseXFont;
741   req->contextTag = gc->currentContextTag;
742   req->font = font;
743   req->first = first;
744   req->count = count;
745   req->listBase = listBase;
746   UnlockDisplay(dpy);
747   SyncHandle();
748}
749
750/************************************************************************/
751
752/*
753** Copy the source context to the destination context using the
754** attribute "mask".
755*/
756PUBLIC void
757glXCopyContext(Display * dpy, GLXContext source,
758               GLXContext dest, unsigned long mask)
759{
760   xGLXCopyContextReq *req;
761   GLXContext gc = __glXGetCurrentContext();
762   GLXContextTag tag;
763   CARD8 opcode;
764
765   opcode = __glXSetupForCommand(dpy);
766   if (!opcode) {
767      return;
768   }
769
770#ifdef GLX_DIRECT_RENDERING
771   if (gc->driContext) {
772      /* NOT_DONE: This does not work yet */
773   }
774#endif
775
776   /*
777    ** If the source is the current context, send its tag so that the context
778    ** can be flushed before the copy.
779    */
780   if (source == gc && dpy == gc->currentDpy) {
781      tag = gc->currentContextTag;
782   }
783   else {
784      tag = 0;
785   }
786
787   /* Send the glXCopyContext request */
788   LockDisplay(dpy);
789   GetReq(GLXCopyContext, req);
790   req->reqType = opcode;
791   req->glxCode = X_GLXCopyContext;
792   req->source = source ? source->xid : None;
793   req->dest = dest ? dest->xid : None;
794   req->mask = mask;
795   req->contextTag = tag;
796   UnlockDisplay(dpy);
797   SyncHandle();
798}
799
800
801/**
802 * Determine if a context uses direct rendering.
803 *
804 * \param dpy        Display where the context was created.
805 * \param contextID  ID of the context to be tested.
806 *
807 * \returns \c GL_TRUE if the context is direct rendering or not.
808 */
809static Bool
810__glXIsDirect(Display * dpy, GLXContextID contextID)
811{
812#if !defined(USE_XCB)
813   xGLXIsDirectReq *req;
814   xGLXIsDirectReply reply;
815#endif
816   CARD8 opcode;
817
818   opcode = __glXSetupForCommand(dpy);
819   if (!opcode) {
820      return GL_FALSE;
821   }
822
823#ifdef USE_XCB
824   xcb_connection_t *c = XGetXCBConnection(dpy);
825   xcb_glx_is_direct_reply_t *reply = xcb_glx_is_direct_reply(c,
826                                                              xcb_glx_is_direct
827                                                              (c, contextID),
828                                                              NULL);
829
830   const Bool is_direct = reply->is_direct ? True : False;
831   free(reply);
832
833   return is_direct;
834#else
835   /* Send the glXIsDirect request */
836   LockDisplay(dpy);
837   GetReq(GLXIsDirect, req);
838   req->reqType = opcode;
839   req->glxCode = X_GLXIsDirect;
840   req->context = contextID;
841   _XReply(dpy, (xReply *) & reply, 0, False);
842   UnlockDisplay(dpy);
843   SyncHandle();
844
845   return reply.isDirect;
846#endif /* USE_XCB */
847}
848
849/**
850 * \todo
851 * Shouldn't this function \b always return \c GL_FALSE when
852 * \c GLX_DIRECT_RENDERING is not defined?  Do we really need to bother with
853 * the GLX protocol here at all?
854 */
855PUBLIC Bool
856glXIsDirect(Display * dpy, GLXContext gc)
857{
858   if (!gc) {
859      return GL_FALSE;
860   }
861   else if (GC_IS_DIRECT(gc)) {
862      return GL_TRUE;
863   }
864   return __glXIsDirect(dpy, gc->xid);
865}
866
867PUBLIC GLXPixmap
868glXCreateGLXPixmap(Display * dpy, XVisualInfo * vis, Pixmap pixmap)
869{
870   xGLXCreateGLXPixmapReq *req;
871   GLXPixmap xid;
872   CARD8 opcode;
873
874   opcode = __glXSetupForCommand(dpy);
875   if (!opcode) {
876      return None;
877   }
878
879   /* Send the glXCreateGLXPixmap request */
880   LockDisplay(dpy);
881   GetReq(GLXCreateGLXPixmap, req);
882   req->reqType = opcode;
883   req->glxCode = X_GLXCreateGLXPixmap;
884   req->screen = vis->screen;
885   req->visual = vis->visualid;
886   req->pixmap = pixmap;
887   req->glxpixmap = xid = XAllocID(dpy);
888   UnlockDisplay(dpy);
889   SyncHandle();
890
891#ifdef GLX_DIRECT_RENDERING
892   do {
893      /* FIXME: Maybe delay __DRIdrawable creation until the drawable
894       * is actually bound to a context... */
895
896      __GLXdisplayPrivate *const priv = __glXInitialize(dpy);
897      __GLXDRIdrawable *pdraw;
898      __GLXscreenConfigs *psc;
899      __GLcontextModes *modes;
900
901      psc = &priv->screenConfigs[vis->screen];
902      if (psc->driScreen == NULL)
903         break;
904      modes = _gl_context_modes_find_visual(psc->visuals, vis->visualid);
905      pdraw = psc->driScreen->createDrawable(psc, pixmap, req->glxpixmap, modes);
906      if (pdraw == NULL) {
907         fprintf(stderr, "failed to create pixmap\n");
908         break;
909      }
910
911      if (__glxHashInsert(psc->drawHash, req->glxpixmap, pdraw)) {
912         (*pdraw->destroyDrawable) (pdraw);
913         return None;           /* FIXME: Check what we're supposed to do here... */
914      }
915   } while (0);
916#endif
917
918   return xid;
919}
920
921/*
922** Destroy the named pixmap
923*/
924PUBLIC void
925glXDestroyGLXPixmap(Display * dpy, GLXPixmap glxpixmap)
926{
927   xGLXDestroyGLXPixmapReq *req;
928   CARD8 opcode;
929
930   opcode = __glXSetupForCommand(dpy);
931   if (!opcode) {
932      return;
933   }
934
935   /* Send the glXDestroyGLXPixmap request */
936   LockDisplay(dpy);
937   GetReq(GLXDestroyGLXPixmap, req);
938   req->reqType = opcode;
939   req->glxCode = X_GLXDestroyGLXPixmap;
940   req->glxpixmap = glxpixmap;
941   UnlockDisplay(dpy);
942   SyncHandle();
943
944#ifdef GLX_DIRECT_RENDERING
945   {
946      int screen;
947      __GLXdisplayPrivate *const priv = __glXInitialize(dpy);
948      __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, glxpixmap, &screen);
949      __GLXscreenConfigs *psc = &priv->screenConfigs[screen];
950
951      if (pdraw != NULL) {
952         (*pdraw->destroyDrawable) (pdraw);
953         __glxHashDelete(psc->drawHash, glxpixmap);
954      }
955   }
956#endif
957}
958
959PUBLIC void
960glXSwapBuffers(Display * dpy, GLXDrawable drawable)
961{
962   GLXContext gc;
963   GLXContextTag tag;
964   CARD8 opcode;
965#ifdef USE_XCB
966   xcb_connection_t *c;
967#else
968   xGLXSwapBuffersReq *req;
969#endif
970
971#ifdef GLX_DIRECT_RENDERING
972   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, NULL);
973
974   if (pdraw != NULL) {
975      glFlush();
976      (*pdraw->psc->driScreen->swapBuffers)(pdraw, 0, 0, 0);
977      return;
978   }
979#endif
980
981   opcode = __glXSetupForCommand(dpy);
982   if (!opcode) {
983      return;
984   }
985
986   /*
987    ** The calling thread may or may not have a current context.  If it
988    ** does, send the context tag so the server can do a flush.
989    */
990   gc = __glXGetCurrentContext();
991   if ((gc != NULL) && (dpy == gc->currentDpy) &&
992       ((drawable == gc->currentDrawable)
993        || (drawable == gc->currentReadable))) {
994      tag = gc->currentContextTag;
995   }
996   else {
997      tag = 0;
998   }
999
1000#ifdef USE_XCB
1001   c = XGetXCBConnection(dpy);
1002   xcb_glx_swap_buffers(c, tag, drawable);
1003   xcb_flush(c);
1004#else
1005   /* Send the glXSwapBuffers request */
1006   LockDisplay(dpy);
1007   GetReq(GLXSwapBuffers, req);
1008   req->reqType = opcode;
1009   req->glxCode = X_GLXSwapBuffers;
1010   req->drawable = drawable;
1011   req->contextTag = tag;
1012   UnlockDisplay(dpy);
1013   SyncHandle();
1014   XFlush(dpy);
1015#endif /* USE_XCB */
1016}
1017
1018
1019/*
1020** Return configuration information for the given display, screen and
1021** visual combination.
1022*/
1023PUBLIC int
1024glXGetConfig(Display * dpy, XVisualInfo * vis, int attribute,
1025             int *value_return)
1026{
1027   __GLXdisplayPrivate *priv;
1028   __GLXscreenConfigs *psc;
1029   __GLcontextModes *modes;
1030   int status;
1031
1032   status = GetGLXPrivScreenConfig(dpy, vis->screen, &priv, &psc);
1033   if (status == Success) {
1034      modes = _gl_context_modes_find_visual(psc->visuals, vis->visualid);
1035
1036      /* Lookup attribute after first finding a match on the visual */
1037      if (modes != NULL) {
1038         return _gl_get_context_mode_data(modes, attribute, value_return);
1039      }
1040
1041      status = GLX_BAD_VISUAL;
1042   }
1043
1044   /*
1045    ** If we can't find the config for this visual, this visual is not
1046    ** supported by the OpenGL implementation on the server.
1047    */
1048   if ((status == GLX_BAD_VISUAL) && (attribute == GLX_USE_GL)) {
1049      *value_return = GL_FALSE;
1050      status = Success;
1051   }
1052
1053   return status;
1054}
1055
1056/************************************************************************/
1057
1058static void
1059init_fbconfig_for_chooser(__GLcontextModes * config,
1060                          GLboolean fbconfig_style_tags)
1061{
1062   memset(config, 0, sizeof(__GLcontextModes));
1063   config->visualID = (XID) GLX_DONT_CARE;
1064   config->visualType = GLX_DONT_CARE;
1065
1066   /* glXChooseFBConfig specifies different defaults for these two than
1067    * glXChooseVisual.
1068    */
1069   if (fbconfig_style_tags) {
1070      config->rgbMode = GL_TRUE;
1071      config->doubleBufferMode = GLX_DONT_CARE;
1072   }
1073
1074   config->visualRating = GLX_DONT_CARE;
1075   config->transparentPixel = GLX_NONE;
1076   config->transparentRed = GLX_DONT_CARE;
1077   config->transparentGreen = GLX_DONT_CARE;
1078   config->transparentBlue = GLX_DONT_CARE;
1079   config->transparentAlpha = GLX_DONT_CARE;
1080   config->transparentIndex = GLX_DONT_CARE;
1081
1082   config->drawableType = GLX_WINDOW_BIT;
1083   config->renderType =
1084      (config->rgbMode) ? GLX_RGBA_BIT : GLX_COLOR_INDEX_BIT;
1085   config->xRenderable = GLX_DONT_CARE;
1086   config->fbconfigID = (GLXFBConfigID) (GLX_DONT_CARE);
1087
1088   config->swapMethod = GLX_DONT_CARE;
1089}
1090
1091#define MATCH_DONT_CARE( param )        \
1092  do {                                  \
1093    if ( ((int) a-> param != (int) GLX_DONT_CARE)   \
1094         && (a-> param != b-> param) ) {        \
1095      return False;                             \
1096    }                                           \
1097  } while ( 0 )
1098
1099#define MATCH_MINIMUM( param )                  \
1100  do {                                          \
1101    if ( ((int) a-> param != (int) GLX_DONT_CARE)	\
1102         && (a-> param > b-> param) ) {         \
1103      return False;                             \
1104    }                                           \
1105  } while ( 0 )
1106
1107#define MATCH_EXACT( param )                    \
1108  do {                                          \
1109    if ( a-> param != b-> param) {              \
1110      return False;                             \
1111    }                                           \
1112  } while ( 0 )
1113
1114/**
1115 * Determine if two GLXFBConfigs are compatible.
1116 *
1117 * \param a  Application specified config to test.
1118 * \param b  Server specified config to test against \c a.
1119 */
1120static Bool
1121fbconfigs_compatible(const __GLcontextModes * const a,
1122                     const __GLcontextModes * const b)
1123{
1124   MATCH_DONT_CARE(doubleBufferMode);
1125   MATCH_DONT_CARE(visualType);
1126   MATCH_DONT_CARE(visualRating);
1127   MATCH_DONT_CARE(xRenderable);
1128   MATCH_DONT_CARE(fbconfigID);
1129   MATCH_DONT_CARE(swapMethod);
1130
1131   MATCH_MINIMUM(rgbBits);
1132   MATCH_MINIMUM(numAuxBuffers);
1133   MATCH_MINIMUM(redBits);
1134   MATCH_MINIMUM(greenBits);
1135   MATCH_MINIMUM(blueBits);
1136   MATCH_MINIMUM(alphaBits);
1137   MATCH_MINIMUM(depthBits);
1138   MATCH_MINIMUM(stencilBits);
1139   MATCH_MINIMUM(accumRedBits);
1140   MATCH_MINIMUM(accumGreenBits);
1141   MATCH_MINIMUM(accumBlueBits);
1142   MATCH_MINIMUM(accumAlphaBits);
1143   MATCH_MINIMUM(sampleBuffers);
1144   MATCH_MINIMUM(maxPbufferWidth);
1145   MATCH_MINIMUM(maxPbufferHeight);
1146   MATCH_MINIMUM(maxPbufferPixels);
1147   MATCH_MINIMUM(samples);
1148
1149   MATCH_DONT_CARE(stereoMode);
1150   MATCH_EXACT(level);
1151
1152   if (((a->drawableType & b->drawableType) == 0)
1153       || ((a->renderType & b->renderType) == 0)) {
1154      return False;
1155   }
1156
1157
1158   /* There is a bug in a few of the XFree86 DDX drivers.  They contain
1159    * visuals with a "transparent type" of 0 when they really mean GLX_NONE.
1160    * Technically speaking, it is a bug in the DDX driver, but there is
1161    * enough of an installed base to work around the problem here.  In any
1162    * case, 0 is not a valid value of the transparent type, so we'll treat 0
1163    * from the app as GLX_DONT_CARE. We'll consider GLX_NONE from the app and
1164    * 0 from the server to be a match to maintain backward compatibility with
1165    * the (broken) drivers.
1166    */
1167
1168   if (a->transparentPixel != (int) GLX_DONT_CARE && a->transparentPixel != 0) {
1169      if (a->transparentPixel == GLX_NONE) {
1170         if (b->transparentPixel != GLX_NONE && b->transparentPixel != 0)
1171            return False;
1172      }
1173      else {
1174         MATCH_EXACT(transparentPixel);
1175      }
1176
1177      switch (a->transparentPixel) {
1178      case GLX_TRANSPARENT_RGB:
1179         MATCH_DONT_CARE(transparentRed);
1180         MATCH_DONT_CARE(transparentGreen);
1181         MATCH_DONT_CARE(transparentBlue);
1182         MATCH_DONT_CARE(transparentAlpha);
1183         break;
1184
1185      case GLX_TRANSPARENT_INDEX:
1186         MATCH_DONT_CARE(transparentIndex);
1187         break;
1188
1189      default:
1190         break;
1191      }
1192   }
1193
1194   return True;
1195}
1196
1197
1198/* There's some trickly language in the GLX spec about how this is supposed
1199 * to work.  Basically, if a given component size is either not specified
1200 * or the requested size is zero, it is supposed to act like PERFER_SMALLER.
1201 * Well, that's really hard to do with the code as-is.  This behavior is
1202 * closer to correct, but still not technically right.
1203 */
1204#define PREFER_LARGER_OR_ZERO(comp)             \
1205  do {                                          \
1206    if ( ((*a)-> comp) != ((*b)-> comp) ) {     \
1207      if ( ((*a)-> comp) == 0 ) {               \
1208        return -1;                              \
1209      }                                         \
1210      else if ( ((*b)-> comp) == 0 ) {          \
1211        return 1;                               \
1212      }                                         \
1213      else {                                    \
1214        return ((*b)-> comp) - ((*a)-> comp) ;  \
1215      }                                         \
1216    }                                           \
1217  } while( 0 )
1218
1219#define PREFER_LARGER(comp)                     \
1220  do {                                          \
1221    if ( ((*a)-> comp) != ((*b)-> comp) ) {     \
1222      return ((*b)-> comp) - ((*a)-> comp) ;    \
1223    }                                           \
1224  } while( 0 )
1225
1226#define PREFER_SMALLER(comp)                    \
1227  do {                                          \
1228    if ( ((*a)-> comp) != ((*b)-> comp) ) {     \
1229      return ((*a)-> comp) - ((*b)-> comp) ;    \
1230    }                                           \
1231  } while( 0 )
1232
1233/**
1234 * Compare two GLXFBConfigs.  This function is intended to be used as the
1235 * compare function passed in to qsort.
1236 *
1237 * \returns If \c a is a "better" config, according to the specification of
1238 *          SGIX_fbconfig, a number less than zero is returned.  If \c b is
1239 *          better, then a number greater than zero is return.  If both are
1240 *          equal, zero is returned.
1241 * \sa qsort, glXChooseVisual, glXChooseFBConfig, glXChooseFBConfigSGIX
1242 */
1243static int
1244fbconfig_compare(const __GLcontextModes * const *const a,
1245                 const __GLcontextModes * const *const b)
1246{
1247   /* The order of these comparisons must NOT change.  It is defined by
1248    * the GLX 1.3 spec and ARB_multisample.
1249    */
1250
1251   PREFER_SMALLER(visualSelectGroup);
1252
1253   /* The sort order for the visualRating is GLX_NONE, GLX_SLOW, and
1254    * GLX_NON_CONFORMANT_CONFIG.  It just so happens that this is the
1255    * numerical sort order of the enums (0x8000, 0x8001, and 0x800D).
1256    */
1257   PREFER_SMALLER(visualRating);
1258
1259   /* This isn't quite right.  It is supposed to compare the sum of the
1260    * components the user specifically set minimums for.
1261    */
1262   PREFER_LARGER_OR_ZERO(redBits);
1263   PREFER_LARGER_OR_ZERO(greenBits);
1264   PREFER_LARGER_OR_ZERO(blueBits);
1265   PREFER_LARGER_OR_ZERO(alphaBits);
1266
1267   PREFER_SMALLER(rgbBits);
1268
1269   if (((*a)->doubleBufferMode != (*b)->doubleBufferMode)) {
1270      /* Prefer single-buffer.
1271       */
1272      return (!(*a)->doubleBufferMode) ? -1 : 1;
1273   }
1274
1275   PREFER_SMALLER(numAuxBuffers);
1276
1277   PREFER_LARGER_OR_ZERO(depthBits);
1278   PREFER_SMALLER(stencilBits);
1279
1280   /* This isn't quite right.  It is supposed to compare the sum of the
1281    * components the user specifically set minimums for.
1282    */
1283   PREFER_LARGER_OR_ZERO(accumRedBits);
1284   PREFER_LARGER_OR_ZERO(accumGreenBits);
1285   PREFER_LARGER_OR_ZERO(accumBlueBits);
1286   PREFER_LARGER_OR_ZERO(accumAlphaBits);
1287
1288   PREFER_SMALLER(visualType);
1289
1290   /* None of the multisample specs say where this comparison should happen,
1291    * so I put it near the end.
1292    */
1293   PREFER_SMALLER(sampleBuffers);
1294   PREFER_SMALLER(samples);
1295
1296   /* None of the pbuffer or fbconfig specs say that this comparison needs
1297    * to happen at all, but it seems like it should.
1298    */
1299   PREFER_LARGER(maxPbufferWidth);
1300   PREFER_LARGER(maxPbufferHeight);
1301   PREFER_LARGER(maxPbufferPixels);
1302
1303   return 0;
1304}
1305
1306
1307/**
1308 * Selects and sorts a subset of the supplied configs based on the attributes.
1309 * This function forms to basis of \c glXChooseVisual, \c glXChooseFBConfig,
1310 * and \c glXChooseFBConfigSGIX.
1311 *
1312 * \param configs   Array of pointers to possible configs.  The elements of
1313 *                  this array that do not meet the criteria will be set to
1314 *                  NULL.  The remaining elements will be sorted according to
1315 *                  the various visual / FBConfig selection rules.
1316 * \param num_configs  Number of elements in the \c configs array.
1317 * \param attribList   Attributes used select from \c configs.  This array is
1318 *                     terminated by a \c None tag.  The array can either take
1319 *                     the form expected by \c glXChooseVisual (where boolean
1320 *                     tags do not have a value) or by \c glXChooseFBConfig
1321 *                     (where every tag has a value).
1322 * \param fbconfig_style_tags  Selects whether \c attribList is in
1323 *                             \c glXChooseVisual style or
1324 *                             \c glXChooseFBConfig style.
1325 * \returns The number of valid elements left in \c configs.
1326 *
1327 * \sa glXChooseVisual, glXChooseFBConfig, glXChooseFBConfigSGIX
1328 */
1329static int
1330choose_visual(__GLcontextModes ** configs, int num_configs,
1331              const int *attribList, GLboolean fbconfig_style_tags)
1332{
1333   __GLcontextModes test_config;
1334   int base;
1335   int i;
1336
1337   /* This is a fairly direct implementation of the selection method
1338    * described by GLX_SGIX_fbconfig.  Start by culling out all the
1339    * configs that are not compatible with the selected parameter
1340    * list.
1341    */
1342
1343   init_fbconfig_for_chooser(&test_config, fbconfig_style_tags);
1344   __glXInitializeVisualConfigFromTags(&test_config, 512,
1345                                       (const INT32 *) attribList,
1346                                       GL_TRUE, fbconfig_style_tags);
1347
1348   base = 0;
1349   for (i = 0; i < num_configs; i++) {
1350      if (fbconfigs_compatible(&test_config, configs[i])) {
1351         configs[base] = configs[i];
1352         base++;
1353      }
1354   }
1355
1356   if (base == 0) {
1357      return 0;
1358   }
1359
1360   if (base < num_configs) {
1361      (void) memset(&configs[base], 0, sizeof(void *) * (num_configs - base));
1362   }
1363
1364   /* After the incompatible configs are removed, the resulting
1365    * list is sorted according to the rules set out in the various
1366    * specifications.
1367    */
1368
1369   qsort(configs, base, sizeof(__GLcontextModes *),
1370         (int (*)(const void *, const void *)) fbconfig_compare);
1371   return base;
1372}
1373
1374
1375
1376
1377/*
1378** Return the visual that best matches the template.  Return None if no
1379** visual matches the template.
1380*/
1381PUBLIC XVisualInfo *
1382glXChooseVisual(Display * dpy, int screen, int *attribList)
1383{
1384   XVisualInfo *visualList = NULL;
1385   __GLXdisplayPrivate *priv;
1386   __GLXscreenConfigs *psc;
1387   __GLcontextModes test_config;
1388   __GLcontextModes *modes;
1389   const __GLcontextModes *best_config = NULL;
1390
1391   /*
1392    ** Get a list of all visuals, return if list is empty
1393    */
1394   if (GetGLXPrivScreenConfig(dpy, screen, &priv, &psc) != Success) {
1395      return None;
1396   }
1397
1398
1399   /*
1400    ** Build a template from the defaults and the attribute list
1401    ** Free visual list and return if an unexpected token is encountered
1402    */
1403   init_fbconfig_for_chooser(&test_config, GL_FALSE);
1404   __glXInitializeVisualConfigFromTags(&test_config, 512,
1405                                       (const INT32 *) attribList,
1406                                       GL_TRUE, GL_FALSE);
1407
1408   /*
1409    ** Eliminate visuals that don't meet minimum requirements
1410    ** Compute a score for those that do
1411    ** Remember which visual, if any, got the highest score
1412    ** If no visual is acceptable, return None
1413    ** Otherwise, create an XVisualInfo list with just the selected X visual
1414    ** and return this.
1415    */
1416   for (modes = psc->visuals; modes != NULL; modes = modes->next) {
1417      if (fbconfigs_compatible(&test_config, modes)
1418          && ((best_config == NULL)
1419              ||
1420              (fbconfig_compare
1421               ((const __GLcontextModes * const *const) &modes,
1422                &best_config) < 0))) {
1423         XVisualInfo visualTemplate;
1424         XVisualInfo *newList;
1425         int i;
1426
1427         visualTemplate.screen = screen;
1428         visualTemplate.visualid = modes->visualID;
1429         newList = XGetVisualInfo(dpy, VisualScreenMask | VisualIDMask,
1430                                  &visualTemplate, &i);
1431
1432         if (newList) {
1433            Xfree(visualList);
1434            visualList = newList;
1435            best_config = modes;
1436         }
1437      }
1438   }
1439
1440   return visualList;
1441}
1442
1443
1444PUBLIC const char *
1445glXQueryExtensionsString(Display * dpy, int screen)
1446{
1447   __GLXscreenConfigs *psc;
1448   __GLXdisplayPrivate *priv;
1449
1450   if (GetGLXPrivScreenConfig(dpy, screen, &priv, &psc) != Success) {
1451      return NULL;
1452   }
1453
1454   if (!psc->effectiveGLXexts) {
1455      if (!psc->serverGLXexts) {
1456         psc->serverGLXexts =
1457            __glXQueryServerString(dpy, priv->majorOpcode, screen,
1458                                   GLX_EXTENSIONS);
1459      }
1460
1461      __glXCalculateUsableExtensions(psc,
1462#ifdef GLX_DIRECT_RENDERING
1463                                     (psc->driScreen != NULL),
1464#else
1465                                     GL_FALSE,
1466#endif
1467                                     priv->minorVersion);
1468   }
1469
1470   return psc->effectiveGLXexts;
1471}
1472
1473PUBLIC const char *
1474glXGetClientString(Display * dpy, int name)
1475{
1476   (void) dpy;
1477
1478   switch (name) {
1479   case GLX_VENDOR:
1480      return (__glXGLXClientVendorName);
1481   case GLX_VERSION:
1482      return (__glXGLXClientVersion);
1483   case GLX_EXTENSIONS:
1484      return (__glXGetClientExtensions());
1485   default:
1486      return NULL;
1487   }
1488}
1489
1490PUBLIC const char *
1491glXQueryServerString(Display * dpy, int screen, int name)
1492{
1493   __GLXscreenConfigs *psc;
1494   __GLXdisplayPrivate *priv;
1495   const char **str;
1496
1497
1498   if (GetGLXPrivScreenConfig(dpy, screen, &priv, &psc) != Success) {
1499      return NULL;
1500   }
1501
1502   switch (name) {
1503   case GLX_VENDOR:
1504      str = &priv->serverGLXvendor;
1505      break;
1506   case GLX_VERSION:
1507      str = &priv->serverGLXversion;
1508      break;
1509   case GLX_EXTENSIONS:
1510      str = &psc->serverGLXexts;
1511      break;
1512   default:
1513      return NULL;
1514   }
1515
1516   if (*str == NULL) {
1517      *str = __glXQueryServerString(dpy, priv->majorOpcode, screen, name);
1518   }
1519
1520   return *str;
1521}
1522
1523void
1524__glXClientInfo(Display * dpy, int opcode)
1525{
1526   char *ext_str = __glXGetClientGLExtensionString();
1527   int size = strlen(ext_str) + 1;
1528
1529#ifdef USE_XCB
1530   xcb_connection_t *c = XGetXCBConnection(dpy);
1531   xcb_glx_client_info(c,
1532                       GLX_MAJOR_VERSION, GLX_MINOR_VERSION, size, ext_str);
1533#else
1534   xGLXClientInfoReq *req;
1535
1536   /* Send the glXClientInfo request */
1537   LockDisplay(dpy);
1538   GetReq(GLXClientInfo, req);
1539   req->reqType = opcode;
1540   req->glxCode = X_GLXClientInfo;
1541   req->major = GLX_MAJOR_VERSION;
1542   req->minor = GLX_MINOR_VERSION;
1543
1544   req->length += (size + 3) >> 2;
1545   req->numbytes = size;
1546   Data(dpy, ext_str, size);
1547
1548   UnlockDisplay(dpy);
1549   SyncHandle();
1550#endif /* USE_XCB */
1551
1552   Xfree(ext_str);
1553}
1554
1555
1556/*
1557** EXT_import_context
1558*/
1559
1560PUBLIC Display *
1561glXGetCurrentDisplay(void)
1562{
1563   GLXContext gc = __glXGetCurrentContext();
1564   if (NULL == gc)
1565      return NULL;
1566   return gc->currentDpy;
1567}
1568
1569PUBLIC
1570GLX_ALIAS(Display *, glXGetCurrentDisplayEXT, (void), (),
1571          glXGetCurrentDisplay)
1572
1573/**
1574 * Used internally by libGL to send \c xGLXQueryContextinfoExtReq requests
1575 * to the X-server.
1576 *
1577 * \param dpy  Display where \c ctx was created.
1578 * \param ctx  Context to query.
1579 * \returns  \c Success on success.  \c GLX_BAD_CONTEXT if \c ctx is invalid,
1580 *           or zero if the request failed due to internal problems (i.e.,
1581 *           unable to allocate temporary memory, etc.)
1582 *
1583 * \note
1584 * This function dynamically determines whether to use the EXT_import_context
1585 * version of the protocol or the GLX 1.3 version of the protocol.
1586 */
1587static int __glXQueryContextInfo(Display * dpy, GLXContext ctx)
1588{
1589   __GLXdisplayPrivate *priv = __glXInitialize(dpy);
1590   xGLXQueryContextReply reply;
1591   CARD8 opcode;
1592   GLuint numValues;
1593   int retval;
1594
1595   if (ctx == NULL) {
1596      return GLX_BAD_CONTEXT;
1597   }
1598   opcode = __glXSetupForCommand(dpy);
1599   if (!opcode) {
1600      return 0;
1601   }
1602
1603   /* Send the glXQueryContextInfoEXT request */
1604   LockDisplay(dpy);
1605
1606   if ((priv->majorVersion > 1) || (priv->minorVersion >= 3)) {
1607      xGLXQueryContextReq *req;
1608
1609      GetReq(GLXQueryContext, req);
1610
1611      req->reqType = opcode;
1612      req->glxCode = X_GLXQueryContext;
1613      req->context = (unsigned int) (ctx->xid);
1614   }
1615   else {
1616      xGLXVendorPrivateReq *vpreq;
1617      xGLXQueryContextInfoEXTReq *req;
1618
1619      GetReqExtra(GLXVendorPrivate,
1620                  sz_xGLXQueryContextInfoEXTReq - sz_xGLXVendorPrivateReq,
1621                  vpreq);
1622      req = (xGLXQueryContextInfoEXTReq *) vpreq;
1623      req->reqType = opcode;
1624      req->glxCode = X_GLXVendorPrivateWithReply;
1625      req->vendorCode = X_GLXvop_QueryContextInfoEXT;
1626      req->context = (unsigned int) (ctx->xid);
1627   }
1628
1629   _XReply(dpy, (xReply *) & reply, 0, False);
1630
1631   numValues = reply.n;
1632   if (numValues == 0)
1633      retval = Success;
1634   else if (numValues > __GLX_MAX_CONTEXT_PROPS)
1635      retval = 0;
1636   else {
1637      int *propList, *pProp;
1638      int nPropListBytes;
1639
1640      nPropListBytes = numValues << 3;
1641      propList = (int *) Xmalloc(nPropListBytes);
1642      if (NULL == propList) {
1643         retval = 0;
1644      }
1645      else {
1646	 unsigned i;
1647
1648         _XRead(dpy, (char *) propList, nPropListBytes);
1649         pProp = propList;
1650         for (i = 0; i < numValues; i++) {
1651            switch (*pProp++) {
1652            case GLX_SHARE_CONTEXT_EXT:
1653               ctx->share_xid = *pProp++;
1654               break;
1655            case GLX_VISUAL_ID_EXT:
1656               ctx->mode =
1657                  _gl_context_modes_find_visual(ctx->psc->visuals, *pProp++);
1658               break;
1659            case GLX_SCREEN:
1660               ctx->screen = *pProp++;
1661               break;
1662            case GLX_FBCONFIG_ID:
1663               ctx->mode =
1664                  _gl_context_modes_find_fbconfig(ctx->psc->configs,
1665                                                  *pProp++);
1666               break;
1667            case GLX_RENDER_TYPE:
1668               ctx->renderType = *pProp++;
1669               break;
1670            default:
1671               pProp++;
1672               continue;
1673            }
1674         }
1675         Xfree((char *) propList);
1676         retval = Success;
1677      }
1678   }
1679   UnlockDisplay(dpy);
1680   SyncHandle();
1681   return retval;
1682}
1683
1684PUBLIC int
1685glXQueryContext(Display * dpy, GLXContext ctx, int attribute, int *value)
1686{
1687   int retVal;
1688
1689   /* get the information from the server if we don't have it already */
1690#ifdef GLX_DIRECT_RENDERING
1691   if (!ctx->driContext && (ctx->mode == NULL)) {
1692#else
1693   if (ctx->mode == NULL) {
1694#endif
1695      retVal = __glXQueryContextInfo(dpy, ctx);
1696      if (Success != retVal)
1697         return retVal;
1698   }
1699   switch (attribute) {
1700   case GLX_SHARE_CONTEXT_EXT:
1701      *value = (int) (ctx->share_xid);
1702      break;
1703   case GLX_VISUAL_ID_EXT:
1704      *value = ctx->mode ? ctx->mode->visualID : None;
1705      break;
1706   case GLX_SCREEN:
1707      *value = (int) (ctx->screen);
1708      break;
1709   case GLX_FBCONFIG_ID:
1710      *value = ctx->mode ? ctx->mode->fbconfigID : None;
1711      break;
1712   case GLX_RENDER_TYPE:
1713      *value = (int) (ctx->renderType);
1714      break;
1715   default:
1716      return GLX_BAD_ATTRIBUTE;
1717   }
1718   return Success;
1719}
1720
1721PUBLIC
1722GLX_ALIAS(int, glXQueryContextInfoEXT,
1723          (Display * dpy, GLXContext ctx, int attribute, int *value),
1724          (dpy, ctx, attribute, value), glXQueryContext)
1725
1726PUBLIC GLXContextID glXGetContextIDEXT(const GLXContext ctx)
1727{
1728   return ctx->xid;
1729}
1730
1731PUBLIC GLXContext
1732glXImportContextEXT(Display * dpy, GLXContextID contextID)
1733{
1734   GLXContext ctx;
1735
1736   if (contextID == None) {
1737      return NULL;
1738   }
1739   if (__glXIsDirect(dpy, contextID)) {
1740      return NULL;
1741   }
1742
1743   ctx = CreateContext(dpy, NULL, NULL, NULL, False, contextID, False, 0);
1744   if (NULL != ctx) {
1745      if (Success != __glXQueryContextInfo(dpy, ctx)) {
1746         return NULL;
1747      }
1748   }
1749   return ctx;
1750}
1751
1752PUBLIC void
1753glXFreeContextEXT(Display * dpy, GLXContext ctx)
1754{
1755   DestroyContext(dpy, ctx);
1756}
1757
1758
1759
1760/*
1761 * GLX 1.3 functions - these are just stubs for now!
1762 */
1763
1764PUBLIC GLXFBConfig *
1765glXChooseFBConfig(Display * dpy, int screen,
1766                  const int *attribList, int *nitems)
1767{
1768   __GLcontextModes **config_list;
1769   int list_size;
1770
1771
1772   config_list = (__GLcontextModes **)
1773      glXGetFBConfigs(dpy, screen, &list_size);
1774
1775   if ((config_list != NULL) && (list_size > 0) && (attribList != NULL)) {
1776      list_size = choose_visual(config_list, list_size, attribList, GL_TRUE);
1777      if (list_size == 0) {
1778         XFree(config_list);
1779         config_list = NULL;
1780      }
1781   }
1782
1783   *nitems = list_size;
1784   return (GLXFBConfig *) config_list;
1785}
1786
1787
1788PUBLIC GLXContext
1789glXCreateNewContext(Display * dpy, GLXFBConfig config,
1790                    int renderType, GLXContext shareList, Bool allowDirect)
1791{
1792   return CreateContext(dpy, NULL, (__GLcontextModes *) config, shareList,
1793                        allowDirect, None, True, renderType);
1794}
1795
1796
1797PUBLIC GLXDrawable
1798glXGetCurrentReadDrawable(void)
1799{
1800   GLXContext gc = __glXGetCurrentContext();
1801   return gc->currentReadable;
1802}
1803
1804
1805PUBLIC GLXFBConfig *
1806glXGetFBConfigs(Display * dpy, int screen, int *nelements)
1807{
1808   __GLXdisplayPrivate *priv = __glXInitialize(dpy);
1809   __GLcontextModes **config = NULL;
1810   int i;
1811
1812   *nelements = 0;
1813   if (priv && (priv->screenConfigs != NULL)
1814       && (screen >= 0) && (screen <= ScreenCount(dpy))
1815       && (priv->screenConfigs[screen].configs != NULL)
1816       && (priv->screenConfigs[screen].configs->fbconfigID
1817	   != (int) GLX_DONT_CARE)) {
1818      unsigned num_configs = 0;
1819      __GLcontextModes *modes;
1820
1821
1822      for (modes = priv->screenConfigs[screen].configs; modes != NULL;
1823           modes = modes->next) {
1824         if (modes->fbconfigID != (int) GLX_DONT_CARE) {
1825            num_configs++;
1826         }
1827      }
1828
1829      config = (__GLcontextModes **) Xmalloc(sizeof(__GLcontextModes *)
1830                                             * num_configs);
1831      if (config != NULL) {
1832         *nelements = num_configs;
1833         i = 0;
1834         for (modes = priv->screenConfigs[screen].configs; modes != NULL;
1835              modes = modes->next) {
1836            if (modes->fbconfigID != (int) GLX_DONT_CARE) {
1837               config[i] = modes;
1838               i++;
1839            }
1840         }
1841      }
1842   }
1843   return (GLXFBConfig *) config;
1844}
1845
1846
1847PUBLIC int
1848glXGetFBConfigAttrib(Display * dpy, GLXFBConfig config,
1849                     int attribute, int *value)
1850{
1851   __GLcontextModes *const modes = ValidateGLXFBConfig(dpy, config);
1852
1853   return (modes != NULL)
1854      ? _gl_get_context_mode_data(modes, attribute, value)
1855      : GLXBadFBConfig;
1856}
1857
1858
1859PUBLIC XVisualInfo *
1860glXGetVisualFromFBConfig(Display * dpy, GLXFBConfig config)
1861{
1862   XVisualInfo visualTemplate;
1863   __GLcontextModes *fbconfig = (__GLcontextModes *) config;
1864   int count;
1865
1866   /*
1867    ** Get a list of all visuals, return if list is empty
1868    */
1869   visualTemplate.visualid = fbconfig->visualID;
1870   return XGetVisualInfo(dpy, VisualIDMask, &visualTemplate, &count);
1871}
1872
1873
1874/*
1875** GLX_SGI_swap_control
1876*/
1877static int
1878__glXSwapIntervalSGI(int interval)
1879{
1880   xGLXVendorPrivateReq *req;
1881   GLXContext gc = __glXGetCurrentContext();
1882   __GLXscreenConfigs *psc;
1883   Display *dpy;
1884   CARD32 *interval_ptr;
1885   CARD8 opcode;
1886
1887   if (gc == NULL) {
1888      return GLX_BAD_CONTEXT;
1889   }
1890
1891   if (interval <= 0) {
1892      return GLX_BAD_VALUE;
1893   }
1894
1895#ifdef __DRI_SWAP_CONTROL
1896   if (gc->driContext) {
1897      __GLXscreenConfigs * const psc = GetGLXScreenConfigs( gc->currentDpy,
1898							    gc->screen );
1899      __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(gc->currentDpy,
1900						  gc->currentDrawable,
1901						  NULL);
1902      if (psc->swapControl != NULL && pdraw != NULL) {
1903	 psc->swapControl->setSwapInterval(pdraw->driDrawable, interval);
1904	 return 0;
1905      }
1906      else if (pdraw == NULL) {
1907	 return GLX_BAD_CONTEXT;
1908      }
1909   }
1910#endif
1911   psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
1912
1913   if (gc->driContext && psc->driScreen && psc->driScreen->setSwapInterval) {
1914      __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(gc->currentDpy,
1915						  gc->currentDrawable,
1916						  NULL);
1917      psc->driScreen->setSwapInterval(pdraw, interval);
1918      return 0;
1919   }
1920
1921   dpy = gc->currentDpy;
1922   opcode = __glXSetupForCommand(dpy);
1923   if (!opcode) {
1924      return 0;
1925   }
1926
1927   /* Send the glXSwapIntervalSGI request */
1928   LockDisplay(dpy);
1929   GetReqExtra(GLXVendorPrivate, sizeof(CARD32), req);
1930   req->reqType = opcode;
1931   req->glxCode = X_GLXVendorPrivate;
1932   req->vendorCode = X_GLXvop_SwapIntervalSGI;
1933   req->contextTag = gc->currentContextTag;
1934
1935   interval_ptr = (CARD32 *) (req + 1);
1936   *interval_ptr = interval;
1937
1938   UnlockDisplay(dpy);
1939   SyncHandle();
1940   XFlush(dpy);
1941
1942   return 0;
1943}
1944
1945
1946/*
1947** GLX_MESA_swap_control
1948*/
1949static int
1950__glXSwapIntervalMESA(unsigned int interval)
1951{
1952   GLXContext gc = __glXGetCurrentContext();
1953
1954   if (interval < 0) {
1955      return GLX_BAD_VALUE;
1956   }
1957
1958#ifdef __DRI_SWAP_CONTROL
1959   if (gc != NULL && gc->driContext) {
1960      __GLXscreenConfigs *const psc = GetGLXScreenConfigs(gc->currentDpy,
1961                                                          gc->screen);
1962
1963      if ((psc != NULL) && (psc->driScreen != NULL)) {
1964         __GLXDRIdrawable *pdraw =
1965            GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable, NULL);
1966         if (psc->swapControl != NULL && pdraw != NULL) {
1967            psc->swapControl->setSwapInterval(pdraw->driDrawable, interval);
1968            return 0;
1969         }
1970      }
1971   }
1972#endif
1973
1974   if (gc != NULL && gc->driContext) {
1975      __GLXscreenConfigs *psc;
1976
1977      psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
1978      if (psc->driScreen && psc->driScreen->setSwapInterval) {
1979         __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(gc->currentDpy,
1980						     gc->currentDrawable, NULL);
1981	 psc->driScreen->setSwapInterval(pdraw, interval);
1982	 return 0;
1983      }
1984   }
1985
1986   return GLX_BAD_CONTEXT;
1987}
1988
1989
1990static int
1991__glXGetSwapIntervalMESA(void)
1992{
1993#ifdef __DRI_SWAP_CONTROL
1994   GLXContext gc = __glXGetCurrentContext();
1995
1996   if (gc != NULL && gc->driContext) {
1997      __GLXscreenConfigs *const psc = GetGLXScreenConfigs(gc->currentDpy,
1998                                                          gc->screen);
1999
2000      if ((psc != NULL) && (psc->driScreen != NULL)) {
2001         __GLXDRIdrawable *pdraw =
2002            GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable, NULL);
2003         if (psc->swapControl != NULL && pdraw != NULL) {
2004            return psc->swapControl->getSwapInterval(pdraw->driDrawable);
2005         }
2006      }
2007   }
2008#endif
2009   if (gc != NULL && gc->driContext) {
2010      __GLXscreenConfigs *psc;
2011
2012      psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
2013      if (psc->driScreen && psc->driScreen->getSwapInterval) {
2014         __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(gc->currentDpy,
2015						     gc->currentDrawable, NULL);
2016	 return psc->driScreen->getSwapInterval(pdraw);
2017      }
2018   }
2019
2020   return 0;
2021}
2022
2023
2024/*
2025** GLX_MESA_swap_frame_usage
2026*/
2027
2028static GLint
2029__glXBeginFrameTrackingMESA(Display * dpy, GLXDrawable drawable)
2030{
2031   int status = GLX_BAD_CONTEXT;
2032#ifdef __DRI_FRAME_TRACKING
2033   int screen = 0;
2034   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2035   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
2036
2037   if (pdraw != NULL && psc->frameTracking != NULL)
2038      status = psc->frameTracking->frameTracking(pdraw->driDrawable, GL_TRUE);
2039#else
2040   (void) dpy;
2041   (void) drawable;
2042#endif
2043   return status;
2044}
2045
2046
2047static GLint
2048__glXEndFrameTrackingMESA(Display * dpy, GLXDrawable drawable)
2049{
2050   int status = GLX_BAD_CONTEXT;
2051#ifdef __DRI_FRAME_TRACKING
2052   int screen = 0;
2053   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2054   __GLXscreenConfigs *psc = GetGLXScreenConfigs(dpy, screen);
2055
2056   if (pdraw != NULL && psc->frameTracking != NULL)
2057      status = psc->frameTracking->frameTracking(pdraw->driDrawable,
2058                                                 GL_FALSE);
2059#else
2060   (void) dpy;
2061   (void) drawable;
2062#endif
2063   return status;
2064}
2065
2066
2067static GLint
2068__glXGetFrameUsageMESA(Display * dpy, GLXDrawable drawable, GLfloat * usage)
2069{
2070   int status = GLX_BAD_CONTEXT;
2071#ifdef __DRI_FRAME_TRACKING
2072   int screen = 0;
2073   __GLXDRIdrawable *const pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2074   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
2075
2076   if (pdraw != NULL && psc->frameTracking != NULL) {
2077      int64_t sbc, missedFrames;
2078      float lastMissedUsage;
2079
2080      status = psc->frameTracking->queryFrameTracking(pdraw->driDrawable,
2081                                                      &sbc,
2082                                                      &missedFrames,
2083                                                      &lastMissedUsage,
2084                                                      usage);
2085   }
2086#else
2087   (void) dpy;
2088   (void) drawable;
2089   (void) usage;
2090#endif
2091   return status;
2092}
2093
2094
2095static GLint
2096__glXQueryFrameTrackingMESA(Display * dpy, GLXDrawable drawable,
2097                            int64_t * sbc, int64_t * missedFrames,
2098                            GLfloat * lastMissedUsage)
2099{
2100   int status = GLX_BAD_CONTEXT;
2101#ifdef __DRI_FRAME_TRACKING
2102   int screen = 0;
2103   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2104   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
2105
2106   if (pdraw != NULL && psc->frameTracking != NULL) {
2107      float usage;
2108
2109      status = psc->frameTracking->queryFrameTracking(pdraw->driDrawable,
2110                                                      sbc, missedFrames,
2111                                                      lastMissedUsage,
2112                                                      &usage);
2113   }
2114#else
2115   (void) dpy;
2116   (void) drawable;
2117   (void) sbc;
2118   (void) missedFrames;
2119   (void) lastMissedUsage;
2120#endif
2121   return status;
2122}
2123
2124
2125/*
2126** GLX_SGI_video_sync
2127*/
2128static int
2129__glXGetVideoSyncSGI(unsigned int *count)
2130{
2131   int64_t ust, msc, sbc;
2132   int ret;
2133   GLXContext gc = __glXGetCurrentContext();
2134   __GLXscreenConfigs *psc;
2135   __GLXDRIdrawable *pdraw;
2136
2137   if (!gc || !gc->driContext)
2138      return GLX_BAD_CONTEXT;
2139
2140   psc = GetGLXScreenConfigs(gc->currentDpy, gc->screen);
2141   pdraw = GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable, NULL);
2142
2143   /* FIXME: Looking at the GLX_SGI_video_sync spec in the extension registry,
2144    * FIXME: there should be a GLX encoding for this call.  I can find no
2145    * FIXME: documentation for the GLX encoding.
2146    */
2147#ifdef __DRI_MEDIA_STREAM_COUNTER
2148   if ( psc->msc && psc->driScreen ) {
2149      ret = (*psc->msc->getDrawableMSC)(psc->__driScreen,
2150					pdraw->driDrawable, &msc);
2151      *count = (unsigned) msc;
2152
2153      return (ret == 0) ? 0 : GLX_BAD_CONTEXT;
2154   }
2155#endif
2156   if (psc->driScreen && psc->driScreen->getDrawableMSC) {
2157      ret = psc->driScreen->getDrawableMSC(psc, pdraw, &ust, &msc, &sbc);
2158      *count = (unsigned) msc;
2159      return (ret == True) ? 0 : GLX_BAD_CONTEXT;
2160   }
2161
2162   return GLX_BAD_CONTEXT;
2163}
2164
2165static int
2166__glXWaitVideoSyncSGI(int divisor, int remainder, unsigned int *count)
2167{
2168   GLXContext gc = __glXGetCurrentContext();
2169   __GLXscreenConfigs *psc;
2170   __GLXDRIdrawable *pdraw;
2171   int64_t ust, msc, sbc;
2172   int ret;
2173
2174   if (divisor <= 0 || remainder < 0)
2175      return GLX_BAD_VALUE;
2176
2177   if (!gc || !gc->driContext)
2178      return GLX_BAD_CONTEXT;
2179
2180   psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
2181   pdraw = GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable, NULL);
2182
2183#ifdef __DRI_MEDIA_STREAM_COUNTER
2184   if (psc->msc != NULL && psc->driScreen ) {
2185      ret = (*psc->msc->waitForMSC)(pdraw->driDrawable, 0,
2186				    divisor, remainder, &msc, &sbc);
2187      *count = (unsigned) msc;
2188      return (ret == 0) ? 0 : GLX_BAD_CONTEXT;
2189   }
2190#endif
2191   if (psc->driScreen && psc->driScreen->waitForMSC) {
2192      ret = psc->driScreen->waitForMSC(pdraw, 0, divisor, remainder, &ust, &msc,
2193				       &sbc);
2194      *count = (unsigned) msc;
2195      return (ret == True) ? 0 : GLX_BAD_CONTEXT;
2196   }
2197
2198   return GLX_BAD_CONTEXT;
2199}
2200
2201
2202/*
2203** GLX_SGIX_fbconfig
2204** Many of these functions are aliased to GLX 1.3 entry points in the
2205** GLX_functions table.
2206*/
2207
2208PUBLIC
2209GLX_ALIAS(int, glXGetFBConfigAttribSGIX,
2210          (Display * dpy, GLXFBConfigSGIX config, int attribute, int *value),
2211          (dpy, config, attribute, value), glXGetFBConfigAttrib)
2212
2213PUBLIC GLX_ALIAS(GLXFBConfigSGIX *, glXChooseFBConfigSGIX,
2214                 (Display * dpy, int screen, int *attrib_list,
2215                  int *nelements), (dpy, screen, attrib_list, nelements),
2216                 glXChooseFBConfig)
2217
2218PUBLIC GLX_ALIAS(XVisualInfo *, glXGetVisualFromFBConfigSGIX,
2219                 (Display * dpy, GLXFBConfigSGIX config),
2220                 (dpy, config), glXGetVisualFromFBConfig)
2221
2222PUBLIC GLXPixmap
2223glXCreateGLXPixmapWithConfigSGIX(Display * dpy,
2224                                 GLXFBConfigSGIX config,
2225                                 Pixmap pixmap)
2226{
2227   xGLXVendorPrivateWithReplyReq *vpreq;
2228   xGLXCreateGLXPixmapWithConfigSGIXReq *req;
2229   GLXPixmap xid = None;
2230   CARD8 opcode;
2231   const __GLcontextModes *const fbconfig = (__GLcontextModes *) config;
2232   __GLXscreenConfigs *psc;
2233
2234
2235   if ((dpy == NULL) || (config == NULL)) {
2236      return None;
2237   }
2238
2239   psc = GetGLXScreenConfigs(dpy, fbconfig->screen);
2240   if ((psc != NULL)
2241       && __glXExtensionBitIsEnabled(psc, SGIX_fbconfig_bit)) {
2242      opcode = __glXSetupForCommand(dpy);
2243      if (!opcode) {
2244         return None;
2245      }
2246
2247      /* Send the glXCreateGLXPixmapWithConfigSGIX request */
2248      LockDisplay(dpy);
2249      GetReqExtra(GLXVendorPrivateWithReply,
2250                  sz_xGLXCreateGLXPixmapWithConfigSGIXReq -
2251                  sz_xGLXVendorPrivateWithReplyReq, vpreq);
2252      req = (xGLXCreateGLXPixmapWithConfigSGIXReq *) vpreq;
2253      req->reqType = opcode;
2254      req->glxCode = X_GLXVendorPrivateWithReply;
2255      req->vendorCode = X_GLXvop_CreateGLXPixmapWithConfigSGIX;
2256      req->screen = fbconfig->screen;
2257      req->fbconfig = fbconfig->fbconfigID;
2258      req->pixmap = pixmap;
2259      req->glxpixmap = xid = XAllocID(dpy);
2260      UnlockDisplay(dpy);
2261      SyncHandle();
2262   }
2263
2264   return xid;
2265}
2266
2267PUBLIC GLXContext
2268glXCreateContextWithConfigSGIX(Display * dpy,
2269                               GLXFBConfigSGIX config, int renderType,
2270                               GLXContext shareList, Bool allowDirect)
2271{
2272   GLXContext gc = NULL;
2273   const __GLcontextModes *const fbconfig = (__GLcontextModes *) config;
2274   __GLXscreenConfigs *psc;
2275
2276
2277   if ((dpy == NULL) || (config == NULL)) {
2278      return None;
2279   }
2280
2281   psc = GetGLXScreenConfigs(dpy, fbconfig->screen);
2282   if ((psc != NULL)
2283       && __glXExtensionBitIsEnabled(psc, SGIX_fbconfig_bit)) {
2284      gc = CreateContext(dpy, NULL, (__GLcontextModes *) config, shareList,
2285                         allowDirect, None, False, renderType);
2286   }
2287
2288   return gc;
2289}
2290
2291
2292PUBLIC GLXFBConfigSGIX
2293glXGetFBConfigFromVisualSGIX(Display * dpy, XVisualInfo * vis)
2294{
2295   __GLXdisplayPrivate *priv;
2296   __GLXscreenConfigs *psc = NULL;
2297
2298   if ((GetGLXPrivScreenConfig(dpy, vis->screen, &priv, &psc) != Success)
2299       && __glXExtensionBitIsEnabled(psc, SGIX_fbconfig_bit)
2300       && (psc->configs->fbconfigID != (int) GLX_DONT_CARE)) {
2301      return (GLXFBConfigSGIX) _gl_context_modes_find_visual(psc->configs,
2302                                                             vis->visualid);
2303   }
2304
2305   return NULL;
2306}
2307
2308
2309/*
2310** GLX_SGIX_swap_group
2311*/
2312static void
2313__glXJoinSwapGroupSGIX(Display * dpy, GLXDrawable drawable,
2314                       GLXDrawable member)
2315{
2316   (void) dpy;
2317   (void) drawable;
2318   (void) member;
2319}
2320
2321
2322/*
2323** GLX_SGIX_swap_barrier
2324*/
2325static void
2326__glXBindSwapBarrierSGIX(Display * dpy, GLXDrawable drawable, int barrier)
2327{
2328   (void) dpy;
2329   (void) drawable;
2330   (void) barrier;
2331}
2332
2333static Bool
2334__glXQueryMaxSwapBarriersSGIX(Display * dpy, int screen, int *max)
2335{
2336   (void) dpy;
2337   (void) screen;
2338   (void) max;
2339   return False;
2340}
2341
2342
2343/*
2344** GLX_OML_sync_control
2345*/
2346static Bool
2347__glXGetSyncValuesOML(Display * dpy, GLXDrawable drawable,
2348                      int64_t * ust, int64_t * msc, int64_t * sbc)
2349{
2350   __GLXdisplayPrivate * const priv = __glXInitialize(dpy);
2351   int i, ret;
2352   __GLXDRIdrawable *pdraw;
2353   __GLXscreenConfigs *psc;
2354
2355   if (!priv)
2356      return False;
2357
2358   pdraw = GetGLXDRIDrawable(dpy, drawable, &i);
2359   psc = &priv->screenConfigs[i];
2360
2361#if defined(__DRI_SWAP_BUFFER_COUNTER) && defined(__DRI_MEDIA_STREAM_COUNTER)
2362   if (pdraw && psc->sbc && psc->sbc)
2363      return ( (pdraw && psc->sbc && psc->msc)
2364	       && ((*psc->msc->getMSC)(psc->driScreen, msc) == 0)
2365	       && ((*psc->sbc->getSBC)(pdraw->driDrawable, sbc) == 0)
2366	       && (__glXGetUST(ust) == 0) );
2367#endif
2368   if (pdraw && psc && psc->driScreen && psc->driScreen->getDrawableMSC) {
2369      ret = psc->driScreen->getDrawableMSC(psc, pdraw, ust, msc, sbc);
2370      return ret;
2371   }
2372
2373   return False;
2374}
2375
2376#ifdef GLX_DIRECT_RENDERING
2377_X_HIDDEN GLboolean
2378__driGetMscRateOML(__DRIdrawable * draw,
2379                   int32_t * numerator, int32_t * denominator, void *private)
2380{
2381#ifdef XF86VIDMODE
2382   __GLXscreenConfigs *psc;
2383   XF86VidModeModeLine mode_line;
2384   int dot_clock;
2385   int i;
2386   __GLXDRIdrawable *glxDraw = private;
2387
2388   (void) draw;
2389
2390   psc = glxDraw->psc;
2391   if (XF86VidModeQueryVersion(psc->dpy, &i, &i) &&
2392       XF86VidModeGetModeLine(psc->dpy, psc->scr, &dot_clock, &mode_line)) {
2393      unsigned n = dot_clock * 1000;
2394      unsigned d = mode_line.vtotal * mode_line.htotal;
2395
2396# define V_INTERLACE 0x010
2397# define V_DBLSCAN   0x020
2398
2399      if (mode_line.flags & V_INTERLACE)
2400         n *= 2;
2401      else if (mode_line.flags & V_DBLSCAN)
2402         d *= 2;
2403
2404      /* The OML_sync_control spec requires that if the refresh rate is a
2405       * whole number, that the returned numerator be equal to the refresh
2406       * rate and the denominator be 1.
2407       */
2408
2409      if (n % d == 0) {
2410         n /= d;
2411         d = 1;
2412      }
2413      else {
2414         static const unsigned f[] = { 13, 11, 7, 5, 3, 2, 0 };
2415
2416         /* This is a poor man's way to reduce a fraction.  It's far from
2417          * perfect, but it will work well enough for this situation.
2418          */
2419
2420         for (i = 0; f[i] != 0; i++) {
2421            while (n % f[i] == 0 && d % f[i] == 0) {
2422               d /= f[i];
2423               n /= f[i];
2424            }
2425         }
2426      }
2427
2428      *numerator = n;
2429      *denominator = d;
2430
2431      return True;
2432   }
2433   else
2434      return False;
2435#else
2436   (void) draw;
2437   (void) numerator;
2438   (void) denominator;
2439   (void) private;
2440
2441   return False;
2442#endif
2443}
2444#endif
2445
2446/**
2447 * Determine the refresh rate of the specified drawable and display.
2448 *
2449 * \param dpy          Display whose refresh rate is to be determined.
2450 * \param drawable     Drawable whose refresh rate is to be determined.
2451 * \param numerator    Numerator of the refresh rate.
2452 * \param demoninator  Denominator of the refresh rate.
2453 * \return  If the refresh rate for the specified display and drawable could
2454 *          be calculated, True is returned.  Otherwise False is returned.
2455 *
2456 * \note This function is implemented entirely client-side.  A lot of other
2457 *       functionality is required to export GLX_OML_sync_control, so on
2458 *       XFree86 this function can be called for direct-rendering contexts
2459 *       when GLX_OML_sync_control appears in the client extension string.
2460 */
2461
2462_X_HIDDEN GLboolean
2463__glXGetMscRateOML(Display * dpy, GLXDrawable drawable,
2464                   int32_t * numerator, int32_t * denominator)
2465{
2466#if defined( GLX_DIRECT_RENDERING ) && defined( XF86VIDMODE )
2467   __GLXDRIdrawable *draw = GetGLXDRIDrawable(dpy, drawable, NULL);
2468
2469   if (draw == NULL)
2470      return False;
2471
2472   return __driGetMscRateOML(draw->driDrawable, numerator, denominator, draw);
2473#else
2474   (void) dpy;
2475   (void) drawable;
2476   (void) numerator;
2477   (void) denominator;
2478#endif
2479   return False;
2480}
2481
2482
2483static int64_t
2484__glXSwapBuffersMscOML(Display * dpy, GLXDrawable drawable,
2485                       int64_t target_msc, int64_t divisor, int64_t remainder)
2486{
2487   GLXContext gc = __glXGetCurrentContext();
2488   int screen;
2489   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2490   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
2491
2492   if (!pdraw || !gc->driContext) /* no GLX for this */
2493      return -1;
2494
2495   /* The OML_sync_control spec says these should "generate a GLX_BAD_VALUE
2496    * error", but it also says "It [glXSwapBuffersMscOML] will return a value
2497    * of -1 if the function failed because of errors detected in the input
2498    * parameters"
2499    */
2500   if (divisor < 0 || remainder < 0 || target_msc < 0)
2501      return -1;
2502   if (divisor > 0 && remainder >= divisor)
2503      return -1;
2504
2505#ifdef __DRI_SWAP_BUFFER_COUNTER
2506   if (psc->counters != NULL)
2507      return (*psc->sbc->swapBuffersMSC)(pdraw->driDrawable, target_msc,
2508					 divisor, remainder);
2509#endif
2510
2511#ifdef GLX_DIRECT_RENDERING
2512   if (psc->driScreen && psc->driScreen->swapBuffers)
2513      return (*psc->driScreen->swapBuffers)(pdraw, target_msc, divisor,
2514					    remainder);
2515#endif
2516
2517   return -1;
2518}
2519
2520
2521static Bool
2522__glXWaitForMscOML(Display * dpy, GLXDrawable drawable,
2523                   int64_t target_msc, int64_t divisor,
2524                   int64_t remainder, int64_t * ust,
2525                   int64_t * msc, int64_t * sbc)
2526{
2527   int screen;
2528   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2529   __GLXscreenConfigs * const psc = GetGLXScreenConfigs( dpy, screen );
2530   int ret;
2531
2532   fprintf(stderr, "waitmsc: %lld, %lld, %lld\n", target_msc, divisor,
2533	   remainder);
2534
2535   /* The OML_sync_control spec says these should "generate a GLX_BAD_VALUE
2536    * error", but the return type in the spec is Bool.
2537    */
2538   if (divisor < 0 || remainder < 0 || target_msc < 0)
2539      return False;
2540   if (divisor > 0 && remainder >= divisor)
2541      return False;
2542
2543#ifdef __DRI_MEDIA_STREAM_COUNTER
2544   if (pdraw != NULL && psc->msc != NULL) {
2545      fprintf(stderr, "dri1 msc\n");
2546      ret = (*psc->msc->waitForMSC) (pdraw->driDrawable, target_msc,
2547                                     divisor, remainder, msc, sbc);
2548
2549      /* __glXGetUST returns zero on success and non-zero on failure.
2550       * This function returns True on success and False on failure.
2551       */
2552      return ((ret == 0) && (__glXGetUST(ust) == 0));
2553   }
2554#endif
2555   if (pdraw && psc->driScreen && psc->driScreen->waitForMSC) {
2556      ret = psc->driScreen->waitForMSC(pdraw, target_msc, divisor, remainder,
2557				       ust, msc, sbc);
2558      return ret;
2559   }
2560
2561   fprintf(stderr, "no drawable??\n");
2562   return False;
2563}
2564
2565
2566static Bool
2567__glXWaitForSbcOML(Display * dpy, GLXDrawable drawable,
2568                   int64_t target_sbc, int64_t * ust,
2569                   int64_t * msc, int64_t * sbc)
2570{
2571   int screen;
2572   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2573   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
2574   int ret;
2575
2576   /* The OML_sync_control spec says this should "generate a GLX_BAD_VALUE
2577    * error", but the return type in the spec is Bool.
2578    */
2579   if (target_sbc < 0)
2580      return False;
2581#ifdef __DRI_SWAP_BUFFER_COUNTER
2582   if (pdraw != NULL && psc->sbc != NULL) {
2583      ret =
2584         (*psc->sbc->waitForSBC) (pdraw->driDrawable, target_sbc, msc, sbc);
2585
2586      /* __glXGetUST returns zero on success and non-zero on failure.
2587       * This function returns True on success and False on failure.
2588       */
2589      return ((ret == 0) && (__glXGetUST(ust) == 0));
2590   }
2591#endif
2592   if (pdraw && psc->driScreen && psc->driScreen->waitForMSC) {
2593      ret = psc->driScreen->waitForSBC(pdraw, target_sbc, ust, msc, sbc);
2594      return ret;
2595   }
2596   return False;
2597}
2598
2599
2600/**
2601 * GLX_MESA_allocate_memory
2602 */
2603/*@{*/
2604
2605PUBLIC void *
2606glXAllocateMemoryMESA(Display * dpy, int scrn,
2607                      size_t size, float readFreq,
2608                      float writeFreq, float priority)
2609{
2610#ifdef __DRI_ALLOCATE
2611   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, scrn);
2612
2613   if (psc && psc->allocate)
2614      return (*psc->allocate->allocateMemory) (psc->__driScreen, size,
2615                                               readFreq, writeFreq, priority);
2616
2617#else
2618   (void) dpy;
2619   (void) scrn;
2620   (void) size;
2621   (void) readFreq;
2622   (void) writeFreq;
2623   (void) priority;
2624#endif /* __DRI_ALLOCATE */
2625
2626   return NULL;
2627}
2628
2629
2630PUBLIC void
2631glXFreeMemoryMESA(Display * dpy, int scrn, void *pointer)
2632{
2633#ifdef __DRI_ALLOCATE
2634   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, scrn);
2635
2636   if (psc && psc->allocate)
2637      (*psc->allocate->freeMemory) (psc->__driScreen, pointer);
2638
2639#else
2640   (void) dpy;
2641   (void) scrn;
2642   (void) pointer;
2643#endif /* __DRI_ALLOCATE */
2644}
2645
2646
2647PUBLIC GLuint
2648glXGetMemoryOffsetMESA(Display * dpy, int scrn, const void *pointer)
2649{
2650#ifdef __DRI_ALLOCATE
2651   __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, scrn);
2652
2653   if (psc && psc->allocate)
2654      return (*psc->allocate->memoryOffset) (psc->__driScreen, pointer);
2655
2656#else
2657   (void) dpy;
2658   (void) scrn;
2659   (void) pointer;
2660#endif /* GLX_DIRECT_RENDERING */
2661
2662   return ~0L;
2663}
2664
2665/*@}*/
2666
2667
2668/**
2669 * Mesa extension stubs.  These will help reduce portability problems.
2670 */
2671/*@{*/
2672
2673/**
2674 * Release all buffers associated with the specified GLX drawable.
2675 *
2676 * \todo
2677 * This function was intended for stand-alone Mesa.  The issue there is that
2678 * the library doesn't get any notification when a window is closed.  In
2679 * DRI there is a similar but slightly different issue.  When GLX 1.3 is
2680 * supported, there are 3 different functions to destroy a drawable.  It
2681 * should be possible to create GLX protocol (or have it determine which
2682 * protocol to use based on the type of the drawable) to have one function
2683 * do the work of 3.  For the direct-rendering case, this function could
2684 * just call the driver's \c __DRIdrawableRec::destroyDrawable function.
2685 * This would reduce the frequency with which \c __driGarbageCollectDrawables
2686 * would need to be used.  This really should be done as part of the new DRI
2687 * interface work.
2688 *
2689 * \sa http://oss.sgi.com/projects/ogl-sample/registry/MESA/release_buffers.txt
2690 *     __driGarbageCollectDrawables
2691 *     glXDestroyGLXPixmap
2692 *     glXDestroyPbuffer glXDestroyPixmap glXDestroyWindow
2693 *     glXDestroyGLXPbufferSGIX glXDestroyGLXVideoSourceSGIX
2694 */
2695static Bool
2696__glXReleaseBuffersMESA(Display * dpy, GLXDrawable d)
2697{
2698   (void) dpy;
2699   (void) d;
2700   return False;
2701}
2702
2703
2704PUBLIC GLXPixmap
2705glXCreateGLXPixmapMESA(Display * dpy, XVisualInfo * visual,
2706                       Pixmap pixmap, Colormap cmap)
2707{
2708   (void) dpy;
2709   (void) visual;
2710   (void) pixmap;
2711   (void) cmap;
2712   return 0;
2713}
2714
2715/*@}*/
2716
2717
2718/**
2719 * GLX_MESA_copy_sub_buffer
2720 */
2721#define X_GLXvop_CopySubBufferMESA 5154 /* temporary */
2722static void
2723__glXCopySubBufferMESA(Display * dpy, GLXDrawable drawable,
2724                       int x, int y, int width, int height)
2725{
2726   xGLXVendorPrivateReq *req;
2727   GLXContext gc;
2728   GLXContextTag tag;
2729   CARD32 *drawable_ptr;
2730   INT32 *x_ptr, *y_ptr, *w_ptr, *h_ptr;
2731   CARD8 opcode;
2732
2733#ifdef __DRI_COPY_SUB_BUFFER
2734   int screen;
2735   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, &screen);
2736   if (pdraw != NULL) {
2737      __GLXscreenConfigs *const psc = GetGLXScreenConfigs(dpy, screen);
2738      if (psc->driScreen->copySubBuffer != NULL) {
2739         glFlush();
2740         (*psc->driScreen->copySubBuffer) (pdraw, x, y, width, height);
2741      }
2742
2743      return;
2744   }
2745#endif
2746
2747   opcode = __glXSetupForCommand(dpy);
2748   if (!opcode)
2749      return;
2750
2751   /*
2752    ** The calling thread may or may not have a current context.  If it
2753    ** does, send the context tag so the server can do a flush.
2754    */
2755   gc = __glXGetCurrentContext();
2756   if ((gc != NULL) && (dpy == gc->currentDpy) &&
2757       ((drawable == gc->currentDrawable) ||
2758        (drawable == gc->currentReadable))) {
2759      tag = gc->currentContextTag;
2760   }
2761   else {
2762      tag = 0;
2763   }
2764
2765   LockDisplay(dpy);
2766   GetReqExtra(GLXVendorPrivate, sizeof(CARD32) + sizeof(INT32) * 4, req);
2767   req->reqType = opcode;
2768   req->glxCode = X_GLXVendorPrivate;
2769   req->vendorCode = X_GLXvop_CopySubBufferMESA;
2770   req->contextTag = tag;
2771
2772   drawable_ptr = (CARD32 *) (req + 1);
2773   x_ptr = (INT32 *) (drawable_ptr + 1);
2774   y_ptr = (INT32 *) (drawable_ptr + 2);
2775   w_ptr = (INT32 *) (drawable_ptr + 3);
2776   h_ptr = (INT32 *) (drawable_ptr + 4);
2777
2778   *drawable_ptr = drawable;
2779   *x_ptr = x;
2780   *y_ptr = y;
2781   *w_ptr = width;
2782   *h_ptr = height;
2783
2784   UnlockDisplay(dpy);
2785   SyncHandle();
2786}
2787
2788
2789/**
2790 * GLX_EXT_texture_from_pixmap
2791 */
2792/*@{*/
2793static void
2794__glXBindTexImageEXT(Display * dpy,
2795                     GLXDrawable drawable, int buffer, const int *attrib_list)
2796{
2797   xGLXVendorPrivateReq *req;
2798   GLXContext gc = __glXGetCurrentContext();
2799   CARD32 *drawable_ptr;
2800   INT32 *buffer_ptr;
2801   CARD32 *num_attrib_ptr;
2802   CARD32 *attrib_ptr;
2803   CARD8 opcode;
2804   unsigned int i;
2805
2806   if (gc == NULL)
2807      return;
2808
2809   i = 0;
2810   if (attrib_list) {
2811      while (attrib_list[i * 2] != None)
2812         i++;
2813   }
2814
2815#ifdef GLX_DIRECT_RENDERING
2816   if (gc->driContext) {
2817      __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable, NULL);
2818
2819      if (pdraw != NULL) {
2820         if (pdraw->psc->texBuffer->base.version >= 2 &&
2821             pdraw->psc->texBuffer->setTexBuffer2 != NULL) {
2822            (*pdraw->psc->texBuffer->setTexBuffer2) (gc->__driContext,
2823                                                     pdraw->textureTarget,
2824                                                     pdraw->textureFormat,
2825                                                     pdraw->driDrawable);
2826         }
2827         else {
2828            (*pdraw->psc->texBuffer->setTexBuffer) (gc->__driContext,
2829                                                    pdraw->textureTarget,
2830                                                    pdraw->driDrawable);
2831         }
2832      }
2833      return;
2834   }
2835#endif
2836
2837   opcode = __glXSetupForCommand(dpy);
2838   if (!opcode)
2839      return;
2840
2841   LockDisplay(dpy);
2842   GetReqExtra(GLXVendorPrivate, 12 + 8 * i, req);
2843   req->reqType = opcode;
2844   req->glxCode = X_GLXVendorPrivate;
2845   req->vendorCode = X_GLXvop_BindTexImageEXT;
2846   req->contextTag = gc->currentContextTag;
2847
2848   drawable_ptr = (CARD32 *) (req + 1);
2849   buffer_ptr = (INT32 *) (drawable_ptr + 1);
2850   num_attrib_ptr = (CARD32 *) (buffer_ptr + 1);
2851   attrib_ptr = (CARD32 *) (num_attrib_ptr + 1);
2852
2853   *drawable_ptr = drawable;
2854   *buffer_ptr = buffer;
2855   *num_attrib_ptr = (CARD32) i;
2856
2857   i = 0;
2858   if (attrib_list) {
2859      while (attrib_list[i * 2] != None) {
2860         *attrib_ptr++ = (CARD32) attrib_list[i * 2 + 0];
2861         *attrib_ptr++ = (CARD32) attrib_list[i * 2 + 1];
2862         i++;
2863      }
2864   }
2865
2866   UnlockDisplay(dpy);
2867   SyncHandle();
2868}
2869
2870static void
2871__glXReleaseTexImageEXT(Display * dpy, GLXDrawable drawable, int buffer)
2872{
2873   xGLXVendorPrivateReq *req;
2874   GLXContext gc = __glXGetCurrentContext();
2875   CARD32 *drawable_ptr;
2876   INT32 *buffer_ptr;
2877   CARD8 opcode;
2878
2879   if ((gc == NULL) || GC_IS_DIRECT(gc))
2880      return;
2881
2882   opcode = __glXSetupForCommand(dpy);
2883   if (!opcode)
2884      return;
2885
2886   LockDisplay(dpy);
2887   GetReqExtra(GLXVendorPrivate, sizeof(CARD32) + sizeof(INT32), req);
2888   req->reqType = opcode;
2889   req->glxCode = X_GLXVendorPrivate;
2890   req->vendorCode = X_GLXvop_ReleaseTexImageEXT;
2891   req->contextTag = gc->currentContextTag;
2892
2893   drawable_ptr = (CARD32 *) (req + 1);
2894   buffer_ptr = (INT32 *) (drawable_ptr + 1);
2895
2896   *drawable_ptr = drawable;
2897   *buffer_ptr = buffer;
2898
2899   UnlockDisplay(dpy);
2900   SyncHandle();
2901}
2902
2903/*@}*/
2904
2905/**
2906 * \c strdup is actually not a standard ANSI C or POSIX routine.
2907 * Irix will not define it if ANSI mode is in effect.
2908 *
2909 * \sa strdup
2910 */
2911_X_HIDDEN char *
2912__glXstrdup(const char *str)
2913{
2914   char *copy;
2915   copy = (char *) Xmalloc(strlen(str) + 1);
2916   if (!copy)
2917      return NULL;
2918   strcpy(copy, str);
2919   return copy;
2920}
2921
2922/*
2923** glXGetProcAddress support
2924*/
2925
2926struct name_address_pair
2927{
2928   const char *Name;
2929   GLvoid *Address;
2930};
2931
2932#define GLX_FUNCTION(f) { # f, (GLvoid *) f }
2933#define GLX_FUNCTION2(n,f) { # n, (GLvoid *) f }
2934
2935static const struct name_address_pair GLX_functions[] = {
2936   /*** GLX_VERSION_1_0 ***/
2937   GLX_FUNCTION(glXChooseVisual),
2938   GLX_FUNCTION(glXCopyContext),
2939   GLX_FUNCTION(glXCreateContext),
2940   GLX_FUNCTION(glXCreateGLXPixmap),
2941   GLX_FUNCTION(glXDestroyContext),
2942   GLX_FUNCTION(glXDestroyGLXPixmap),
2943   GLX_FUNCTION(glXGetConfig),
2944   GLX_FUNCTION(glXGetCurrentContext),
2945   GLX_FUNCTION(glXGetCurrentDrawable),
2946   GLX_FUNCTION(glXIsDirect),
2947   GLX_FUNCTION(glXMakeCurrent),
2948   GLX_FUNCTION(glXQueryExtension),
2949   GLX_FUNCTION(glXQueryVersion),
2950   GLX_FUNCTION(glXSwapBuffers),
2951   GLX_FUNCTION(glXUseXFont),
2952   GLX_FUNCTION(glXWaitGL),
2953   GLX_FUNCTION(glXWaitX),
2954
2955   /*** GLX_VERSION_1_1 ***/
2956   GLX_FUNCTION(glXGetClientString),
2957   GLX_FUNCTION(glXQueryExtensionsString),
2958   GLX_FUNCTION(glXQueryServerString),
2959
2960   /*** GLX_VERSION_1_2 ***/
2961   GLX_FUNCTION(glXGetCurrentDisplay),
2962
2963   /*** GLX_VERSION_1_3 ***/
2964   GLX_FUNCTION(glXChooseFBConfig),
2965   GLX_FUNCTION(glXCreateNewContext),
2966   GLX_FUNCTION(glXCreatePbuffer),
2967   GLX_FUNCTION(glXCreatePixmap),
2968   GLX_FUNCTION(glXCreateWindow),
2969   GLX_FUNCTION(glXDestroyPbuffer),
2970   GLX_FUNCTION(glXDestroyPixmap),
2971   GLX_FUNCTION(glXDestroyWindow),
2972   GLX_FUNCTION(glXGetCurrentReadDrawable),
2973   GLX_FUNCTION(glXGetFBConfigAttrib),
2974   GLX_FUNCTION(glXGetFBConfigs),
2975   GLX_FUNCTION(glXGetSelectedEvent),
2976   GLX_FUNCTION(glXGetVisualFromFBConfig),
2977   GLX_FUNCTION(glXMakeContextCurrent),
2978   GLX_FUNCTION(glXQueryContext),
2979   GLX_FUNCTION(glXQueryDrawable),
2980   GLX_FUNCTION(glXSelectEvent),
2981
2982   /*** GLX_SGI_swap_control ***/
2983   GLX_FUNCTION2(glXSwapIntervalSGI, __glXSwapIntervalSGI),
2984
2985   /*** GLX_SGI_video_sync ***/
2986   GLX_FUNCTION2(glXGetVideoSyncSGI, __glXGetVideoSyncSGI),
2987   GLX_FUNCTION2(glXWaitVideoSyncSGI, __glXWaitVideoSyncSGI),
2988
2989   /*** GLX_SGI_make_current_read ***/
2990   GLX_FUNCTION2(glXMakeCurrentReadSGI, glXMakeContextCurrent),
2991   GLX_FUNCTION2(glXGetCurrentReadDrawableSGI, glXGetCurrentReadDrawable),
2992
2993   /*** GLX_EXT_import_context ***/
2994   GLX_FUNCTION(glXFreeContextEXT),
2995   GLX_FUNCTION(glXGetContextIDEXT),
2996   GLX_FUNCTION2(glXGetCurrentDisplayEXT, glXGetCurrentDisplay),
2997   GLX_FUNCTION(glXImportContextEXT),
2998   GLX_FUNCTION2(glXQueryContextInfoEXT, glXQueryContext),
2999
3000   /*** GLX_SGIX_fbconfig ***/
3001   GLX_FUNCTION2(glXGetFBConfigAttribSGIX, glXGetFBConfigAttrib),
3002   GLX_FUNCTION2(glXChooseFBConfigSGIX, glXChooseFBConfig),
3003   GLX_FUNCTION(glXCreateGLXPixmapWithConfigSGIX),
3004   GLX_FUNCTION(glXCreateContextWithConfigSGIX),
3005   GLX_FUNCTION2(glXGetVisualFromFBConfigSGIX, glXGetVisualFromFBConfig),
3006   GLX_FUNCTION(glXGetFBConfigFromVisualSGIX),
3007
3008   /*** GLX_SGIX_pbuffer ***/
3009   GLX_FUNCTION(glXCreateGLXPbufferSGIX),
3010   GLX_FUNCTION(glXDestroyGLXPbufferSGIX),
3011   GLX_FUNCTION(glXQueryGLXPbufferSGIX),
3012   GLX_FUNCTION(glXSelectEventSGIX),
3013   GLX_FUNCTION(glXGetSelectedEventSGIX),
3014
3015   /*** GLX_SGIX_swap_group ***/
3016   GLX_FUNCTION2(glXJoinSwapGroupSGIX, __glXJoinSwapGroupSGIX),
3017
3018   /*** GLX_SGIX_swap_barrier ***/
3019   GLX_FUNCTION2(glXBindSwapBarrierSGIX, __glXBindSwapBarrierSGIX),
3020   GLX_FUNCTION2(glXQueryMaxSwapBarriersSGIX, __glXQueryMaxSwapBarriersSGIX),
3021
3022   /*** GLX_MESA_allocate_memory ***/
3023   GLX_FUNCTION(glXAllocateMemoryMESA),
3024   GLX_FUNCTION(glXFreeMemoryMESA),
3025   GLX_FUNCTION(glXGetMemoryOffsetMESA),
3026
3027   /*** GLX_MESA_copy_sub_buffer ***/
3028   GLX_FUNCTION2(glXCopySubBufferMESA, __glXCopySubBufferMESA),
3029
3030   /*** GLX_MESA_pixmap_colormap ***/
3031   GLX_FUNCTION(glXCreateGLXPixmapMESA),
3032
3033   /*** GLX_MESA_release_buffers ***/
3034   GLX_FUNCTION2(glXReleaseBuffersMESA, __glXReleaseBuffersMESA),
3035
3036   /*** GLX_MESA_swap_control ***/
3037   GLX_FUNCTION2(glXSwapIntervalMESA, __glXSwapIntervalMESA),
3038   GLX_FUNCTION2(glXGetSwapIntervalMESA, __glXGetSwapIntervalMESA),
3039
3040   /*** GLX_MESA_swap_frame_usage ***/
3041   GLX_FUNCTION2(glXBeginFrameTrackingMESA, __glXBeginFrameTrackingMESA),
3042   GLX_FUNCTION2(glXEndFrameTrackingMESA, __glXEndFrameTrackingMESA),
3043   GLX_FUNCTION2(glXGetFrameUsageMESA, __glXGetFrameUsageMESA),
3044   GLX_FUNCTION2(glXQueryFrameTrackingMESA, __glXQueryFrameTrackingMESA),
3045
3046   /*** GLX_ARB_get_proc_address ***/
3047   GLX_FUNCTION(glXGetProcAddressARB),
3048
3049   /*** GLX 1.4 ***/
3050   GLX_FUNCTION2(glXGetProcAddress, glXGetProcAddressARB),
3051
3052   /*** GLX_OML_sync_control ***/
3053   GLX_FUNCTION2(glXWaitForSbcOML, __glXWaitForSbcOML),
3054   GLX_FUNCTION2(glXWaitForMscOML, __glXWaitForMscOML),
3055   GLX_FUNCTION2(glXSwapBuffersMscOML, __glXSwapBuffersMscOML),
3056   GLX_FUNCTION2(glXGetMscRateOML, __glXGetMscRateOML),
3057   GLX_FUNCTION2(glXGetSyncValuesOML, __glXGetSyncValuesOML),
3058
3059   /*** GLX_EXT_texture_from_pixmap ***/
3060   GLX_FUNCTION2(glXBindTexImageEXT, __glXBindTexImageEXT),
3061   GLX_FUNCTION2(glXReleaseTexImageEXT, __glXReleaseTexImageEXT),
3062
3063#ifdef GLX_DIRECT_RENDERING
3064   /*** DRI configuration ***/
3065   GLX_FUNCTION(glXGetScreenDriver),
3066   GLX_FUNCTION(glXGetDriverConfig),
3067#endif
3068
3069   {NULL, NULL}                 /* end of list */
3070};
3071
3072
3073static const GLvoid *
3074get_glx_proc_address(const char *funcName)
3075{
3076   GLuint i;
3077
3078   /* try static functions */
3079   for (i = 0; GLX_functions[i].Name; i++) {
3080      if (strcmp(GLX_functions[i].Name, funcName) == 0)
3081         return GLX_functions[i].Address;
3082   }
3083
3084   return NULL;
3085}
3086
3087
3088/**
3089 * Get the address of a named GL function.  This is the pre-GLX 1.4 name for
3090 * \c glXGetProcAddress.
3091 *
3092 * \param procName  Name of a GL or GLX function.
3093 * \returns         A pointer to the named function
3094 *
3095 * \sa glXGetProcAddress
3096 */
3097PUBLIC void (*glXGetProcAddressARB(const GLubyte * procName)) (void)
3098{
3099   typedef void (*gl_function) (void);
3100   gl_function f;
3101
3102
3103   /* Search the table of GLX and internal functions first.  If that
3104    * fails and the supplied name could be a valid core GL name, try
3105    * searching the core GL function table.  This check is done to prevent
3106    * DRI based drivers from searching the core GL function table for
3107    * internal API functions.
3108    */
3109
3110   f = (gl_function) get_glx_proc_address((const char *) procName);
3111   if ((f == NULL) && (procName[0] == 'g') && (procName[1] == 'l')
3112       && (procName[2] != 'X')) {
3113      f = (gl_function) _glapi_get_proc_address((const char *) procName);
3114   }
3115
3116   return f;
3117}
3118
3119/**
3120 * Get the address of a named GL function.  This is the GLX 1.4 name for
3121 * \c glXGetProcAddressARB.
3122 *
3123 * \param procName  Name of a GL or GLX function.
3124 * \returns         A pointer to the named function
3125 *
3126 * \sa glXGetProcAddressARB
3127 */
3128PUBLIC void (*glXGetProcAddress(const GLubyte * procName)) (void)
3129#if defined(__GNUC__) && !defined(GLX_ALIAS_UNSUPPORTED)
3130   __attribute__ ((alias("glXGetProcAddressARB")));
3131#else
3132{
3133   return glXGetProcAddressARB(procName);
3134}
3135#endif /* __GNUC__ */
3136
3137
3138#ifdef GLX_DIRECT_RENDERING
3139/**
3140 * Get the unadjusted system time (UST).  Currently, the UST is measured in
3141 * microseconds since Epoc.  The actual resolution of the UST may vary from
3142 * system to system, and the units may vary from release to release.
3143 * Drivers should not call this function directly.  They should instead use
3144 * \c glXGetProcAddress to obtain a pointer to the function.
3145 *
3146 * \param ust Location to store the 64-bit UST
3147 * \returns Zero on success or a negative errno value on failure.
3148 *
3149 * \sa glXGetProcAddress, PFNGLXGETUSTPROC
3150 *
3151 * \since Internal API version 20030317.
3152 */
3153_X_HIDDEN int
3154__glXGetUST(int64_t * ust)
3155{
3156   struct timeval tv;
3157
3158   if (ust == NULL) {
3159      return -EFAULT;
3160   }
3161
3162   if (gettimeofday(&tv, NULL) == 0) {
3163      ust[0] = (tv.tv_sec * 1000000) + tv.tv_usec;
3164      return 0;
3165   }
3166   else {
3167      return -errno;
3168   }
3169}
3170#endif /* GLX_DIRECT_RENDERING */
3171