OSDN Git Service

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