OSDN Git Service

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