ieframe: Use proper helpers for iface calls.
[wine] / dlls / winex11.drv / opengl.c
1 /*
2  * X11DRV OpenGL functions
3  *
4  * Copyright 2000 Lionel Ulmer
5  * Copyright 2005 Alex Woods
6  * Copyright 2005 Raphael Junqueira
7  * Copyright 2006-2009 Roderick Colenbrander
8  * Copyright 2006 Tomas Carnecky
9  * Copyright 2012 Alexandre Julliard
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <assert.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #ifdef HAVE_SYS_SOCKET_H
34 #include <sys/socket.h>
35 #endif
36 #ifdef HAVE_SYS_UN_H
37 #include <sys/un.h>
38 #endif
39 #ifdef HAVE_GL_GL_H
40 # include <GL/gl.h>
41 #endif
42 #ifdef HAVE_GL_GLX_H
43 # include <GL/glx.h>
44 #endif
45 #undef APIENTRY
46 #undef GLAPI
47 #undef WINGDIAPI
48
49 #include "x11drv.h"
50 #include "winternl.h"
51 #include "wine/library.h"
52 #include "wine/debug.h"
53
54 WINE_DEFAULT_DEBUG_CHANNEL(wgl);
55
56 #ifdef SONAME_LIBGL
57
58 WINE_DECLARE_DEBUG_CHANNEL(winediag);
59 WINE_DECLARE_DEBUG_CHANNEL(fps);
60
61 #include "wine/wgl_driver.h"
62 #include "wine/wglext.h"
63
64 /* For compatibility with old Mesa headers */
65 #ifndef GLX_SAMPLE_BUFFERS_ARB
66 # define GLX_SAMPLE_BUFFERS_ARB           100000
67 #endif
68 #ifndef GLX_SAMPLES_ARB
69 # define GLX_SAMPLES_ARB                  100001
70 #endif
71 #ifndef GL_TEXTURE_CUBE_MAP
72 # define GL_TEXTURE_CUBE_MAP              0x8513
73 #endif
74 #ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT
75 # define GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20B2
76 #endif
77 #ifndef GLX_EXT_fbconfig_packed_float
78 # define GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT 0x20B1
79 # define GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT  0x00000008
80 #endif
81 #ifndef GLX_ARB_create_context
82 # define GLX_CONTEXT_MAJOR_VERSION_ARB    0x2091
83 # define GLX_CONTEXT_MINOR_VERSION_ARB    0x2092
84 # define GLX_CONTEXT_FLAGS_ARB            0x2094
85 #endif
86 #ifndef GLX_ARB_create_context_profile
87 # define GLX_CONTEXT_PROFILE_MASK_ARB     0x9126
88 #endif
89 /** GLX_ATI_pixel_format_float */
90 #define GLX_RGBA_FLOAT_ATI_BIT            0x00000100
91 /** GLX_ARB_pixel_format_float */
92 #define GLX_RGBA_FLOAT_BIT                0x00000004
93 #define GLX_RGBA_FLOAT_TYPE               0x20B9
94 /** GL_NV_float_buffer */
95 #define GL_FLOAT_R_NV                     0x8880
96 #define GL_FLOAT_RG_NV                    0x8881
97 #define GL_FLOAT_RGB_NV                   0x8882
98 #define GL_FLOAT_RGBA_NV                  0x8883
99 #define GL_FLOAT_R16_NV                   0x8884
100 #define GL_FLOAT_R32_NV                   0x8885
101 #define GL_FLOAT_RG16_NV                  0x8886
102 #define GL_FLOAT_RG32_NV                  0x8887
103 #define GL_FLOAT_RGB16_NV                 0x8888
104 #define GL_FLOAT_RGB32_NV                 0x8889
105 #define GL_FLOAT_RGBA16_NV                0x888A
106 #define GL_FLOAT_RGBA32_NV                0x888B
107 #define GL_TEXTURE_FLOAT_COMPONENTS_NV    0x888C
108 #define GL_FLOAT_CLEAR_COLOR_VALUE_NV     0x888D
109 #define GL_FLOAT_RGBA_MODE_NV             0x888E
110 /** GLX_NV_float_buffer */
111 #define GLX_FLOAT_COMPONENTS_NV           0x20B0
112
113
114 struct WineGLInfo {
115     const char *glVersion;
116     char *glExtensions;
117
118     int glxVersion[2];
119
120     const char *glxServerVersion;
121     const char *glxServerVendor;
122     const char *glxServerExtensions;
123
124     const char *glxClientVersion;
125     const char *glxClientVendor;
126     const char *glxClientExtensions;
127
128     const char *glxExtensions;
129
130     BOOL glxDirect;
131     char wglExtensions[4096];
132 };
133
134 typedef struct wine_glpixelformat {
135     int         iPixelFormat;
136     GLXFBConfig fbconfig;
137     int         fmt_id;
138     int         render_type;
139     BOOL        offscreenOnly;
140     DWORD       dwFlags; /* We store some PFD_* flags in here for emulated bitmap formats */
141 } WineGLPixelFormat;
142
143 struct wgl_context
144 {
145     HDC hdc;
146     BOOL has_been_current;
147     BOOL sharing;
148     BOOL gl3_context;
149     XVisualInfo *vis;
150     WineGLPixelFormat *fmt;
151     int numAttribs; /* This is needed for delaying wglCreateContextAttribsARB */
152     int attribList[16]; /* This is needed for delaying wglCreateContextAttribsARB */
153     GLXContext ctx;
154     Drawable drawables[2];
155     BOOL refresh_drawables;
156     Pixmap pixmap;            /* pixmap for memory DCs */
157     GLXPixmap glxpixmap;      /* GLX pixmap for memory DCs */
158     SIZE pixmap_size;         /* pixmap size for memory DCs */
159     struct list entry;
160 };
161
162 struct wgl_pbuffer
163 {
164     Drawable   drawable;
165     WineGLPixelFormat* fmt;
166     int        width;
167     int        height;
168     int*       attribList;
169     int        use_render_texture; /* This is also the internal texture format */
170     int        texture_bind_target;
171     int        texture_bpp;
172     GLint      texture_format;
173     GLuint     texture_target;
174     GLenum     texture_type;
175     GLuint     texture;
176     int        texture_level;
177 };
178
179 struct glx_physdev
180 {
181     struct gdi_physdev dev;
182     X11DRV_PDEVICE    *x11dev;
183     enum dc_gl_type    type;          /* type of GL device context */
184     int                pixel_format;
185     Drawable           drawable;
186     Pixmap             pixmap;        /* pixmap for a DL_GL_PIXMAP_WIN drawable */
187 };
188
189 static const struct gdi_dc_funcs glxdrv_funcs;
190
191 static inline struct glx_physdev *get_glxdrv_dev( PHYSDEV dev )
192 {
193     return (struct glx_physdev *)dev;
194 }
195
196 static struct list context_list = LIST_INIT( context_list );
197 static struct WineGLInfo WineGLInfo = { 0 };
198 static int use_render_texture_emulation = 1;
199 static BOOL has_swap_control;
200 static int swap_interval = 1;
201
202 static struct opengl_funcs opengl_funcs;
203
204 #define USE_GL_FUNC(name) #name,
205 static const char *opengl_func_names[] = { ALL_WGL_FUNCS };
206 #undef USE_GL_FUNC
207
208 static void X11DRV_WineGL_LoadExtensions(void);
209 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count);
210 static BOOL glxRequireVersion(int requiredVersion);
211
212 static void dump_PIXELFORMATDESCRIPTOR(const PIXELFORMATDESCRIPTOR *ppfd) {
213   TRACE("  - size / version : %d / %d\n", ppfd->nSize, ppfd->nVersion);
214   TRACE("  - dwFlags : ");
215 #define TEST_AND_DUMP(t,tv) if ((t) & (tv)) TRACE(#tv " ")
216   TEST_AND_DUMP(ppfd->dwFlags, PFD_DEPTH_DONTCARE);
217   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER);
218   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER_DONTCARE);
219   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_WINDOW);
220   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_BITMAP);
221   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_ACCELERATED);
222   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_FORMAT);
223   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_PALETTE);
224   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_SYSTEM_PALETTE);
225   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO);
226   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO_DONTCARE);
227   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_GDI);
228   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_OPENGL);
229   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_COPY);
230   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_EXCHANGE);
231   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_LAYER_BUFFERS);
232   /* PFD_SUPPORT_COMPOSITION is new in Vista, it is similar to composition
233    * under X e.g. COMPOSITE + GLX_EXT_TEXTURE_FROM_PIXMAP. */
234   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_COMPOSITION);
235 #undef TEST_AND_DUMP
236   TRACE("\n");
237
238   TRACE("  - iPixelType : ");
239   switch (ppfd->iPixelType) {
240   case PFD_TYPE_RGBA: TRACE("PFD_TYPE_RGBA"); break;
241   case PFD_TYPE_COLORINDEX: TRACE("PFD_TYPE_COLORINDEX"); break;
242   }
243   TRACE("\n");
244
245   TRACE("  - Color   : %d\n", ppfd->cColorBits);
246   TRACE("  - Red     : %d\n", ppfd->cRedBits);
247   TRACE("  - Green   : %d\n", ppfd->cGreenBits);
248   TRACE("  - Blue    : %d\n", ppfd->cBlueBits);
249   TRACE("  - Alpha   : %d\n", ppfd->cAlphaBits);
250   TRACE("  - Accum   : %d\n", ppfd->cAccumBits);
251   TRACE("  - Depth   : %d\n", ppfd->cDepthBits);
252   TRACE("  - Stencil : %d\n", ppfd->cStencilBits);
253   TRACE("  - Aux     : %d\n", ppfd->cAuxBuffers);
254
255   TRACE("  - iLayerType : ");
256   switch (ppfd->iLayerType) {
257   case PFD_MAIN_PLANE: TRACE("PFD_MAIN_PLANE"); break;
258   case PFD_OVERLAY_PLANE: TRACE("PFD_OVERLAY_PLANE"); break;
259   case (BYTE)PFD_UNDERLAY_PLANE: TRACE("PFD_UNDERLAY_PLANE"); break;
260   }
261   TRACE("\n");
262 }
263
264 #define PUSH1(attribs,att)        do { attribs[nAttribs++] = (att); } while (0)
265 #define PUSH2(attribs,att,value)  do { attribs[nAttribs++] = (att); attribs[nAttribs++] = (value); } while(0)
266
267 #define MAKE_FUNCPTR(f) static typeof(f) * p##f;
268 /* GLX 1.0 */
269 MAKE_FUNCPTR(glXChooseVisual)
270 MAKE_FUNCPTR(glXCopyContext)
271 MAKE_FUNCPTR(glXCreateContext)
272 MAKE_FUNCPTR(glXCreateGLXPixmap)
273 MAKE_FUNCPTR(glXGetCurrentContext)
274 MAKE_FUNCPTR(glXGetCurrentDrawable)
275 MAKE_FUNCPTR(glXDestroyContext)
276 MAKE_FUNCPTR(glXDestroyGLXPixmap)
277 MAKE_FUNCPTR(glXGetConfig)
278 MAKE_FUNCPTR(glXIsDirect)
279 MAKE_FUNCPTR(glXMakeCurrent)
280 MAKE_FUNCPTR(glXSwapBuffers)
281 MAKE_FUNCPTR(glXQueryExtension)
282 MAKE_FUNCPTR(glXQueryVersion)
283
284 /* GLX 1.1 */
285 MAKE_FUNCPTR(glXGetClientString)
286 MAKE_FUNCPTR(glXQueryExtensionsString)
287 MAKE_FUNCPTR(glXQueryServerString)
288
289 /* GLX 1.3 */
290 MAKE_FUNCPTR(glXGetFBConfigs)
291 MAKE_FUNCPTR(glXChooseFBConfig)
292 MAKE_FUNCPTR(glXCreatePbuffer)
293 MAKE_FUNCPTR(glXCreateNewContext)
294 MAKE_FUNCPTR(glXDestroyPbuffer)
295 MAKE_FUNCPTR(glXGetFBConfigAttrib)
296 MAKE_FUNCPTR(glXGetVisualFromFBConfig)
297 MAKE_FUNCPTR(glXMakeContextCurrent)
298 MAKE_FUNCPTR(glXQueryDrawable)
299 MAKE_FUNCPTR(glXGetCurrentReadDrawable)
300 #undef MAKE_FUNCPTR
301
302 /* GLX Extensions */
303 static GLXContext (*pglXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
304 static void* (*pglXGetProcAddressARB)(const GLubyte *);
305 static int   (*pglXSwapIntervalSGI)(int);
306
307 /* NV GLX Extension */
308 static void* (*pglXAllocateMemoryNV)(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
309 static void  (*pglXFreeMemoryNV)(GLvoid *pointer);
310
311 /* MESA GLX Extensions */
312 static void (*pglXCopySubBufferMESA)(Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
313
314 /* Standard OpenGL */
315 static void (*pglFinish)(void);
316 static void (*pglFlush)(void);
317
318 static void wglFinish(void);
319 static void wglFlush(void);
320
321 /* check if the extension is present in the list */
322 static BOOL has_extension( const char *list, const char *ext )
323 {
324     size_t len = strlen( ext );
325
326     while (list)
327     {
328         while (*list == ' ') list++;
329         if (!strncmp( list, ext, len ) && (!list[len] || list[len] == ' ')) return TRUE;
330         list = strchr( list, ' ' );
331     }
332     return FALSE;
333 }
334
335 static int GLXErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
336 {
337     /* In the future we might want to find the exact X or GLX error to report back to the app */
338     return 1;
339 }
340
341 static BOOL infoInitialized = FALSE;
342 static BOOL X11DRV_WineGL_InitOpenglInfo(void)
343 {
344     int screen = DefaultScreen(gdi_display);
345     Window win = 0, root = 0;
346     const char *gl_renderer;
347     const char* str;
348     XVisualInfo *vis;
349     GLXContext ctx = NULL;
350     XSetWindowAttributes attr;
351     BOOL ret = FALSE;
352     int attribList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
353
354     if (infoInitialized)
355         return TRUE;
356     infoInitialized = TRUE;
357
358     attr.override_redirect = True;
359     attr.colormap = None;
360     attr.border_pixel = 0;
361
362     wine_tsx11_lock();
363
364     vis = pglXChooseVisual(gdi_display, screen, attribList);
365     if (vis) {
366 #ifdef __i386__
367         WORD old_fs = wine_get_fs();
368         /* Create a GLX Context. Without one we can't query GL information */
369         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
370         if (wine_get_fs() != old_fs)
371         {
372             wine_set_fs( old_fs );
373             ERR( "%%fs register corrupted, probably broken ATI driver, disabling OpenGL.\n" );
374             ERR( "You need to set the \"UseFastTls\" option to \"2\" in your X config file.\n" );
375             goto done;
376         }
377 #else
378         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
379 #endif
380     }
381     if (!ctx) goto done;
382
383     root = RootWindow( gdi_display, vis->screen );
384     if (vis->visual != DefaultVisual( gdi_display, vis->screen ))
385         attr.colormap = XCreateColormap( gdi_display, root, vis->visual, AllocNone );
386     if ((win = XCreateWindow( gdi_display, root, -1, -1, 1, 1, 0, vis->depth, InputOutput,
387                               vis->visual, CWBorderPixel | CWOverrideRedirect | CWColormap, &attr )))
388         XMapWindow( gdi_display, win );
389     else
390         win = root;
391
392     if(pglXMakeCurrent(gdi_display, win, ctx) == 0)
393     {
394         ERR_(winediag)( "Unable to activate OpenGL context, most likely your OpenGL drivers haven't been installed correctly\n" );
395         goto done;
396     }
397     gl_renderer = (const char *)opengl_funcs.gl.p_glGetString(GL_RENDERER);
398     WineGLInfo.glVersion = (const char *) opengl_funcs.gl.p_glGetString(GL_VERSION);
399     str = (const char *) opengl_funcs.gl.p_glGetString(GL_EXTENSIONS);
400     WineGLInfo.glExtensions = HeapAlloc(GetProcessHeap(), 0, strlen(str)+1);
401     strcpy(WineGLInfo.glExtensions, str);
402
403     /* Get the common GLX version supported by GLX client and server ( major/minor) */
404     pglXQueryVersion(gdi_display, &WineGLInfo.glxVersion[0], &WineGLInfo.glxVersion[1]);
405
406     WineGLInfo.glxServerVersion = pglXQueryServerString(gdi_display, screen, GLX_VERSION);
407     WineGLInfo.glxServerVendor = pglXQueryServerString(gdi_display, screen, GLX_VENDOR);
408     WineGLInfo.glxServerExtensions = pglXQueryServerString(gdi_display, screen, GLX_EXTENSIONS);
409
410     WineGLInfo.glxClientVersion = pglXGetClientString(gdi_display, GLX_VERSION);
411     WineGLInfo.glxClientVendor = pglXGetClientString(gdi_display, GLX_VENDOR);
412     WineGLInfo.glxClientExtensions = pglXGetClientString(gdi_display, GLX_EXTENSIONS);
413
414     WineGLInfo.glxExtensions = pglXQueryExtensionsString(gdi_display, screen);
415     WineGLInfo.glxDirect = pglXIsDirect(gdi_display, ctx);
416
417     TRACE("GL version             : %s.\n", WineGLInfo.glVersion);
418     TRACE("GL renderer            : %s.\n", gl_renderer);
419     TRACE("GLX version            : %d.%d.\n", WineGLInfo.glxVersion[0], WineGLInfo.glxVersion[1]);
420     TRACE("Server GLX version     : %s.\n", WineGLInfo.glxServerVersion);
421     TRACE("Server GLX vendor:     : %s.\n", WineGLInfo.glxServerVendor);
422     TRACE("Client GLX version     : %s.\n", WineGLInfo.glxClientVersion);
423     TRACE("Client GLX vendor:     : %s.\n", WineGLInfo.glxClientVendor);
424     TRACE("Direct rendering enabled: %s\n", WineGLInfo.glxDirect ? "True" : "False");
425
426     if(!WineGLInfo.glxDirect)
427     {
428         int fd = ConnectionNumber(gdi_display);
429         struct sockaddr_un uaddr;
430         unsigned int uaddrlen = sizeof(struct sockaddr_un);
431
432         /* In general indirect rendering on a local X11 server indicates a driver problem.
433          * Detect a local X11 server by checking whether the X11 socket is a Unix socket.
434          */
435         if(!getsockname(fd, (struct sockaddr *)&uaddr, &uaddrlen) && uaddr.sun_family == AF_UNIX)
436             ERR_(winediag)("Direct rendering is disabled, most likely your OpenGL drivers "
437                            "haven't been installed correctly (using GL renderer %s, version %s).\n",
438                            debugstr_a(gl_renderer), debugstr_a(WineGLInfo.glVersion));
439     }
440     else
441     {
442         /* In general you would expect that if direct rendering is returned, that you receive hardware
443          * accelerated OpenGL rendering. The definition of direct rendering is that rendering is performed
444          * client side without sending all GL commands to X using the GLX protocol. When Mesa falls back to
445          * software rendering, it shows direct rendering.
446          *
447          * Depending on the cause of software rendering a different rendering string is shown. In case Mesa fails
448          * to load a DRI module 'Software Rasterizer' is returned. When Mesa is compiled as a OpenGL reference driver
449          * it shows 'Mesa X11'.
450          */
451         if(!strcmp(gl_renderer, "Software Rasterizer") || !strcmp(gl_renderer, "Mesa X11"))
452             ERR_(winediag)("The Mesa OpenGL driver is using software rendering, most likely your OpenGL "
453                            "drivers haven't been installed correctly (using GL renderer %s, version %s).\n",
454                            debugstr_a(gl_renderer), debugstr_a(WineGLInfo.glVersion));
455     }
456     ret = TRUE;
457
458 done:
459     if(vis) XFree(vis);
460     if(ctx) {
461         pglXMakeCurrent(gdi_display, None, NULL);    
462         pglXDestroyContext(gdi_display, ctx);
463     }
464     if (win != root) XDestroyWindow( gdi_display, win );
465     if (attr.colormap) XFreeColormap( gdi_display, attr.colormap );
466     wine_tsx11_unlock();
467     if (!ret) ERR(" couldn't initialize OpenGL, expect problems\n");
468     return ret;
469 }
470
471 static BOOL has_opengl(void)
472 {
473     static int init_done;
474     static void *opengl_handle;
475
476     char buffer[200];
477     int error_base, event_base;
478     unsigned int i;
479
480     if (init_done) return (opengl_handle != NULL);
481     init_done = 1;
482
483     /* No need to load any other libraries as according to the ABI, libGL should be self-sufficient
484        and include all dependencies */
485     opengl_handle = wine_dlopen(SONAME_LIBGL, RTLD_NOW|RTLD_GLOBAL, buffer, sizeof(buffer));
486     if (opengl_handle == NULL)
487     {
488         ERR( "Failed to load libGL: %s\n", buffer );
489         ERR( "OpenGL support is disabled.\n");
490         return FALSE;
491     }
492
493     for (i = 0; i < sizeof(opengl_func_names)/sizeof(opengl_func_names[0]); i++)
494     {
495         if (!(((void **)&opengl_funcs.gl)[i] = wine_dlsym( opengl_handle, opengl_func_names[i], NULL, 0 )))
496         {
497             ERR( "%s not found in libGL, disabling OpenGL.\n", opengl_func_names[i] );
498             goto failed;
499         }
500     }
501
502     /* redirect some standard OpenGL functions */
503 #define REDIRECT(func) \
504     do { p##func = opengl_funcs.gl.p_##func; opengl_funcs.gl.p_##func = w##func; } while(0)
505     REDIRECT( glFinish );
506     REDIRECT( glFlush );
507 #undef REDIRECT
508
509     pglXGetProcAddressARB = wine_dlsym(opengl_handle, "glXGetProcAddressARB", NULL, 0);
510     if (pglXGetProcAddressARB == NULL) {
511         ERR("Could not find glXGetProcAddressARB in libGL, disabling OpenGL.\n");
512         goto failed;
513     }
514
515 #define LOAD_FUNCPTR(f) do if((p##f = (void*)pglXGetProcAddressARB((const unsigned char*)#f)) == NULL) \
516     { \
517         ERR( "%s not found in libGL, disabling OpenGL.\n", #f ); \
518         goto failed; \
519     } while(0)
520
521     /* GLX 1.0 */
522     LOAD_FUNCPTR(glXChooseVisual);
523     LOAD_FUNCPTR(glXCopyContext);
524     LOAD_FUNCPTR(glXCreateContext);
525     LOAD_FUNCPTR(glXCreateGLXPixmap);
526     LOAD_FUNCPTR(glXGetCurrentContext);
527     LOAD_FUNCPTR(glXGetCurrentDrawable);
528     LOAD_FUNCPTR(glXDestroyContext);
529     LOAD_FUNCPTR(glXDestroyGLXPixmap);
530     LOAD_FUNCPTR(glXGetConfig);
531     LOAD_FUNCPTR(glXIsDirect);
532     LOAD_FUNCPTR(glXMakeCurrent);
533     LOAD_FUNCPTR(glXSwapBuffers);
534     LOAD_FUNCPTR(glXQueryExtension);
535     LOAD_FUNCPTR(glXQueryVersion);
536
537     /* GLX 1.1 */
538     LOAD_FUNCPTR(glXGetClientString);
539     LOAD_FUNCPTR(glXQueryExtensionsString);
540     LOAD_FUNCPTR(glXQueryServerString);
541
542     /* GLX 1.3 */
543     LOAD_FUNCPTR(glXCreatePbuffer);
544     LOAD_FUNCPTR(glXCreateNewContext);
545     LOAD_FUNCPTR(glXDestroyPbuffer);
546     LOAD_FUNCPTR(glXMakeContextCurrent);
547     LOAD_FUNCPTR(glXGetCurrentReadDrawable);
548     LOAD_FUNCPTR(glXGetFBConfigs);
549 #undef LOAD_FUNCPTR
550
551 /* It doesn't matter if these fail. They'll only be used if the driver reports
552    the associated extension is available (and if a driver reports the extension
553    is available but fails to provide the functions, it's quite broken) */
554 #define LOAD_FUNCPTR(f) p##f = pglXGetProcAddressARB((const GLubyte *)#f)
555     /* ARB GLX Extension */
556     LOAD_FUNCPTR(glXCreateContextAttribsARB);
557     /* SGI GLX Extension */
558     LOAD_FUNCPTR(glXSwapIntervalSGI);
559     /* NV GLX Extension */
560     LOAD_FUNCPTR(glXAllocateMemoryNV);
561     LOAD_FUNCPTR(glXFreeMemoryNV);
562 #undef LOAD_FUNCPTR
563
564     if(!X11DRV_WineGL_InitOpenglInfo()) goto failed;
565
566     wine_tsx11_lock();
567     if (pglXQueryExtension(gdi_display, &error_base, &event_base)) {
568         TRACE("GLX is up and running error_base = %d\n", error_base);
569     } else {
570         wine_tsx11_unlock();
571         ERR( "GLX extension is missing, disabling OpenGL.\n" );
572         goto failed;
573     }
574
575     /* In case of GLX you have direct and indirect rendering. Most of the time direct rendering is used
576      * as in general only that is hardware accelerated. In some cases like in case of remote X indirect
577      * rendering is used.
578      *
579      * The main problem for our OpenGL code is that we need certain GLX calls but their presence
580      * depends on the reported GLX client / server version and on the client / server extension list.
581      * Those don't have to be the same.
582      *
583      * In general the server GLX information lists the capabilities in case of indirect rendering.
584      * When direct rendering is used, the OpenGL client library is responsible for which GLX calls are
585      * available and in that case the client GLX informat can be used.
586      * OpenGL programs should use the 'intersection' of both sets of information which is advertised
587      * in the GLX version/extension list. When a program does this it works for certain for both
588      * direct and indirect rendering.
589      *
590      * The problem we are having in this area is that ATI's Linux drivers are broken. For some reason
591      * they haven't added some very important GLX extensions like GLX_SGIX_fbconfig to their client
592      * extension list which causes this extension not to be listed. (Wine requires this extension).
593      * ATI advertises a GLX client version of 1.3 which implies that this fbconfig extension among
594      * pbuffers is around.
595      *
596      * In order to provide users of Ati's proprietary drivers with OpenGL support, we need to detect
597      * the ATI drivers and from then on use GLX client information for them.
598      */
599
600     if(glxRequireVersion(3)) {
601         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
602         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
603         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
604         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
605     } else if (has_extension( WineGLInfo.glxExtensions, "GLX_SGIX_fbconfig")) {
606         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfigSGIX");
607         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttribSGIX");
608         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfigSGIX");
609
610         /* The mesa libGL client library seems to forward glXQueryDrawable to the Xserver, so only
611          * enable this function when the Xserver understand GLX 1.3 or newer
612          */
613         pglXQueryDrawable = NULL;
614      } else if(strcmp("ATI", WineGLInfo.glxClientVendor) == 0) {
615         TRACE("Overriding ATI GLX capabilities!\n");
616         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
617         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
618         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
619         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
620
621         /* Use client GLX information in case of the ATI drivers. We override the
622          * capabilities over here and not somewhere else as ATI might better their
623          * life in the future. In case they release proper drivers this block of
624          * code won't be called. */
625         WineGLInfo.glxExtensions = WineGLInfo.glxClientExtensions;
626     } else {
627          ERR(" glx_version is %s and GLX_SGIX_fbconfig extension is unsupported. Expect problems.\n", WineGLInfo.glxServerVersion);
628     }
629
630     if (has_extension( WineGLInfo.glxExtensions, "GLX_MESA_copy_sub_buffer")) {
631         pglXCopySubBufferMESA = pglXGetProcAddressARB((const GLubyte *) "glXCopySubBufferMESA");
632     }
633
634     X11DRV_WineGL_LoadExtensions();
635
636     wine_tsx11_unlock();
637     return TRUE;
638
639 failed:
640     wine_dlclose(opengl_handle, NULL, 0);
641     opengl_handle = NULL;
642     return FALSE;
643 }
644
645 static int describeContext( struct wgl_context *ctx ) {
646     int tmp;
647     int ctx_vis_id;
648     TRACE(" Context %p have (vis:%p):\n", ctx, ctx->vis);
649     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_FBCONFIG_ID, &tmp);
650     TRACE(" - FBCONFIG_ID 0x%x\n", tmp);
651     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &tmp);
652     TRACE(" - VISUAL_ID 0x%x\n", tmp);
653     ctx_vis_id = tmp;
654     return ctx_vis_id;
655 }
656
657 static int ConvertAttribWGLtoGLX(const int* iWGLAttr, int* oGLXAttr, struct wgl_pbuffer* pbuf) {
658   int nAttribs = 0;
659   unsigned cur = 0; 
660   int pop;
661   int drawattrib = 0;
662   int nvfloatattrib = GLX_DONT_CARE;
663   int pixelattrib = GLX_DONT_CARE;
664
665   /* The list of WGL attributes is allowed to be NULL. We don't return here for NULL
666    * because we need to do fixups for GLX_DRAWABLE_TYPE/GLX_RENDER_TYPE/GLX_FLOAT_COMPONENTS_NV. */
667   while (iWGLAttr && 0 != iWGLAttr[cur]) {
668     TRACE("pAttr[%d] = %x\n", cur, iWGLAttr[cur]);
669
670     switch (iWGLAttr[cur]) {
671     case WGL_AUX_BUFFERS_ARB:
672       pop = iWGLAttr[++cur];
673       PUSH2(oGLXAttr, GLX_AUX_BUFFERS, pop);
674       TRACE("pAttr[%d] = GLX_AUX_BUFFERS: %d\n", cur, pop);
675       break;
676     case WGL_COLOR_BITS_ARB:
677       pop = iWGLAttr[++cur];
678       PUSH2(oGLXAttr, GLX_BUFFER_SIZE, pop);
679       TRACE("pAttr[%d] = GLX_BUFFER_SIZE: %d\n", cur, pop);
680       break;
681     case WGL_BLUE_BITS_ARB:
682       pop = iWGLAttr[++cur];
683       PUSH2(oGLXAttr, GLX_BLUE_SIZE, pop);
684       TRACE("pAttr[%d] = GLX_BLUE_SIZE: %d\n", cur, pop);
685       break;
686     case WGL_RED_BITS_ARB:
687       pop = iWGLAttr[++cur];
688       PUSH2(oGLXAttr, GLX_RED_SIZE, pop);
689       TRACE("pAttr[%d] = GLX_RED_SIZE: %d\n", cur, pop);
690       break;
691     case WGL_GREEN_BITS_ARB:
692       pop = iWGLAttr[++cur];
693       PUSH2(oGLXAttr, GLX_GREEN_SIZE, pop);
694       TRACE("pAttr[%d] = GLX_GREEN_SIZE: %d\n", cur, pop);
695       break;
696     case WGL_ALPHA_BITS_ARB:
697       pop = iWGLAttr[++cur];
698       PUSH2(oGLXAttr, GLX_ALPHA_SIZE, pop);
699       TRACE("pAttr[%d] = GLX_ALPHA_SIZE: %d\n", cur, pop);
700       break;
701     case WGL_DEPTH_BITS_ARB:
702       pop = iWGLAttr[++cur];
703       PUSH2(oGLXAttr, GLX_DEPTH_SIZE, pop);
704       TRACE("pAttr[%d] = GLX_DEPTH_SIZE: %d\n", cur, pop);
705       break;
706     case WGL_STENCIL_BITS_ARB:
707       pop = iWGLAttr[++cur];
708       PUSH2(oGLXAttr, GLX_STENCIL_SIZE, pop);
709       TRACE("pAttr[%d] = GLX_STENCIL_SIZE: %d\n", cur, pop);
710       break;
711     case WGL_DOUBLE_BUFFER_ARB:
712       pop = iWGLAttr[++cur];
713       PUSH2(oGLXAttr, GLX_DOUBLEBUFFER, pop);
714       TRACE("pAttr[%d] = GLX_DOUBLEBUFFER: %d\n", cur, pop);
715       break;
716     case WGL_STEREO_ARB:
717       pop = iWGLAttr[++cur];
718       PUSH2(oGLXAttr, GLX_STEREO, pop);
719       TRACE("pAttr[%d] = GLX_STEREO: %d\n", cur, pop);
720       break;
721
722     case WGL_PIXEL_TYPE_ARB:
723       pop = iWGLAttr[++cur];
724       TRACE("pAttr[%d] = WGL_PIXEL_TYPE_ARB: %d\n", cur, pop);
725       switch (pop) {
726       case WGL_TYPE_COLORINDEX_ARB: pixelattrib = GLX_COLOR_INDEX_BIT; break ;
727       case WGL_TYPE_RGBA_ARB: pixelattrib = GLX_RGBA_BIT; break ;
728       /* This is the same as WGL_TYPE_RGBA_FLOAT_ATI but the GLX constants differ, only the ARB GLX one is widely supported so use that */
729       case WGL_TYPE_RGBA_FLOAT_ATI: pixelattrib = GLX_RGBA_FLOAT_BIT; break ;
730       case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT: pixelattrib = GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT; break ;
731       default:
732         ERR("unexpected PixelType(%x)\n", pop); 
733         pop = 0;
734       }
735       break;
736
737     case WGL_SUPPORT_GDI_ARB:
738       /* This flag is set in a WineGLPixelFormat */
739       pop = iWGLAttr[++cur];
740       TRACE("pAttr[%d] = WGL_SUPPORT_GDI_ARB: %d\n", cur, pop);
741       break;
742
743     case WGL_DRAW_TO_BITMAP_ARB:
744       /* This flag is set in a WineGLPixelFormat */
745       pop = iWGLAttr[++cur];
746       TRACE("pAttr[%d] = WGL_DRAW_TO_BITMAP_ARB: %d\n", cur, pop);
747       break;
748
749     case WGL_DRAW_TO_WINDOW_ARB:
750       pop = iWGLAttr[++cur];
751       TRACE("pAttr[%d] = WGL_DRAW_TO_WINDOW_ARB: %d\n", cur, pop);
752       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
753       if (pop) {
754         drawattrib |= GLX_WINDOW_BIT;
755       }
756       break;
757
758     case WGL_DRAW_TO_PBUFFER_ARB:
759       pop = iWGLAttr[++cur];
760       TRACE("pAttr[%d] = WGL_DRAW_TO_PBUFFER_ARB: %d\n", cur, pop);
761       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
762       if (pop) {
763         drawattrib |= GLX_PBUFFER_BIT;
764       }
765       break;
766
767     case WGL_ACCELERATION_ARB:
768       /* This flag is set in a WineGLPixelFormat */
769       pop = iWGLAttr[++cur];
770       TRACE("pAttr[%d] = WGL_ACCELERATION_ARB: %d\n", cur, pop);
771       break;
772
773     case WGL_SUPPORT_OPENGL_ARB:
774       pop = iWGLAttr[++cur];
775       /** nothing to do, if we are here, supposing support Accelerated OpenGL */
776       TRACE("pAttr[%d] = WGL_SUPPORT_OPENGL_ARB: %d\n", cur, pop);
777       break;
778
779     case WGL_SWAP_METHOD_ARB:
780       pop = iWGLAttr[++cur];
781       /* For now we ignore this and just return SWAP_EXCHANGE */
782       TRACE("pAttr[%d] = WGL_SWAP_METHOD_ARB: %#x\n", cur, pop);
783       break;
784
785     case WGL_PBUFFER_LARGEST_ARB:
786       pop = iWGLAttr[++cur];
787       PUSH2(oGLXAttr, GLX_LARGEST_PBUFFER, pop);
788       TRACE("pAttr[%d] = GLX_LARGEST_PBUFFER: %x\n", cur, pop);
789       break;
790
791     case WGL_SAMPLE_BUFFERS_ARB:
792       pop = iWGLAttr[++cur];
793       PUSH2(oGLXAttr, GLX_SAMPLE_BUFFERS_ARB, pop);
794       TRACE("pAttr[%d] = GLX_SAMPLE_BUFFERS_ARB: %x\n", cur, pop);
795       break;
796
797     case WGL_SAMPLES_ARB:
798       pop = iWGLAttr[++cur];
799       PUSH2(oGLXAttr, GLX_SAMPLES_ARB, pop);
800       TRACE("pAttr[%d] = GLX_SAMPLES_ARB: %x\n", cur, pop);
801       break;
802
803     case WGL_TEXTURE_FORMAT_ARB:
804     case WGL_TEXTURE_TARGET_ARB:
805     case WGL_MIPMAP_TEXTURE_ARB:
806       TRACE("WGL_render_texture Attributes: %x as %x\n", iWGLAttr[cur], iWGLAttr[cur + 1]);
807       pop = iWGLAttr[++cur];
808       if (NULL == pbuf) {
809         ERR("trying to use GLX_Pbuffer Attributes without Pbuffer (was %x)\n", iWGLAttr[cur]);
810       }
811       if (!use_render_texture_emulation) {
812         if (WGL_NO_TEXTURE_ARB != pop) {
813           ERR("trying to use WGL_render_texture Attributes without support (was %x)\n", iWGLAttr[cur]);
814           return -1; /** error: don't support it */
815         } else {
816           drawattrib |= GLX_PBUFFER_BIT;
817         }
818       }
819       break ;
820     case WGL_FLOAT_COMPONENTS_NV:
821       nvfloatattrib = iWGLAttr[++cur];
822       TRACE("pAttr[%d] = WGL_FLOAT_COMPONENTS_NV: %x\n", cur, nvfloatattrib);
823       break ;
824     case WGL_BIND_TO_TEXTURE_DEPTH_NV:
825     case WGL_BIND_TO_TEXTURE_RGB_ARB:
826     case WGL_BIND_TO_TEXTURE_RGBA_ARB:
827     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV:
828     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV:
829     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV:
830     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV:
831       pop = iWGLAttr[++cur];
832       /** cannot be converted, see direct handling on 
833        *   - wglGetPixelFormatAttribivARB
834        *  TODO: wglChoosePixelFormat
835        */
836       break ;
837     case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
838       pop = iWGLAttr[++cur];
839       PUSH2(oGLXAttr, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, pop);
840       TRACE("pAttr[%d] = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT: %x\n", cur, pop);
841       break ;
842
843     case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
844       pop = iWGLAttr[++cur];
845       PUSH2(oGLXAttr, GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT, pop);
846       TRACE("pAttr[%d] = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT: %x\n", cur, pop);
847       break ;
848     default:
849       FIXME("unsupported %x WGL Attribute\n", iWGLAttr[cur]);
850       break;
851     }
852     ++cur;
853   }
854
855   /* By default glXChooseFBConfig defaults to GLX_WINDOW_BIT. wglChoosePixelFormatARB searches through
856    * all formats. Unless drawattrib is set to a non-zero value override it with GLX_DONT_CARE, so that
857    * pixmap and pbuffer formats appear as well. */
858   if (!drawattrib) drawattrib = GLX_DONT_CARE;
859   PUSH2(oGLXAttr, GLX_DRAWABLE_TYPE, drawattrib);
860   TRACE("pAttr[?] = GLX_DRAWABLE_TYPE: %#x\n", drawattrib);
861
862   /* By default glXChooseFBConfig uses GLX_RGBA_BIT as the default value. Since wglChoosePixelFormatARB
863    * searches in all formats we have to do the same. For this reason we set GLX_RENDER_TYPE to
864    * GLX_DONT_CARE unless it is overridden. */
865   PUSH2(oGLXAttr, GLX_RENDER_TYPE, pixelattrib);
866   TRACE("pAttr[?] = GLX_RENDER_TYPE: %#x\n", pixelattrib);
867
868   /* Set GLX_FLOAT_COMPONENTS_NV all the time */
869   if (has_extension(WineGLInfo.glxExtensions, "GLX_NV_float_buffer")) {
870     PUSH2(oGLXAttr, GLX_FLOAT_COMPONENTS_NV, nvfloatattrib);
871     TRACE("pAttr[?] = GLX_FLOAT_COMPONENTS_NV: %#x\n", nvfloatattrib);
872   }
873
874   return nAttribs;
875 }
876
877 static int get_render_type_from_fbconfig(Display *display, GLXFBConfig fbconfig)
878 {
879     int render_type=0, render_type_bit;
880     pglXGetFBConfigAttrib(display, fbconfig, GLX_RENDER_TYPE, &render_type_bit);
881     switch(render_type_bit)
882     {
883         case GLX_RGBA_BIT:
884             render_type = GLX_RGBA_TYPE;
885             break;
886         case GLX_COLOR_INDEX_BIT:
887             render_type = GLX_COLOR_INDEX_TYPE;
888             break;
889         case GLX_RGBA_FLOAT_BIT:
890             render_type = GLX_RGBA_FLOAT_TYPE;
891             break;
892         case GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT:
893             render_type = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
894             break;
895         default:
896             ERR("Unknown render_type: %x\n", render_type_bit);
897     }
898     return render_type;
899 }
900
901 /* Check whether a fbconfig is suitable for Windows-style bitmap rendering */
902 static BOOL check_fbconfig_bitmap_capability(Display *display, GLXFBConfig fbconfig)
903 {
904     int dbuf, value;
905     pglXGetFBConfigAttrib(display, fbconfig, GLX_DOUBLEBUFFER, &dbuf);
906     pglXGetFBConfigAttrib(gdi_display, fbconfig, GLX_DRAWABLE_TYPE, &value);
907
908     /* Windows only supports bitmap rendering on single buffered formats, further the fbconfig needs to have
909      * the GLX_PIXMAP_BIT set. */
910     return !dbuf && (value & GLX_PIXMAP_BIT);
911 }
912
913 static WineGLPixelFormat *get_formats(Display *display, int *size_ret, int *onscreen_size_ret)
914 {
915     static WineGLPixelFormat *list;
916     static int size, onscreen_size;
917
918     int fmt_id, nCfgs, i, run, bmp_formats;
919     GLXFBConfig* cfgs;
920     XVisualInfo *visinfo;
921
922     wine_tsx11_lock();
923     if (list) goto done;
924
925     cfgs = pglXGetFBConfigs(display, DefaultScreen(display), &nCfgs);
926     if (NULL == cfgs || 0 == nCfgs) {
927         if(cfgs != NULL) XFree(cfgs);
928         wine_tsx11_unlock();
929         ERR("glXChooseFBConfig returns NULL\n");
930         return NULL;
931     }
932
933     /* Bitmap rendering on Windows implies the use of the Microsoft GDI software renderer.
934      * Further most GLX drivers only offer pixmap rendering using indirect rendering (except for modern drivers which support 'AIGLX' / composite).
935      * Indirect rendering can indicate software rendering (on Nvidia it is hw accelerated)
936      * Since bitmap rendering implies the use of software rendering we can safely use indirect rendering for bitmaps.
937      *
938      * Below we count the number of formats which are suitable for bitmap rendering. Windows restricts bitmap rendering to single buffered formats.
939      */
940     for(i=0, bmp_formats=0; i<nCfgs; i++)
941     {
942         if(check_fbconfig_bitmap_capability(display, cfgs[i]))
943             bmp_formats++;
944     }
945     TRACE("Found %d bitmap capable fbconfigs\n", bmp_formats);
946
947     list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (nCfgs + bmp_formats)*sizeof(WineGLPixelFormat));
948
949     /* Fill the pixel format list. Put onscreen formats at the top and offscreen ones at the bottom.
950      * Do this as GLX doesn't guarantee that the list is sorted */
951     for(run=0; run < 2; run++)
952     {
953         for(i=0; i<nCfgs; i++) {
954             pglXGetFBConfigAttrib(display, cfgs[i], GLX_FBCONFIG_ID, &fmt_id);
955             visinfo = pglXGetVisualFromFBConfig(display, cfgs[i]);
956
957             /* The first run we only add onscreen formats (ones which have an associated X Visual).
958              * The second run we only set offscreen formats. */
959             if(!run && visinfo)
960             {
961                 /* We implement child window rendering using offscreen buffers (using composite or an XPixmap).
962                  * The contents is copied to the destination using XCopyArea. For the copying to work
963                  * the depth of the source and destination window should be the same. In general this should
964                  * not be a problem for OpenGL as drivers only advertise formats with a similar depth (or no depth).
965                  * As of the introduction of composition managers at least Nvidia now also offers ARGB visuals
966                  * with a depth of 32 in addition to the default 24 bit. In order to prevent BadMatch errors we only
967                  * list formats with the same depth. */
968                 if(visinfo->depth != screen_depth)
969                 {
970                     XFree(visinfo);
971                     continue;
972                 }
973
974                 TRACE("Found onscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
975                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
976                 list[size].fbconfig = cfgs[i];
977                 list[size].fmt_id = fmt_id;
978                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
979                 list[size].offscreenOnly = FALSE;
980                 list[size].dwFlags = 0;
981                 size++;
982                 onscreen_size++;
983
984                 /* Clone a format if it is bitmap capable for indirect rendering to bitmaps */
985                 if(check_fbconfig_bitmap_capability(display, cfgs[i]))
986                 {
987                     TRACE("Found bitmap capable format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
988                     list[size].iPixelFormat = size+1; /* The index starts at 1 */
989                     list[size].fbconfig = cfgs[i];
990                     list[size].fmt_id = fmt_id;
991                     list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
992                     list[size].offscreenOnly = FALSE;
993                     list[size].dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI | PFD_GENERIC_FORMAT;
994                     size++;
995                     onscreen_size++;
996                 }
997             } else if(run && !visinfo) {
998                 int window_drawable=0;
999                 pglXGetFBConfigAttrib(gdi_display, cfgs[i], GLX_DRAWABLE_TYPE, &window_drawable);
1000
1001                 /* Recent Nvidia drivers and DRI drivers offer window drawable formats without a visual.
1002                  * This are formats like 16-bit rgb on a 24-bit desktop. In order to support these formats
1003                  * onscreen we would have to use glXCreateWindow instead of XCreateWindow. Further it will
1004                  * likely make our child window opengl rendering more complicated since likely you can't use
1005                  * XCopyArea on a GLX Window.
1006                  * For now ignore fbconfigs which are window drawable but lack a visual. */
1007                 if(window_drawable & GLX_WINDOW_BIT)
1008                 {
1009                     TRACE("Skipping FBCONFIG_ID 0x%x as an offscreen format because it is window_drawable\n", fmt_id);
1010                     continue;
1011                 }
1012
1013                 TRACE("Found offscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1014                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
1015                 list[size].fbconfig = cfgs[i];
1016                 list[size].fmt_id = fmt_id;
1017                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1018                 list[size].offscreenOnly = TRUE;
1019                 list[size].dwFlags = 0;
1020                 size++;
1021             }
1022
1023             if (visinfo) XFree(visinfo);
1024         }
1025     }
1026
1027     XFree(cfgs);
1028
1029 done:
1030     if (size_ret) *size_ret = size;
1031     if (onscreen_size_ret) *onscreen_size_ret = onscreen_size;
1032     wine_tsx11_unlock();
1033     return list;
1034 }
1035
1036 /* GLX can advertise dozens of different pixelformats including offscreen and onscreen ones.
1037  * In our WGL implementation we only support a subset of these formats namely the format of
1038  * Wine's main visual and offscreen formats (if they are available).
1039  * This function converts a WGL format to its corresponding GLX one. It returns a WineGLPixelFormat
1040  * and it returns the number of supported WGL formats in fmt_count.
1041  */
1042 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count)
1043 {
1044     WineGLPixelFormat *list, *res = NULL;
1045     int size, onscreen_size;
1046
1047     if (!(list = get_formats(display, &size, &onscreen_size ))) return NULL;
1048
1049     /* Check if the pixelformat is valid. Note that it is legal to pass an invalid
1050      * iPixelFormat in case of probing the number of pixelformats.
1051      */
1052     if((iPixelFormat > 0) && (iPixelFormat <= size) &&
1053        (!list[iPixelFormat-1].offscreenOnly || AllowOffscreen)) {
1054         res = &list[iPixelFormat-1];
1055         TRACE("Returning fmt_id=%#x for iPixelFormat=%d\n", res->fmt_id, iPixelFormat);
1056     }
1057
1058     if(AllowOffscreen)
1059         *fmt_count = size;
1060     else
1061         *fmt_count = onscreen_size;
1062
1063     TRACE("Number of returned pixelformats=%d\n", *fmt_count);
1064
1065     return res;
1066 }
1067
1068 /* Search our internal pixelformat list for the WGL format corresponding to the given fbconfig */
1069 static WineGLPixelFormat* ConvertPixelFormatGLXtoWGL(Display *display, int fmt_id, DWORD dwFlags)
1070 {
1071     WineGLPixelFormat *list;
1072     int i, size;
1073
1074     if (!(list = get_formats(display, &size, NULL ))) return NULL;
1075
1076     for(i=0; i<size; i++) {
1077         /* A GLX format can appear multiple times in the pixel format list due to fake formats for bitmap rendering.
1078          * Fake formats might get selected when the user passes the proper flags using the dwFlags parameter. */
1079         if( (list[i].fmt_id == fmt_id) && ((list[i].dwFlags & dwFlags) == dwFlags) ) {
1080             TRACE("Returning iPixelFormat %d for fmt_id 0x%x\n", list[i].iPixelFormat, fmt_id);
1081             return &list[i];
1082         }
1083     }
1084     TRACE("No compatible format found for fmt_id 0x%x\n", fmt_id);
1085     return NULL;
1086 }
1087
1088 static int pixelformat_from_fbconfig_id(XID fbconfig_id)
1089 {
1090     WineGLPixelFormat *fmt;
1091
1092     if (!fbconfig_id) return 0;
1093
1094     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
1095     if(fmt)
1096         return fmt->iPixelFormat;
1097     /* This will happen on hwnds without a pixel format set; it's ok */
1098     return 0;
1099 }
1100
1101
1102 /* Mark any allocated context using the glx drawable 'old' to use 'new' */
1103 void mark_drawable_dirty(Drawable old, Drawable new)
1104 {
1105     struct wgl_context *ctx;
1106     LIST_FOR_EACH_ENTRY( ctx, &context_list, struct wgl_context, entry )
1107     {
1108         if (old == ctx->drawables[0]) {
1109             ctx->drawables[0] = new;
1110             ctx->refresh_drawables = TRUE;
1111         }
1112         if (old == ctx->drawables[1]) {
1113             ctx->drawables[1] = new;
1114             ctx->refresh_drawables = TRUE;
1115         }
1116     }
1117 }
1118
1119 /* Given the current context, make sure its drawable is sync'd */
1120 static inline void sync_context(struct wgl_context *context)
1121 {
1122     if(context && context->refresh_drawables) {
1123         if (glxRequireVersion(3))
1124             pglXMakeContextCurrent(gdi_display, context->drawables[0],
1125                                    context->drawables[1], context->ctx);
1126         else
1127             pglXMakeCurrent(gdi_display, context->drawables[0], context->ctx);
1128         context->refresh_drawables = FALSE;
1129     }
1130 }
1131
1132
1133 static GLXContext create_glxcontext(Display *display, struct wgl_context *context, GLXContext shareList)
1134 {
1135     GLXContext ctx;
1136
1137     /* We use indirect rendering for rendering to bitmaps. See get_formats for a comment about this. */
1138     BOOL indirect = (context->fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? FALSE : TRUE;
1139
1140     if(context->gl3_context)
1141     {
1142         if(context->numAttribs)
1143             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, context->attribList);
1144         else
1145             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, NULL);
1146     }
1147     else if(context->vis)
1148         ctx = pglXCreateContext(gdi_display, context->vis, shareList, indirect);
1149     else /* Create a GLX Context for a pbuffer */
1150         ctx = pglXCreateNewContext(gdi_display, context->fmt->fbconfig, context->fmt->render_type, shareList, TRUE);
1151
1152     return ctx;
1153 }
1154
1155
1156 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
1157 {
1158     return pglXCreateGLXPixmap(display, vis, parent);
1159 }
1160
1161
1162 /**
1163  * glxdrv_DescribePixelFormat
1164  *
1165  * Get the pixel-format descriptor associated to the given id
1166  */
1167 static int glxdrv_DescribePixelFormat(PHYSDEV dev, int iPixelFormat,
1168                                       UINT nBytes, PIXELFORMATDESCRIPTOR *ppfd)
1169 {
1170   /*XVisualInfo *vis;*/
1171   int value;
1172   int rb,gb,bb,ab;
1173   WineGLPixelFormat *fmt;
1174   int ret = 0;
1175   int fmt_count = 0;
1176
1177   if (!has_opengl()) return 0;
1178
1179   TRACE("(%p,%d,%d,%p)\n", dev->hdc, iPixelFormat, nBytes, ppfd);
1180
1181   /* Look for the iPixelFormat in our list of supported formats. If it is supported we get the index in the FBConfig table and the number of supported formats back */
1182   fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &fmt_count);
1183   if (ppfd == NULL) {
1184       /* The application is only querying the number of pixelformats */
1185       return fmt_count;
1186   } else if(fmt == NULL) {
1187       WARN("unexpected iPixelFormat(%d): not >=1 and <=nFormats(%d), returning NULL!\n", iPixelFormat, fmt_count);
1188       return 0;
1189   }
1190
1191   if (nBytes < sizeof(PIXELFORMATDESCRIPTOR)) {
1192     ERR("Wrong structure size !\n");
1193     /* Should set error */
1194     return 0;
1195   }
1196
1197   ret = fmt_count;
1198
1199   memset(ppfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
1200   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
1201   ppfd->nVersion = 1;
1202
1203   /* These flags are always the same... */
1204   ppfd->dwFlags = PFD_SUPPORT_OPENGL;
1205   /* Now the flags extracted from the Visual */
1206
1207   wine_tsx11_lock();
1208
1209   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1210   if(value & GLX_WINDOW_BIT)
1211       ppfd->dwFlags |= PFD_DRAW_TO_WINDOW;
1212
1213   /* On Windows bitmap rendering is only offered using the GDI Software renderer. We reserve some formats (see get_formats for more info)
1214    * for bitmap rendering since we require indirect rendering for this. Further pixel format logs of a GeforceFX, Geforce8800GT, Radeon HD3400 and a
1215    * Radeon 9000 indicated that all bitmap formats have PFD_SUPPORT_GDI. Except for 2 formats on the Radeon 9000 none of the hw accelerated formats
1216    * offered the GDI bit either. */
1217   ppfd->dwFlags |= fmt->dwFlags & (PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI);
1218
1219   /* PFD_GENERIC_FORMAT - gdi software rendering
1220    * PFD_GENERIC_ACCELERATED - some parts are accelerated by a display driver (MCD e.g. 3dfx minigl)
1221    * none set - full hardware accelerated by a ICD
1222    *
1223    * We only set PFD_GENERIC_FORMAT on bitmap formats (see get_formats) as that's what ATI and Nvidia Windows drivers do  */
1224   ppfd->dwFlags |= fmt->dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED);
1225
1226   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1227   if (value) {
1228       ppfd->dwFlags |= PFD_DOUBLEBUFFER;
1229       ppfd->dwFlags &= ~PFD_SUPPORT_GDI;
1230   }
1231   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value); if (value) ppfd->dwFlags |= PFD_STEREO;
1232
1233   /* Pixel type */
1234   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1235   if (value & GLX_RGBA_BIT)
1236     ppfd->iPixelType = PFD_TYPE_RGBA;
1237   else
1238     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
1239
1240   /* Color bits */
1241   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &value);
1242   ppfd->cColorBits = value;
1243
1244   /* Red, green, blue and alpha bits / shifts */
1245   if (ppfd->iPixelType == PFD_TYPE_RGBA) {
1246     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RED_SIZE, &rb);
1247     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_GREEN_SIZE, &gb);
1248     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BLUE_SIZE, &bb);
1249     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &ab);
1250
1251     ppfd->cRedBits = rb;
1252     ppfd->cRedShift = gb + bb + ab;
1253     ppfd->cBlueBits = bb;
1254     ppfd->cBlueShift = ab;
1255     ppfd->cGreenBits = gb;
1256     ppfd->cGreenShift = bb + ab;
1257     ppfd->cAlphaBits = ab;
1258     ppfd->cAlphaShift = 0;
1259   } else {
1260     ppfd->cRedBits = 0;
1261     ppfd->cRedShift = 0;
1262     ppfd->cBlueBits = 0;
1263     ppfd->cBlueShift = 0;
1264     ppfd->cGreenBits = 0;
1265     ppfd->cGreenShift = 0;
1266     ppfd->cAlphaBits = 0;
1267     ppfd->cAlphaShift = 0;
1268   }
1269
1270   /* Accum RGBA bits */
1271   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &rb);
1272   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &gb);
1273   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &bb);
1274   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &ab);
1275
1276   ppfd->cAccumBits = rb+gb+bb+ab;
1277   ppfd->cAccumRedBits = rb;
1278   ppfd->cAccumGreenBits = gb;
1279   ppfd->cAccumBlueBits = bb;
1280   ppfd->cAccumAlphaBits = ab;
1281
1282   /* Aux bits */
1283   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &value);
1284   ppfd->cAuxBuffers = value;
1285
1286   /* Depth bits */
1287   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &value);
1288   ppfd->cDepthBits = value;
1289
1290   /* stencil bits */
1291   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &value);
1292   ppfd->cStencilBits = value;
1293
1294   wine_tsx11_unlock();
1295
1296   ppfd->iLayerType = PFD_MAIN_PLANE;
1297
1298   if (TRACE_ON(wgl)) {
1299     dump_PIXELFORMATDESCRIPTOR(ppfd);
1300   }
1301
1302   return ret;
1303 }
1304
1305 /***********************************************************************
1306  *              glxdrv_wglGetPixelFormat
1307  */
1308 static int glxdrv_wglGetPixelFormat( HDC hdc )
1309 {
1310     struct x11drv_escape_get_drawable escape;
1311     WineGLPixelFormat *fmt;
1312     int tmp;
1313
1314     TRACE( "(%p)\n", hdc );
1315
1316     escape.code = X11DRV_GET_DRAWABLE;
1317     if (!ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape.code), (LPCSTR)&escape.code,
1318                     sizeof(escape), (LPSTR)&escape ))
1319         return 0;
1320
1321     if (!escape.pixel_format) return 0;  /* not set yet */
1322
1323     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, escape.pixel_format, TRUE, &tmp);
1324     if (!fmt)
1325     {
1326         ERR("Unable to find a WineGLPixelFormat for iPixelFormat=%d\n", escape.pixel_format);
1327         return 0;
1328     }
1329     if (fmt->offscreenOnly)
1330     {
1331         /* Offscreen formats can't be used with traditional WGL calls.
1332          * As has been verified on Windows GetPixelFormat doesn't fail but returns iPixelFormat=1. */
1333         TRACE("Returning iPixelFormat=1 for offscreen format: %d\n", fmt->iPixelFormat);
1334         return 1;
1335     }
1336     TRACE("(%p): returns %d\n", hdc, escape.pixel_format);
1337     return escape.pixel_format;
1338 }
1339
1340 /***********************************************************************
1341  *              glxdrv_SetPixelFormat
1342  */
1343 static BOOL glxdrv_SetPixelFormat(PHYSDEV dev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
1344 {
1345     struct glx_physdev *physdev = get_glxdrv_dev( dev );
1346     WineGLPixelFormat *fmt;
1347     int value;
1348     HWND hwnd;
1349
1350     TRACE("(%p,%d,%p)\n", dev->hdc, iPixelFormat, ppfd);
1351
1352     if (!has_opengl()) return FALSE;
1353
1354     if(physdev->pixel_format)  /* cannot change it if already set */
1355         return (physdev->pixel_format == iPixelFormat);
1356
1357     /* SetPixelFormat is not allowed on the X root_window e.g. GetDC(0) */
1358     if(physdev->x11dev->drawable == root_window)
1359     {
1360         ERR("Invalid operation on root_window\n");
1361         return FALSE;
1362     }
1363
1364     /* Check if iPixelFormat is in our list of supported formats to see if it is supported. */
1365     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &value);
1366     if(!fmt) {
1367         ERR("Invalid iPixelFormat: %d\n", iPixelFormat);
1368         return FALSE;
1369     }
1370
1371     wine_tsx11_lock();
1372     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1373     wine_tsx11_unlock();
1374
1375     hwnd = WindowFromDC(physdev->dev.hdc);
1376     if(hwnd) {
1377         if(!(value&GLX_WINDOW_BIT)) {
1378             WARN("Pixel format %d is not compatible for window rendering\n", iPixelFormat);
1379             return FALSE;
1380         }
1381
1382         if(!SendMessageW(hwnd, WM_X11DRV_SET_WIN_FORMAT, fmt->fmt_id, 0)) {
1383             ERR("Couldn't set format of the window, returning failure\n");
1384             return FALSE;
1385         }
1386         /* physDev->current_pf will be set by the DCE update */
1387     }
1388     else if (GetObjectType( physdev->dev.hdc ) == OBJ_MEMDC) {
1389         if(!(value&GLX_PIXMAP_BIT)) {
1390             WARN("Pixel format %d is not compatible for bitmap rendering\n", iPixelFormat);
1391             return FALSE;
1392         }
1393
1394         physdev->pixel_format = iPixelFormat;
1395         physdev->type = DC_GL_BITMAP;
1396     }
1397     else {
1398         FIXME("called on a non-window, non-bitmap object?\n");
1399     }
1400
1401     if (TRACE_ON(wgl)) {
1402         int gl_test = 0;
1403
1404         wine_tsx11_lock();
1405         gl_test = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_FBCONFIG_ID, &value);
1406         if (gl_test) {
1407            ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
1408         } else {
1409             TRACE(" FBConfig have :\n");
1410             TRACE(" - FBCONFIG_ID   0x%x\n", value);
1411             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &value);
1412             TRACE(" - VISUAL_ID     0x%x\n", value);
1413             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1414             TRACE(" - DRAWABLE_TYPE 0x%x\n", value);
1415         }
1416         wine_tsx11_unlock();
1417     }
1418     return TRUE;
1419 }
1420
1421 /***********************************************************************
1422  *              glxdrv_wglCopyContext
1423  */
1424 static BOOL glxdrv_wglCopyContext(struct wgl_context *src, struct wgl_context *dst, UINT mask)
1425 {
1426     TRACE("%p -> %p mask %#x\n", src, dst, mask);
1427
1428     wine_tsx11_lock();
1429     pglXCopyContext(gdi_display, src->ctx, dst->ctx, mask);
1430     wine_tsx11_unlock();
1431
1432     /* As opposed to wglCopyContext, glXCopyContext doesn't return anything, so hopefully we passed */
1433     return TRUE;
1434 }
1435
1436 /***********************************************************************
1437  *              glxdrv_wglCreateContext
1438  */
1439 static struct wgl_context *glxdrv_wglCreateContext( HDC hdc )
1440 {
1441     struct x11drv_escape_get_drawable escape;
1442     struct wgl_context *ret;
1443     WineGLPixelFormat *fmt;
1444     int fmt_count = 0;
1445
1446     TRACE( "(%p)\n", hdc );
1447
1448     escape.code = X11DRV_GET_DRAWABLE;
1449     if (!ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape.code), (LPCSTR)&escape.code,
1450                     sizeof(escape), (LPSTR)&escape ))
1451         return 0;
1452
1453     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, escape.pixel_format, TRUE /* Offscreen */, &fmt_count);
1454     /* We can render using the iPixelFormat (1) of Wine's Main visual AND using some offscreen formats.
1455      * Note that standard WGL-calls don't recognize offscreen-only formats. For that reason pbuffers
1456      * use a sort of 'proxy' HDC (wglGetPbufferDCARB).
1457      * If this fails something is very wrong on the system. */
1458     if(!fmt) {
1459         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", escape.pixel_format);
1460         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
1461         return NULL;
1462     }
1463
1464     if (!(ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret)))) return 0;
1465
1466     ret->hdc = hdc;
1467     ret->fmt = fmt;
1468     ret->has_been_current = FALSE;
1469     ret->sharing = FALSE;
1470
1471     wine_tsx11_lock();
1472     ret->vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
1473     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
1474     list_add_head( &context_list, &ret->entry );
1475     wine_tsx11_unlock();
1476
1477     TRACE(" creating context %p (GL context creation delayed)\n", ret);
1478     return ret;
1479 }
1480
1481 /***********************************************************************
1482  *              glxdrv_wglDeleteContext
1483  */
1484 static void glxdrv_wglDeleteContext(struct wgl_context *ctx)
1485 {
1486     TRACE("(%p)\n", ctx);
1487
1488     wine_tsx11_lock();
1489     list_remove( &ctx->entry );
1490     if (ctx->ctx) pglXDestroyContext( gdi_display, ctx->ctx );
1491     if (ctx->glxpixmap) pglXDestroyGLXPixmap( gdi_display, ctx->glxpixmap );
1492     if (ctx->pixmap) XFreePixmap( gdi_display, ctx->pixmap );
1493     if (ctx->vis) XFree( ctx->vis );
1494     wine_tsx11_unlock();
1495
1496     HeapFree( GetProcessHeap(), 0, ctx );
1497 }
1498
1499 /***********************************************************************
1500  *              glxdrv_wglGetProcAddress
1501  */
1502 static PROC glxdrv_wglGetProcAddress(LPCSTR lpszProc)
1503 {
1504     if (!strncmp(lpszProc, "wgl", 3)) return NULL;
1505     return pglXGetProcAddressARB((const GLubyte*)lpszProc);
1506 }
1507
1508 static GLXPixmap get_context_pixmap( HDC hdc, struct wgl_context *ctx )
1509 {
1510     if (!ctx->pixmap)
1511     {
1512         BITMAP bmp;
1513
1514         GetObjectW( GetCurrentObject( hdc, OBJ_BITMAP ), sizeof(bmp), &bmp );
1515
1516         wine_tsx11_lock();
1517         ctx->pixmap = XCreatePixmap( gdi_display, root_window,
1518                                      bmp.bmWidth, bmp.bmHeight, ctx->vis->depth );
1519         ctx->glxpixmap = pglXCreateGLXPixmap( gdi_display, ctx->vis, ctx->pixmap );
1520         wine_tsx11_unlock();
1521         ctx->pixmap_size.cx = bmp.bmWidth;
1522         ctx->pixmap_size.cy = bmp.bmHeight;
1523     }
1524     return ctx->glxpixmap;
1525 }
1526
1527 /***********************************************************************
1528  *              glxdrv_wglMakeCurrent
1529  */
1530 static BOOL glxdrv_wglMakeCurrent(HDC hdc, struct wgl_context *ctx)
1531 {
1532     BOOL ret;
1533     struct x11drv_escape_get_drawable escape;
1534
1535     TRACE("(%p,%p)\n", hdc, ctx);
1536
1537     if (!ctx)
1538     {
1539         wine_tsx11_lock();
1540         ret = pglXMakeCurrent(gdi_display, None, NULL);
1541         wine_tsx11_unlock();
1542         NtCurrentTeb()->glContext = NULL;
1543         return TRUE;
1544     }
1545
1546     escape.code = X11DRV_GET_DRAWABLE;
1547     if (!ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape.code), (LPCSTR)&escape.code,
1548                     sizeof(escape), (LPSTR)&escape ))
1549         return FALSE;
1550
1551     if (!escape.pixel_format)
1552     {
1553         WARN("Trying to use an invalid drawable\n");
1554         SetLastError(ERROR_INVALID_HANDLE);
1555         return FALSE;
1556     }
1557     if (ctx->fmt->iPixelFormat != escape.pixel_format)
1558     {
1559         WARN( "mismatched pixel format hdc %p %u ctx %p %u\n",
1560               hdc, escape.pixel_format, ctx, ctx->fmt->iPixelFormat );
1561         SetLastError( ERROR_INVALID_PIXEL_FORMAT );
1562         return FALSE;
1563     }
1564     else
1565     {
1566         if (escape.gl_type == DC_GL_BITMAP) escape.gl_drawable = get_context_pixmap( hdc, ctx );
1567
1568         wine_tsx11_lock();
1569
1570         if (TRACE_ON(wgl)) {
1571             int vis_id;
1572             pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &vis_id);
1573             describeContext(ctx);
1574             TRACE("hdc %p drawable %lx fmt %u vis %x ctx %p\n", hdc,
1575                   escape.gl_drawable, escape.pixel_format, vis_id, ctx->ctx);
1576         }
1577
1578         ret = pglXMakeCurrent(gdi_display, escape.gl_drawable, ctx->ctx);
1579
1580         if (ret)
1581         {
1582             NtCurrentTeb()->glContext = ctx;
1583
1584             ctx->has_been_current = TRUE;
1585             ctx->hdc = hdc;
1586             ctx->drawables[0] = escape.gl_drawable;
1587             ctx->drawables[1] = escape.gl_drawable;
1588             ctx->refresh_drawables = FALSE;
1589
1590             if (escape.gl_type == DC_GL_BITMAP) opengl_funcs.gl.p_glDrawBuffer(GL_FRONT_LEFT);
1591         }
1592         else
1593             SetLastError(ERROR_INVALID_HANDLE);
1594         wine_tsx11_unlock();
1595     }
1596     TRACE(" returning %s\n", (ret ? "True" : "False"));
1597     return ret;
1598 }
1599
1600 /***********************************************************************
1601  *              X11DRV_wglMakeContextCurrentARB
1602  */
1603 static BOOL X11DRV_wglMakeContextCurrentARB( HDC draw_hdc, HDC read_hdc, struct wgl_context *ctx )
1604 {
1605     struct x11drv_escape_get_drawable escape_draw, escape_read;
1606     BOOL ret;
1607
1608     TRACE("(%p,%p,%p)\n", draw_hdc, read_hdc, ctx);
1609
1610     if (!ctx)
1611     {
1612         wine_tsx11_lock();
1613         ret = pglXMakeCurrent(gdi_display, None, NULL);
1614         wine_tsx11_unlock();
1615         NtCurrentTeb()->glContext = NULL;
1616         return TRUE;
1617     }
1618
1619     escape_draw.code = X11DRV_GET_DRAWABLE;
1620     if (!ExtEscape( draw_hdc, X11DRV_ESCAPE, sizeof(escape_draw.code), (LPCSTR)&escape_draw.code,
1621                     sizeof(escape_draw), (LPSTR)&escape_draw ))
1622         return FALSE;
1623
1624     escape_read.code = X11DRV_GET_DRAWABLE;
1625     if (!ExtEscape( read_hdc, X11DRV_ESCAPE, sizeof(escape_read.code), (LPCSTR)&escape_read.code,
1626                     sizeof(escape_read), (LPSTR)&escape_read ))
1627         return FALSE;
1628
1629     if (!escape_draw.pixel_format)
1630     {
1631         WARN("Trying to use an invalid drawable\n");
1632         SetLastError(ERROR_INVALID_HANDLE);
1633         return FALSE;
1634     }
1635     else
1636     {
1637         if (!pglXMakeContextCurrent) return FALSE;
1638
1639         if (escape_draw.gl_type == DC_GL_BITMAP) escape_draw.gl_drawable = get_context_pixmap( draw_hdc, ctx );
1640         if (escape_read.gl_type == DC_GL_BITMAP) escape_read.gl_drawable = get_context_pixmap( read_hdc, ctx );
1641
1642         wine_tsx11_lock();
1643         ret = pglXMakeContextCurrent(gdi_display, escape_draw.gl_drawable, escape_read.gl_drawable, ctx->ctx);
1644         if (ret)
1645         {
1646             ctx->has_been_current = TRUE;
1647             ctx->hdc = draw_hdc;
1648             ctx->drawables[0] = escape_draw.gl_drawable;
1649             ctx->drawables[1] = escape_read.gl_drawable;
1650             ctx->refresh_drawables = FALSE;
1651             NtCurrentTeb()->glContext = ctx;
1652         }
1653         else
1654             SetLastError(ERROR_INVALID_HANDLE);
1655         wine_tsx11_unlock();
1656     }
1657
1658     TRACE(" returning %s\n", (ret ? "True" : "False"));
1659     return ret;
1660 }
1661
1662 /***********************************************************************
1663  *              glxdrv_wglShareLists
1664  */
1665 static BOOL glxdrv_wglShareLists(struct wgl_context *org, struct wgl_context *dest)
1666 {
1667     TRACE("(%p, %p)\n", org, dest);
1668
1669     /* Sharing of display lists works differently in GLX and WGL. In case of GLX it is done
1670      * at context creation time but in case of WGL it is done using wglShareLists.
1671      * In the past we tried to emulate wglShareLists by delaying GLX context creation until
1672      * either a wglMakeCurrent or wglShareLists. This worked fine for most apps but it causes
1673      * issues for OpenGL 3 because there wglCreateContextAttribsARB can fail in a lot of cases,
1674      * so there delaying context creation doesn't work.
1675      *
1676      * The new approach is to create a GLX context in wglCreateContext / wglCreateContextAttribsARB
1677      * and when a program requests sharing we recreate the destination context if it hasn't been made
1678      * current or when it hasn't shared display lists before.
1679      */
1680
1681     if((org->has_been_current && dest->has_been_current) || dest->has_been_current)
1682     {
1683         ERR("Could not share display lists, one of the contexts has been current already !\n");
1684         return FALSE;
1685     }
1686     else if(dest->sharing)
1687     {
1688         ERR("Could not share display lists because hglrc2 has already shared lists before\n");
1689         return FALSE;
1690     }
1691     else
1692     {
1693         if((GetObjectType(org->hdc) == OBJ_MEMDC) ^ (GetObjectType(dest->hdc) == OBJ_MEMDC))
1694         {
1695             WARN("Attempting to share a context between a direct and indirect rendering context, expect issues!\n");
1696         }
1697
1698         wine_tsx11_lock();
1699         describeContext(org);
1700         describeContext(dest);
1701
1702         /* Re-create the GLX context and share display lists */
1703         pglXDestroyContext(gdi_display, dest->ctx);
1704         dest->ctx = create_glxcontext(gdi_display, dest, org->ctx);
1705         wine_tsx11_unlock();
1706         TRACE(" re-created an OpenGL context (%p) for Wine context %p sharing lists with OpenGL ctx %p\n", dest->ctx, dest, org->ctx);
1707
1708         org->sharing = TRUE;
1709         dest->sharing = TRUE;
1710         return TRUE;
1711     }
1712     return FALSE;
1713 }
1714
1715 static void flush_pixmap( struct wgl_context *ctx )
1716 {
1717     char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1718     BITMAPINFO *info = (BITMAPINFO *)buffer;
1719     struct gdi_image_bits bits;
1720
1721     if (!get_pixmap_image( ctx->pixmap, ctx->pixmap_size.cx, ctx->pixmap_size.cy, ctx->vis, info, &bits ))
1722     {
1723         HBITMAP bitmap = GetCurrentObject( ctx->hdc, OBJ_BITMAP );
1724         SetDIBits( 0, bitmap, 0, ctx->pixmap_size.cy, bits.ptr, info, DIB_RGB_COLORS );
1725         if (bits.free) bits.free( &bits );
1726     }
1727 }
1728
1729 static void flush_gl_drawable( struct glx_physdev *physdev )
1730 {
1731     RECT rect;
1732     int w = physdev->x11dev->dc_rect.right - physdev->x11dev->dc_rect.left;
1733     int h = physdev->x11dev->dc_rect.bottom - physdev->x11dev->dc_rect.top;
1734     Drawable src = physdev->drawable;
1735
1736     if (w <= 0 || h <= 0) return;
1737
1738     switch (physdev->type)
1739     {
1740     case DC_GL_PIXMAP_WIN:
1741         src = physdev->pixmap;
1742         /* fall through */
1743     case DC_GL_CHILD_WIN:
1744         /* The GL drawable may be lagged behind if we don't flush first, so
1745          * flush the display make sure we copy up-to-date data */
1746         wine_tsx11_lock();
1747         XFlush(gdi_display);
1748         XSetFunction(gdi_display, physdev->x11dev->gc, GXcopy);
1749         XCopyArea(gdi_display, src, physdev->x11dev->drawable, physdev->x11dev->gc, 0, 0, w, h,
1750                   physdev->x11dev->dc_rect.left, physdev->x11dev->dc_rect.top);
1751         wine_tsx11_unlock();
1752         SetRect( &rect, 0, 0, w, h );
1753         add_device_bounds( physdev->x11dev, &rect );
1754     default:
1755         break;
1756     }
1757 }
1758
1759
1760 static void wglFinish(void)
1761 {
1762     struct wgl_context *ctx = NtCurrentTeb()->glContext;
1763     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
1764
1765     wine_tsx11_lock();
1766     sync_context(ctx);
1767     pglFinish();
1768     wine_tsx11_unlock();
1769     if (ctx)
1770     {
1771         if (ctx->pixmap) flush_pixmap( ctx );
1772         else ExtEscape( ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
1773     }
1774 }
1775
1776 static void wglFlush(void)
1777 {
1778     struct wgl_context *ctx = NtCurrentTeb()->glContext;
1779     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
1780
1781     wine_tsx11_lock();
1782     sync_context(ctx);
1783     pglFlush();
1784     wine_tsx11_unlock();
1785     if (ctx)
1786     {
1787         if (ctx->pixmap) flush_pixmap( ctx );
1788         else ExtEscape( ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
1789     }
1790 }
1791
1792 /***********************************************************************
1793  *              X11DRV_wglCreateContextAttribsARB
1794  */
1795 static struct wgl_context *X11DRV_wglCreateContextAttribsARB( HDC hdc, struct wgl_context *hShareContext,
1796                                                               const int* attribList )
1797 {
1798     struct x11drv_escape_get_drawable escape;
1799     struct wgl_context *ret;
1800     WineGLPixelFormat *fmt;
1801     int fmt_count = 0;
1802
1803     TRACE("(%p %p %p)\n", hdc, hShareContext, attribList);
1804
1805     escape.code = X11DRV_GET_DRAWABLE;
1806     if (!ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape.code), (LPCSTR)&escape.code,
1807                     sizeof(escape), (LPSTR)&escape ))
1808         return 0;
1809
1810     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, escape.pixel_format, TRUE /* Offscreen */, &fmt_count);
1811     /* wglCreateContextAttribsARB supports ALL pixel formats, so also offscreen ones.
1812      * If this fails something is very wrong on the system. */
1813     if(!fmt)
1814     {
1815         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", escape.pixel_format);
1816         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
1817         return NULL;
1818     }
1819
1820     if (!(ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret)))) return 0;
1821
1822     ret->hdc = hdc;
1823     ret->fmt = fmt;
1824     ret->vis = NULL; /* glXCreateContextAttribsARB requires a fbconfig instead of a visual */
1825     ret->gl3_context = TRUE;
1826
1827     ret->numAttribs = 0;
1828     if(attribList)
1829     {
1830         int *pAttribList = (int*)attribList;
1831         int *pContextAttribList = &ret->attribList[0];
1832         /* attribList consists of pairs {token, value] terminated with 0 */
1833         while(pAttribList[0] != 0)
1834         {
1835             TRACE("%#x %#x\n", pAttribList[0], pAttribList[1]);
1836             switch(pAttribList[0])
1837             {
1838                 case WGL_CONTEXT_MAJOR_VERSION_ARB:
1839                     pContextAttribList[0] = GLX_CONTEXT_MAJOR_VERSION_ARB;
1840                     pContextAttribList[1] = pAttribList[1];
1841                     break;
1842                 case WGL_CONTEXT_MINOR_VERSION_ARB:
1843                     pContextAttribList[0] = GLX_CONTEXT_MINOR_VERSION_ARB;
1844                     pContextAttribList[1] = pAttribList[1];
1845                     break;
1846                 case WGL_CONTEXT_LAYER_PLANE_ARB:
1847                     break;
1848                 case WGL_CONTEXT_FLAGS_ARB:
1849                     pContextAttribList[0] = GLX_CONTEXT_FLAGS_ARB;
1850                     pContextAttribList[1] = pAttribList[1];
1851                     break;
1852                 case WGL_CONTEXT_PROFILE_MASK_ARB:
1853                     pContextAttribList[0] = GLX_CONTEXT_PROFILE_MASK_ARB;
1854                     pContextAttribList[1] = pAttribList[1];
1855                     break;
1856                 default:
1857                     ERR("Unhandled attribList pair: %#x %#x\n", pAttribList[0], pAttribList[1]);
1858             }
1859
1860             ret->numAttribs++;
1861             pAttribList += 2;
1862             pContextAttribList += 2;
1863         }
1864     }
1865
1866     wine_tsx11_lock();
1867     X11DRV_expect_error(gdi_display, GLXErrorHandler, NULL);
1868     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
1869
1870     XSync(gdi_display, False);
1871     if(X11DRV_check_error() || !ret->ctx)
1872     {
1873         /* In the future we should convert the GLX error to a win32 one here if needed */
1874         ERR("Context creation failed\n");
1875         HeapFree( GetProcessHeap(), 0, ret );
1876         wine_tsx11_unlock();
1877         return NULL;
1878     }
1879
1880     list_add_head( &context_list, &ret->entry );
1881     wine_tsx11_unlock();
1882     TRACE(" creating context %p\n", ret);
1883     return ret;
1884 }
1885
1886 /**
1887  * X11DRV_wglGetExtensionsStringARB
1888  *
1889  * WGL_ARB_extensions_string: wglGetExtensionsStringARB
1890  */
1891 static const GLubyte *X11DRV_wglGetExtensionsStringARB(HDC hdc)
1892 {
1893     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
1894     return (const GLubyte *)WineGLInfo.wglExtensions;
1895 }
1896
1897 /**
1898  * X11DRV_wglCreatePbufferARB
1899  *
1900  * WGL_ARB_pbuffer: wglCreatePbufferARB
1901  */
1902 static struct wgl_pbuffer *X11DRV_wglCreatePbufferARB( HDC hdc, int iPixelFormat, int iWidth, int iHeight,
1903                                                        const int *piAttribList )
1904 {
1905     struct wgl_pbuffer* object = NULL;
1906     WineGLPixelFormat *fmt = NULL;
1907     int nCfgs = 0;
1908     int attribs[256];
1909     int nAttribs = 0;
1910
1911     TRACE("(%p, %d, %d, %d, %p)\n", hdc, iPixelFormat, iWidth, iHeight, piAttribList);
1912
1913     /* Convert the WGL pixelformat to a GLX format, if it fails then the format is invalid */
1914     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nCfgs);
1915     if(!fmt) {
1916         ERR("(%p): invalid pixel format %d\n", hdc, iPixelFormat);
1917         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
1918         return NULL;
1919     }
1920
1921     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1922     if (NULL == object) {
1923         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
1924         return NULL;
1925     }
1926     object->width = iWidth;
1927     object->height = iHeight;
1928     object->fmt = fmt;
1929
1930     PUSH2(attribs, GLX_PBUFFER_WIDTH,  iWidth);
1931     PUSH2(attribs, GLX_PBUFFER_HEIGHT, iHeight); 
1932     while (piAttribList && 0 != *piAttribList) {
1933         int attr_v;
1934         switch (*piAttribList) {
1935             case WGL_PBUFFER_LARGEST_ARB: {
1936                 ++piAttribList;
1937                 attr_v = *piAttribList;
1938                 TRACE("WGL_LARGEST_PBUFFER_ARB = %d\n", attr_v);
1939                 PUSH2(attribs, GLX_LARGEST_PBUFFER, attr_v);
1940                 break;
1941             }
1942
1943             case WGL_TEXTURE_FORMAT_ARB: {
1944                 ++piAttribList;
1945                 attr_v = *piAttribList;
1946                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_FORMAT_ARB as %x\n", attr_v);
1947                 if (WGL_NO_TEXTURE_ARB == attr_v) {
1948                     object->use_render_texture = 0;
1949                 } else {
1950                     if (!use_render_texture_emulation) {
1951                         SetLastError(ERROR_INVALID_DATA);
1952                         goto create_failed;
1953                     }
1954                     switch (attr_v) {
1955                         case WGL_TEXTURE_RGB_ARB:
1956                             object->use_render_texture = GL_RGB;
1957                             object->texture_bpp = 3;
1958                             object->texture_format = GL_RGB;
1959                             object->texture_type = GL_UNSIGNED_BYTE;
1960                             break;
1961                         case WGL_TEXTURE_RGBA_ARB:
1962                             object->use_render_texture = GL_RGBA;
1963                             object->texture_bpp = 4;
1964                             object->texture_format = GL_RGBA;
1965                             object->texture_type = GL_UNSIGNED_BYTE;
1966                             break;
1967
1968                         /* WGL_FLOAT_COMPONENTS_NV */
1969                         case WGL_TEXTURE_FLOAT_R_NV:
1970                             object->use_render_texture = GL_FLOAT_R_NV;
1971                             object->texture_bpp = 4;
1972                             object->texture_format = GL_RED;
1973                             object->texture_type = GL_FLOAT;
1974                             break;
1975                         case WGL_TEXTURE_FLOAT_RG_NV:
1976                             object->use_render_texture = GL_FLOAT_RG_NV;
1977                             object->texture_bpp = 8;
1978                             object->texture_format = GL_LUMINANCE_ALPHA;
1979                             object->texture_type = GL_FLOAT;
1980                             break;
1981                         case WGL_TEXTURE_FLOAT_RGB_NV:
1982                             object->use_render_texture = GL_FLOAT_RGB_NV;
1983                             object->texture_bpp = 12;
1984                             object->texture_format = GL_RGB;
1985                             object->texture_type = GL_FLOAT;
1986                             break;
1987                         case WGL_TEXTURE_FLOAT_RGBA_NV:
1988                             object->use_render_texture = GL_FLOAT_RGBA_NV;
1989                             object->texture_bpp = 16;
1990                             object->texture_format = GL_RGBA;
1991                             object->texture_type = GL_FLOAT;
1992                             break;
1993                         default:
1994                             ERR("Unknown texture format: %x\n", attr_v);
1995                             SetLastError(ERROR_INVALID_DATA);
1996                             goto create_failed;
1997                     }
1998                 }
1999                 break;
2000             }
2001
2002             case WGL_TEXTURE_TARGET_ARB: {
2003                 ++piAttribList;
2004                 attr_v = *piAttribList;
2005                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_TARGET_ARB as %x\n", attr_v);
2006                 if (WGL_NO_TEXTURE_ARB == attr_v) {
2007                     object->texture_target = 0;
2008                 } else {
2009                     if (!use_render_texture_emulation) {
2010                         SetLastError(ERROR_INVALID_DATA);
2011                         goto create_failed;
2012                     }
2013                     switch (attr_v) {
2014                         case WGL_TEXTURE_CUBE_MAP_ARB: {
2015                             if (iWidth != iHeight) {
2016                                 SetLastError(ERROR_INVALID_DATA);
2017                                 goto create_failed;
2018                             }
2019                             object->texture_target = GL_TEXTURE_CUBE_MAP;
2020                             object->texture_bind_target = GL_TEXTURE_BINDING_CUBE_MAP;
2021                            break;
2022                         }
2023                         case WGL_TEXTURE_1D_ARB: {
2024                             if (1 != iHeight) {
2025                                 SetLastError(ERROR_INVALID_DATA);
2026                                 goto create_failed;
2027                             }
2028                             object->texture_target = GL_TEXTURE_1D;
2029                             object->texture_bind_target = GL_TEXTURE_BINDING_1D;
2030                             break;
2031                         }
2032                         case WGL_TEXTURE_2D_ARB: {
2033                             object->texture_target = GL_TEXTURE_2D;
2034                             object->texture_bind_target = GL_TEXTURE_BINDING_2D;
2035                             break;
2036                         }
2037                         case WGL_TEXTURE_RECTANGLE_NV: {
2038                             object->texture_target = GL_TEXTURE_RECTANGLE_NV;
2039                             object->texture_bind_target = GL_TEXTURE_BINDING_RECTANGLE_NV;
2040                             break;
2041                         }
2042                         default:
2043                             ERR("Unknown texture target: %x\n", attr_v);
2044                             SetLastError(ERROR_INVALID_DATA);
2045                             goto create_failed;
2046                     }
2047                 }
2048                 break;
2049             }
2050
2051             case WGL_MIPMAP_TEXTURE_ARB: {
2052                 ++piAttribList;
2053                 attr_v = *piAttribList;
2054                 TRACE("WGL_render_texture Attribute: WGL_MIPMAP_TEXTURE_ARB as %x\n", attr_v);
2055                 if (!use_render_texture_emulation) {
2056                     SetLastError(ERROR_INVALID_DATA);
2057                     goto create_failed;
2058                 }
2059                 break;
2060             }
2061         }
2062         ++piAttribList;
2063     }
2064
2065     PUSH1(attribs, None);
2066     wine_tsx11_lock();
2067     object->drawable = pglXCreatePbuffer(gdi_display, fmt->fbconfig, attribs);
2068     wine_tsx11_unlock();
2069     TRACE("new Pbuffer drawable as %lx\n", object->drawable);
2070     if (!object->drawable) {
2071         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2072         goto create_failed; /* unexpected error */
2073     }
2074     TRACE("->(%p)\n", object);
2075     return object;
2076
2077 create_failed:
2078     HeapFree(GetProcessHeap(), 0, object);
2079     TRACE("->(FAILED)\n");
2080     return NULL;
2081 }
2082
2083 /**
2084  * X11DRV_wglDestroyPbufferARB
2085  *
2086  * WGL_ARB_pbuffer: wglDestroyPbufferARB
2087  */
2088 static BOOL X11DRV_wglDestroyPbufferARB( struct wgl_pbuffer *object )
2089 {
2090     TRACE("(%p)\n", object);
2091
2092     wine_tsx11_lock();
2093     pglXDestroyPbuffer(gdi_display, object->drawable);
2094     wine_tsx11_unlock();
2095     HeapFree(GetProcessHeap(), 0, object);
2096     return GL_TRUE;
2097 }
2098
2099 /**
2100  * X11DRV_wglGetPbufferDCARB
2101  *
2102  * WGL_ARB_pbuffer: wglGetPbufferDCARB
2103  */
2104 static HDC X11DRV_wglGetPbufferDCARB( struct wgl_pbuffer *object )
2105 {
2106     struct x11drv_escape_set_drawable escape;
2107     HDC hdc;
2108
2109     hdc = CreateDCA( "DISPLAY", NULL, NULL, NULL );
2110     if (!hdc) return 0;
2111
2112     escape.code = X11DRV_SET_DRAWABLE;
2113     escape.drawable = object->drawable;
2114     escape.mode = IncludeInferiors;
2115     SetRect( &escape.dc_rect, 0, 0, object->width, object->height );
2116     escape.fbconfig_id = object->fmt->fmt_id;
2117     escape.gl_drawable = object->drawable;
2118     escape.pixmap = 0;
2119     escape.gl_type = DC_GL_PBUFFER;
2120     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
2121
2122     TRACE( "(%p)->(%p)\n", object, hdc );
2123     return hdc;
2124 }
2125
2126 /**
2127  * X11DRV_wglQueryPbufferARB
2128  *
2129  * WGL_ARB_pbuffer: wglQueryPbufferARB
2130  */
2131 static BOOL X11DRV_wglQueryPbufferARB( struct wgl_pbuffer *object, int iAttribute, int *piValue )
2132 {
2133     TRACE("(%p, 0x%x, %p)\n", object, iAttribute, piValue);
2134
2135     switch (iAttribute) {
2136         case WGL_PBUFFER_WIDTH_ARB:
2137             wine_tsx11_lock();
2138             pglXQueryDrawable(gdi_display, object->drawable, GLX_WIDTH, (unsigned int*) piValue);
2139             wine_tsx11_unlock();
2140             break;
2141         case WGL_PBUFFER_HEIGHT_ARB:
2142             wine_tsx11_lock();
2143             pglXQueryDrawable(gdi_display, object->drawable, GLX_HEIGHT, (unsigned int*) piValue);
2144             wine_tsx11_unlock();
2145             break;
2146
2147         case WGL_PBUFFER_LOST_ARB:
2148             /* GLX Pbuffers cannot be lost by default. We can support this by
2149              * setting GLX_PRESERVED_CONTENTS to False and using glXSelectEvent
2150              * to receive pixel buffer clobber events, however that may or may
2151              * not give any benefit */
2152             *piValue = GL_FALSE;
2153             break;
2154
2155         case WGL_TEXTURE_FORMAT_ARB:
2156             if (!object->use_render_texture) {
2157                 *piValue = WGL_NO_TEXTURE_ARB;
2158             } else {
2159                 if (!use_render_texture_emulation) {
2160                     SetLastError(ERROR_INVALID_HANDLE);
2161                     return GL_FALSE;
2162                 }
2163                 switch(object->use_render_texture) {
2164                     case GL_RGB:
2165                         *piValue = WGL_TEXTURE_RGB_ARB;
2166                         break;
2167                     case GL_RGBA:
2168                         *piValue = WGL_TEXTURE_RGBA_ARB;
2169                         break;
2170                     /* WGL_FLOAT_COMPONENTS_NV */
2171                     case GL_FLOAT_R_NV:
2172                         *piValue = WGL_TEXTURE_FLOAT_R_NV;
2173                         break;
2174                     case GL_FLOAT_RG_NV:
2175                         *piValue = WGL_TEXTURE_FLOAT_RG_NV;
2176                         break;
2177                     case GL_FLOAT_RGB_NV:
2178                         *piValue = WGL_TEXTURE_FLOAT_RGB_NV;
2179                         break;
2180                     case GL_FLOAT_RGBA_NV:
2181                         *piValue = WGL_TEXTURE_FLOAT_RGBA_NV;
2182                         break;
2183                     default:
2184                         ERR("Unknown texture format: %x\n", object->use_render_texture);
2185                 }
2186             }
2187             break;
2188
2189         case WGL_TEXTURE_TARGET_ARB:
2190             if (!object->texture_target){
2191                 *piValue = WGL_NO_TEXTURE_ARB;
2192             } else {
2193                 if (!use_render_texture_emulation) {
2194                     SetLastError(ERROR_INVALID_DATA);
2195                     return GL_FALSE;
2196                 }
2197                 switch (object->texture_target) {
2198                     case GL_TEXTURE_1D:       *piValue = WGL_TEXTURE_1D_ARB; break;
2199                     case GL_TEXTURE_2D:       *piValue = WGL_TEXTURE_2D_ARB; break;
2200                     case GL_TEXTURE_CUBE_MAP: *piValue = WGL_TEXTURE_CUBE_MAP_ARB; break;
2201                     case GL_TEXTURE_RECTANGLE_NV: *piValue = WGL_TEXTURE_RECTANGLE_NV; break;
2202                 }
2203             }
2204             break;
2205
2206         case WGL_MIPMAP_TEXTURE_ARB:
2207             *piValue = GL_FALSE; /** don't support that */
2208             FIXME("unsupported WGL_ARB_render_texture attribute query for 0x%x\n", iAttribute);
2209             break;
2210
2211         default:
2212             FIXME("unexpected attribute %x\n", iAttribute);
2213             break;
2214     }
2215
2216     return GL_TRUE;
2217 }
2218
2219 /**
2220  * X11DRV_wglReleasePbufferDCARB
2221  *
2222  * WGL_ARB_pbuffer: wglReleasePbufferDCARB
2223  */
2224 static int X11DRV_wglReleasePbufferDCARB( struct wgl_pbuffer *object, HDC hdc )
2225 {
2226     TRACE("(%p, %p)\n", object, hdc);
2227     return DeleteDC(hdc);
2228 }
2229
2230 /**
2231  * X11DRV_wglSetPbufferAttribARB
2232  *
2233  * WGL_ARB_pbuffer: wglSetPbufferAttribARB
2234  */
2235 static BOOL X11DRV_wglSetPbufferAttribARB( struct wgl_pbuffer *object, const int *piAttribList )
2236 {
2237     GLboolean ret = GL_FALSE;
2238
2239     WARN("(%p, %p): alpha-testing, report any problem\n", object, piAttribList);
2240
2241     if (!object->use_render_texture) {
2242         SetLastError(ERROR_INVALID_HANDLE);
2243         return GL_FALSE;
2244     }
2245     if (1 == use_render_texture_emulation) {
2246         return GL_TRUE;
2247     }
2248     return ret;
2249 }
2250
2251 /**
2252  * X11DRV_wglChoosePixelFormatARB
2253  *
2254  * WGL_ARB_pixel_format: wglChoosePixelFormatARB
2255  */
2256 static BOOL X11DRV_wglChoosePixelFormatARB( HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList,
2257                                             UINT nMaxFormats, int *piFormats, UINT *nNumFormats )
2258 {
2259     int gl_test = 0;
2260     int attribs[256];
2261     int nAttribs = 0;
2262     GLXFBConfig* cfgs = NULL;
2263     int nCfgs = 0;
2264     int it;
2265     int fmt_id;
2266     WineGLPixelFormat *fmt;
2267     UINT pfmt_it = 0;
2268     int run;
2269     int i;
2270     DWORD dwFlags = 0;
2271
2272     TRACE("(%p, %p, %p, %d, %p, %p): hackish\n", hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats);
2273     if (NULL != pfAttribFList) {
2274         FIXME("unused pfAttribFList\n");
2275     }
2276
2277     nAttribs = ConvertAttribWGLtoGLX(piAttribIList, attribs, NULL);
2278     if (-1 == nAttribs) {
2279         WARN("Cannot convert WGL to GLX attributes\n");
2280         return GL_FALSE;
2281     }
2282     PUSH1(attribs, None);
2283
2284     /* There is no 1:1 mapping between GLX and WGL formats because we duplicate some GLX formats for bitmap rendering (see get_formats).
2285      * Flags like PFD_SUPPORT_GDI, PFD_DRAW_TO_BITMAP and others are a property of the WineGLPixelFormat. We don't query these attributes
2286      * using glXChooseFBConfig but we filter the result of glXChooseFBConfig later on by passing a dwFlags to 'ConvertPixelFormatGLXtoWGL'. */
2287     for(i=0; piAttribIList[i] != 0; i+=2)
2288     {
2289         switch(piAttribIList[i])
2290         {
2291             case WGL_DRAW_TO_BITMAP_ARB:
2292                 if(piAttribIList[i+1])
2293                     dwFlags |= PFD_DRAW_TO_BITMAP;
2294                 break;
2295             case WGL_ACCELERATION_ARB:
2296                 switch(piAttribIList[i+1])
2297                 {
2298                     case WGL_NO_ACCELERATION_ARB:
2299                         dwFlags |= PFD_GENERIC_FORMAT;
2300                         break;
2301                     case WGL_GENERIC_ACCELERATION_ARB:
2302                         dwFlags |= PFD_GENERIC_ACCELERATED;
2303                         break;
2304                     case WGL_FULL_ACCELERATION_ARB:
2305                         /* Nothing to do */
2306                         break;
2307                 }
2308                 break;
2309             case WGL_SUPPORT_GDI_ARB:
2310                 if(piAttribIList[i+1])
2311                     dwFlags |= PFD_SUPPORT_GDI;
2312                 break;
2313         }
2314     }
2315
2316     /* Search for FB configurations matching the requirements in attribs */
2317     wine_tsx11_lock();
2318     cfgs = pglXChooseFBConfig(gdi_display, DefaultScreen(gdi_display), attribs, &nCfgs);
2319     if (NULL == cfgs) {
2320         wine_tsx11_unlock();
2321         WARN("Compatible Pixel Format not found\n");
2322         return GL_FALSE;
2323     }
2324
2325     /* Loop through all matching formats and check if they are suitable.
2326      * Note that this function should at max return nMaxFormats different formats */
2327     for(run=0; run < 2; run++)
2328     {
2329         for (it = 0; it < nCfgs && pfmt_it < nMaxFormats; ++it)
2330         {
2331             gl_test = pglXGetFBConfigAttrib(gdi_display, cfgs[it], GLX_FBCONFIG_ID, &fmt_id);
2332             if (gl_test) {
2333                 ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
2334                 continue;
2335             }
2336
2337             /* Search for the format in our list of compatible formats */
2338             fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fmt_id, dwFlags);
2339             if(!fmt)
2340                 continue;
2341
2342             /* During the first run we only want onscreen formats and during the second only offscreen 'XOR' */
2343             if( ((run == 0) && fmt->offscreenOnly) || ((run == 1) && !fmt->offscreenOnly) )
2344                 continue;
2345
2346             piFormats[pfmt_it] = fmt->iPixelFormat;
2347             TRACE("at %d/%d found FBCONFIG_ID 0x%x (%d)\n", it + 1, nCfgs, fmt_id, piFormats[pfmt_it]);
2348             pfmt_it++;
2349         }
2350     }
2351
2352     *nNumFormats = pfmt_it;
2353     /** free list */
2354     XFree(cfgs);
2355     wine_tsx11_unlock();
2356     return GL_TRUE;
2357 }
2358
2359 /**
2360  * X11DRV_wglGetPixelFormatAttribivARB
2361  *
2362  * WGL_ARB_pixel_format: wglGetPixelFormatAttribivARB
2363  */
2364 static BOOL X11DRV_wglGetPixelFormatAttribivARB( HDC hdc, int iPixelFormat, int iLayerPlane,
2365                                                  UINT nAttributes, const int *piAttributes, int *piValues )
2366 {
2367     UINT i;
2368     WineGLPixelFormat *fmt = NULL;
2369     int hTest;
2370     int tmp;
2371     int curGLXAttr = 0;
2372     int nWGLFormats = 0;
2373
2374     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues);
2375
2376     if (0 < iLayerPlane) {
2377         FIXME("unsupported iLayerPlane(%d) > 0, returns FALSE\n", iLayerPlane);
2378         return GL_FALSE;
2379     }
2380
2381     /* Convert the WGL pixelformat to a GLX one, if this fails then most likely the iPixelFormat isn't supported.
2382     * We don't have to fail yet as a program can specify an invalid iPixelFormat (lets say 0) if it wants to query
2383     * the number of supported WGL formats. Whether the iPixelFormat is valid is handled in the for-loop below. */
2384     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nWGLFormats);
2385     if(!fmt) {
2386         WARN("Unable to convert iPixelFormat %d to a GLX one!\n", iPixelFormat);
2387     }
2388
2389     wine_tsx11_lock();
2390     for (i = 0; i < nAttributes; ++i) {
2391         const int curWGLAttr = piAttributes[i];
2392         TRACE("pAttr[%d] = %x\n", i, curWGLAttr);
2393
2394         switch (curWGLAttr) {
2395             case WGL_NUMBER_PIXEL_FORMATS_ARB:
2396                 piValues[i] = nWGLFormats; 
2397                 continue;
2398
2399             case WGL_SUPPORT_OPENGL_ARB:
2400                 piValues[i] = GL_TRUE; 
2401                 continue;
2402
2403             case WGL_ACCELERATION_ARB:
2404                 curGLXAttr = GLX_CONFIG_CAVEAT;
2405                 if (!fmt) goto pix_error;
2406                 if(fmt->dwFlags & PFD_GENERIC_FORMAT)
2407                     piValues[i] = WGL_NO_ACCELERATION_ARB;
2408                 else if(fmt->dwFlags & PFD_GENERIC_ACCELERATED)
2409                     piValues[i] = WGL_GENERIC_ACCELERATION_ARB;
2410                 else
2411                     piValues[i] = WGL_FULL_ACCELERATION_ARB;
2412                 continue;
2413
2414             case WGL_TRANSPARENT_ARB:
2415                 curGLXAttr = GLX_TRANSPARENT_TYPE;
2416                 if (!fmt) goto pix_error;
2417                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2418                 if (hTest) goto get_error;
2419                     piValues[i] = GL_FALSE;
2420                 if (GLX_NONE != tmp) piValues[i] = GL_TRUE;
2421                     continue;
2422
2423             case WGL_PIXEL_TYPE_ARB:
2424                 curGLXAttr = GLX_RENDER_TYPE;
2425                 if (!fmt) goto pix_error;
2426                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2427                 if (hTest) goto get_error;
2428                 TRACE("WGL_PIXEL_TYPE_ARB: GLX_RENDER_TYPE = 0x%x\n", tmp);
2429                 if      (tmp & GLX_RGBA_BIT)           { piValues[i] = WGL_TYPE_RGBA_ARB; }
2430                 else if (tmp & GLX_COLOR_INDEX_BIT)    { piValues[i] = WGL_TYPE_COLORINDEX_ARB; }
2431                 else if (tmp & GLX_RGBA_FLOAT_BIT)     { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
2432                 else if (tmp & GLX_RGBA_FLOAT_ATI_BIT) { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
2433                 else if (tmp & GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT) { piValues[i] = WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT; }
2434                 else {
2435                     ERR("unexpected RenderType(%x)\n", tmp);
2436                     piValues[i] = WGL_TYPE_RGBA_ARB;
2437                 }
2438                 continue;
2439
2440             case WGL_COLOR_BITS_ARB:
2441                 curGLXAttr = GLX_BUFFER_SIZE;
2442                 break;
2443
2444             case WGL_BIND_TO_TEXTURE_RGB_ARB:
2445             case WGL_BIND_TO_TEXTURE_RGBA_ARB:
2446                 if (!use_render_texture_emulation) {
2447                     piValues[i] = GL_FALSE;
2448                     continue;   
2449                 }
2450                 curGLXAttr = GLX_RENDER_TYPE;
2451                 if (!fmt) goto pix_error;
2452                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2453                 if (hTest) goto get_error;
2454                 if (GLX_COLOR_INDEX_BIT == tmp) {
2455                     piValues[i] = GL_FALSE;  
2456                     continue;
2457                 }
2458                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
2459                 if (hTest) goto get_error;
2460                 piValues[i] = (tmp & GLX_PBUFFER_BIT) ? GL_TRUE : GL_FALSE;
2461                 continue;
2462
2463             case WGL_BLUE_BITS_ARB:
2464                 curGLXAttr = GLX_BLUE_SIZE;
2465                 break;
2466             case WGL_RED_BITS_ARB:
2467                 curGLXAttr = GLX_RED_SIZE;
2468                 break;
2469             case WGL_GREEN_BITS_ARB:
2470                 curGLXAttr = GLX_GREEN_SIZE;
2471                 break;
2472             case WGL_ALPHA_BITS_ARB:
2473                 curGLXAttr = GLX_ALPHA_SIZE;
2474                 break;
2475             case WGL_DEPTH_BITS_ARB:
2476                 curGLXAttr = GLX_DEPTH_SIZE;
2477                 break;
2478             case WGL_STENCIL_BITS_ARB:
2479                 curGLXAttr = GLX_STENCIL_SIZE;
2480                 break;
2481             case WGL_DOUBLE_BUFFER_ARB:
2482                 curGLXAttr = GLX_DOUBLEBUFFER;
2483                 break;
2484             case WGL_STEREO_ARB:
2485                 curGLXAttr = GLX_STEREO;
2486                 break;
2487             case WGL_AUX_BUFFERS_ARB:
2488                 curGLXAttr = GLX_AUX_BUFFERS;
2489                 break;
2490
2491             case WGL_SUPPORT_GDI_ARB:
2492                 if (!fmt) goto pix_error;
2493                 piValues[i] = (fmt->dwFlags & PFD_SUPPORT_GDI) ? TRUE : FALSE;
2494                 continue;
2495
2496             case WGL_DRAW_TO_BITMAP_ARB:
2497                 if (!fmt) goto pix_error;
2498                 piValues[i] = (fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? TRUE : FALSE;
2499                 continue;
2500
2501             case WGL_DRAW_TO_WINDOW_ARB:
2502             case WGL_DRAW_TO_PBUFFER_ARB:
2503                 if (!fmt) goto pix_error;
2504                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
2505                 if (hTest) goto get_error;
2506                 if((curWGLAttr == WGL_DRAW_TO_WINDOW_ARB && (tmp&GLX_WINDOW_BIT)) ||
2507                    (curWGLAttr == WGL_DRAW_TO_PBUFFER_ARB && (tmp&GLX_PBUFFER_BIT)))
2508                     piValues[i] = GL_TRUE;
2509                 else
2510                     piValues[i] = GL_FALSE;
2511                 continue;
2512
2513             case WGL_SWAP_METHOD_ARB:
2514                 /* For now return SWAP_EXCHANGE_ARB which is the best type of buffer switch available.
2515                  * Later on we can also use GLX_OML_swap_method on drivers which support this. At this
2516                  * point only ATI offers this.
2517                  */
2518                 piValues[i] = WGL_SWAP_EXCHANGE_ARB;
2519                 break;
2520
2521             case WGL_PBUFFER_LARGEST_ARB:
2522                 curGLXAttr = GLX_LARGEST_PBUFFER;
2523                 break;
2524
2525             case WGL_SAMPLE_BUFFERS_ARB:
2526                 curGLXAttr = GLX_SAMPLE_BUFFERS_ARB;
2527                 break;
2528
2529             case WGL_SAMPLES_ARB:
2530                 curGLXAttr = GLX_SAMPLES_ARB;
2531                 break;
2532
2533             case WGL_FLOAT_COMPONENTS_NV:
2534                 curGLXAttr = GLX_FLOAT_COMPONENTS_NV;
2535                 break;
2536
2537             case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
2538                 curGLXAttr = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT;
2539                 break;
2540
2541             case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
2542                 curGLXAttr = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
2543                 break;
2544
2545             case WGL_ACCUM_RED_BITS_ARB:
2546                 curGLXAttr = GLX_ACCUM_RED_SIZE;
2547                 break;
2548             case WGL_ACCUM_GREEN_BITS_ARB:
2549                 curGLXAttr = GLX_ACCUM_GREEN_SIZE;
2550                 break;
2551             case WGL_ACCUM_BLUE_BITS_ARB:
2552                 curGLXAttr = GLX_ACCUM_BLUE_SIZE;
2553                 break;
2554             case WGL_ACCUM_ALPHA_BITS_ARB:
2555                 curGLXAttr = GLX_ACCUM_ALPHA_SIZE;
2556                 break;
2557             case WGL_ACCUM_BITS_ARB:
2558                 if (!fmt) goto pix_error;
2559                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &tmp);
2560                 if (hTest) goto get_error;
2561                 piValues[i] = tmp;
2562                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &tmp);
2563                 if (hTest) goto get_error;
2564                 piValues[i] += tmp;
2565                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &tmp);
2566                 if (hTest) goto get_error;
2567                 piValues[i] += tmp;
2568                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &tmp);
2569                 if (hTest) goto get_error;
2570                 piValues[i] += tmp;
2571                 continue;
2572
2573             default:
2574                 FIXME("unsupported %x WGL Attribute\n", curWGLAttr);
2575         }
2576
2577         /* Retrieve a GLX FBConfigAttrib when the attribute to query is valid and
2578          * iPixelFormat != 0. When iPixelFormat is 0 the only value which makes
2579          * sense to query is WGL_NUMBER_PIXEL_FORMATS_ARB.
2580          *
2581          * TODO: properly test the behavior of wglGetPixelFormatAttrib*v on Windows
2582          *       and check which options can work using iPixelFormat=0 and which not.
2583          *       A problem would be that this function is an extension. This would
2584          *       mean that the behavior could differ between different vendors (ATI, Nvidia, ..).
2585          */
2586         if (0 != curGLXAttr && iPixelFormat != 0) {
2587             if (!fmt) goto pix_error;
2588             hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, piValues + i);
2589             if (hTest) goto get_error;
2590             curGLXAttr = 0;
2591         } else { 
2592             piValues[i] = GL_FALSE; 
2593         }
2594     }
2595     wine_tsx11_unlock();
2596     return GL_TRUE;
2597
2598 get_error:
2599     wine_tsx11_unlock();
2600     ERR("(%p): unexpected failure on GetFBConfigAttrib(%x) returns FALSE\n", hdc, curGLXAttr);
2601     return GL_FALSE;
2602
2603 pix_error:
2604     wine_tsx11_unlock();
2605     ERR("(%p): unexpected iPixelFormat(%d) vs nFormats(%d), returns FALSE\n", hdc, iPixelFormat, nWGLFormats);
2606     return GL_FALSE;
2607 }
2608
2609 /**
2610  * X11DRV_wglGetPixelFormatAttribfvARB
2611  *
2612  * WGL_ARB_pixel_format: wglGetPixelFormatAttribfvARB
2613  */
2614 static BOOL X11DRV_wglGetPixelFormatAttribfvARB( HDC hdc, int iPixelFormat, int iLayerPlane,
2615                                                  UINT nAttributes, const int *piAttributes, FLOAT *pfValues )
2616 {
2617     int *attr;
2618     int ret;
2619     UINT i;
2620
2621     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues);
2622
2623     /* Allocate a temporary array to store integer values */
2624     attr = HeapAlloc(GetProcessHeap(), 0, nAttributes * sizeof(int));
2625     if (!attr) {
2626         ERR("couldn't allocate %d array\n", nAttributes);
2627         return GL_FALSE;
2628     }
2629
2630     /* Piggy-back on wglGetPixelFormatAttribivARB */
2631     ret = X11DRV_wglGetPixelFormatAttribivARB(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, attr);
2632     if (ret) {
2633         /* Convert integer values to float. Should also check for attributes
2634            that can give decimal values here */
2635         for (i=0; i<nAttributes;i++) {
2636             pfValues[i] = attr[i];
2637         }
2638     }
2639
2640     HeapFree(GetProcessHeap(), 0, attr);
2641     return ret;
2642 }
2643
2644 /**
2645  * X11DRV_wglBindTexImageARB
2646  *
2647  * WGL_ARB_render_texture: wglBindTexImageARB
2648  */
2649 static BOOL X11DRV_wglBindTexImageARB( struct wgl_pbuffer *object, int iBuffer )
2650 {
2651     GLboolean ret = GL_FALSE;
2652
2653     TRACE("(%p, %d)\n", object, iBuffer);
2654
2655     if (!object->use_render_texture) {
2656         SetLastError(ERROR_INVALID_HANDLE);
2657         return GL_FALSE;
2658     }
2659
2660     if (1 == use_render_texture_emulation) {
2661         static int init = 0;
2662         int prev_binded_texture = 0;
2663         GLXContext prev_context;
2664         Drawable prev_drawable;
2665         GLXContext tmp_context;
2666
2667         wine_tsx11_lock();
2668         prev_context = pglXGetCurrentContext();
2669         prev_drawable = pglXGetCurrentDrawable();
2670
2671         /* Our render_texture emulation is basic and lacks some features (1D/Cube support).
2672            This is mostly due to lack of demos/games using them. Further the use of glReadPixels
2673            isn't ideal performance wise but I wasn't able to get other ways working.
2674         */
2675         if(!init) {
2676             init = 1; /* Only show the FIXME once for performance reasons */
2677             FIXME("partial stub!\n");
2678         }
2679
2680         TRACE("drawable=%lx, context=%p\n", object->drawable, prev_context);
2681         tmp_context = pglXCreateNewContext(gdi_display, object->fmt->fbconfig, object->fmt->render_type, prev_context, True);
2682
2683         opengl_funcs.gl.p_glGetIntegerv(object->texture_bind_target, &prev_binded_texture);
2684
2685         /* Switch to our pbuffer */
2686         pglXMakeCurrent(gdi_display, object->drawable, tmp_context);
2687
2688         /* Make sure that the prev_binded_texture is set as the current texture state isn't shared between contexts.
2689          * After that upload the pbuffer texture data. */
2690         opengl_funcs.gl.p_glBindTexture(object->texture_target, prev_binded_texture);
2691         opengl_funcs.gl.p_glCopyTexImage2D(object->texture_target, 0, object->use_render_texture, 0, 0, object->width, object->height, 0);
2692
2693         /* Switch back to the original drawable and upload the pbuffer-texture */
2694         pglXMakeCurrent(gdi_display, prev_drawable, prev_context);
2695         pglXDestroyContext(gdi_display, tmp_context);
2696         wine_tsx11_unlock();
2697         return GL_TRUE;
2698     }
2699
2700     return ret;
2701 }
2702
2703 /**
2704  * X11DRV_wglReleaseTexImageARB
2705  *
2706  * WGL_ARB_render_texture: wglReleaseTexImageARB
2707  */
2708 static BOOL X11DRV_wglReleaseTexImageARB( struct wgl_pbuffer *object, int iBuffer )
2709 {
2710     GLboolean ret = GL_FALSE;
2711
2712     TRACE("(%p, %d)\n", object, iBuffer);
2713
2714     if (!object->use_render_texture) {
2715         SetLastError(ERROR_INVALID_HANDLE);
2716         return GL_FALSE;
2717     }
2718     if (1 == use_render_texture_emulation) {
2719         return GL_TRUE;
2720     }
2721     return ret;
2722 }
2723
2724 /**
2725  * X11DRV_wglGetExtensionsStringEXT
2726  *
2727  * WGL_EXT_extensions_string: wglGetExtensionsStringEXT
2728  */
2729 static const GLubyte *X11DRV_wglGetExtensionsStringEXT(void)
2730 {
2731     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
2732     return (const GLubyte *)WineGLInfo.wglExtensions;
2733 }
2734
2735 /**
2736  * X11DRV_wglGetSwapIntervalEXT
2737  *
2738  * WGL_EXT_swap_control: wglGetSwapIntervalEXT
2739  */
2740 static int X11DRV_wglGetSwapIntervalEXT(void)
2741 {
2742     /* GLX_SGI_swap_control doesn't have any provisions for getting the swap
2743      * interval, so the swap interval has to be tracked. */
2744     TRACE("()\n");
2745     return swap_interval;
2746 }
2747
2748 /**
2749  * X11DRV_wglSwapIntervalEXT
2750  *
2751  * WGL_EXT_swap_control: wglSwapIntervalEXT
2752  */
2753 static BOOL X11DRV_wglSwapIntervalEXT(int interval)
2754 {
2755     BOOL ret = TRUE;
2756
2757     TRACE("(%d)\n", interval);
2758
2759     if (interval < 0)
2760     {
2761         SetLastError(ERROR_INVALID_DATA);
2762         return FALSE;
2763     }
2764     else if (!has_swap_control && interval == 0)
2765     {
2766         /* wglSwapIntervalEXT considers an interval value of zero to mean that
2767          * vsync should be disabled, but glXSwapIntervalSGI considers such a
2768          * value to be an error. Just silently ignore the request for now. */
2769         WARN("Request to disable vertical sync is not handled\n");
2770         swap_interval = 0;
2771     }
2772     else
2773     {
2774         if (pglXSwapIntervalSGI)
2775         {
2776             wine_tsx11_lock();
2777             ret = !pglXSwapIntervalSGI(interval);
2778             wine_tsx11_unlock();
2779         }
2780         else
2781             WARN("GLX_SGI_swap_control extension is not available\n");
2782
2783         if (ret)
2784             swap_interval = interval;
2785         else
2786             SetLastError(ERROR_DC_NOT_FOUND);
2787     }
2788
2789     return ret;
2790 }
2791
2792 /**
2793  * X11DRV_wglSetPixelFormatWINE
2794  *
2795  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
2796  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
2797  */
2798 static BOOL X11DRV_wglSetPixelFormatWINE(HDC hdc, int format)
2799 {
2800     WineGLPixelFormat *fmt;
2801     int value;
2802     HWND hwnd;
2803
2804     TRACE("(%p,%d)\n", hdc, format);
2805
2806     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, format, FALSE /* Offscreen */, &value);
2807     if (!fmt)
2808     {
2809         ERR( "Invalid format %d\n", format );
2810         return FALSE;
2811     }
2812
2813     hwnd = WindowFromDC( hdc );
2814     if (!hwnd || hwnd == GetDesktopWindow())
2815     {
2816         ERR( "not a valid window DC %p\n", hdc );
2817         return FALSE;
2818     }
2819
2820     wine_tsx11_lock();
2821     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
2822     wine_tsx11_unlock();
2823
2824     if (!(value & GLX_WINDOW_BIT))
2825     {
2826         WARN( "Pixel format %d is not compatible for window rendering\n", format );
2827         return FALSE;
2828     }
2829
2830     return SendMessageW(hwnd, WM_X11DRV_SET_WIN_FORMAT, fmt->fmt_id, 0);
2831     /* DC pixel format will be set by the DCE update */
2832 }
2833
2834 /**
2835  * glxRequireVersion (internal)
2836  *
2837  * Check if the supported GLX version matches requiredVersion.
2838  */
2839 static BOOL glxRequireVersion(int requiredVersion)
2840 {
2841     /* Both requiredVersion and glXVersion[1] contains the minor GLX version */
2842     if(requiredVersion <= WineGLInfo.glxVersion[1])
2843         return TRUE;
2844
2845     return FALSE;
2846 }
2847
2848 static void register_extension(const char *ext)
2849 {
2850     if (WineGLInfo.wglExtensions[0])
2851         strcat(WineGLInfo.wglExtensions, " ");
2852     strcat(WineGLInfo.wglExtensions, ext);
2853
2854     TRACE("'%s'\n", ext);
2855 }
2856
2857 /**
2858  * X11DRV_WineGL_LoadExtensions
2859  */
2860 static void X11DRV_WineGL_LoadExtensions(void)
2861 {
2862     WineGLInfo.wglExtensions[0] = 0;
2863
2864     /* ARB Extensions */
2865
2866     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_create_context"))
2867     {
2868         register_extension( "WGL_ARB_create_context" );
2869         opengl_funcs.ext.p_wglCreateContextAttribsARB = X11DRV_wglCreateContextAttribsARB;
2870
2871         if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_create_context_profile"))
2872             register_extension("WGL_ARB_create_context_profile");
2873     }
2874
2875     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_fbconfig_float"))
2876     {
2877         register_extension("WGL_ARB_pixel_format_float");
2878         register_extension("WGL_ATI_pixel_format_float");
2879     }
2880
2881     register_extension( "WGL_ARB_extensions_string" );
2882     opengl_funcs.ext.p_wglGetExtensionsStringARB = X11DRV_wglGetExtensionsStringARB;
2883
2884     if (glxRequireVersion(3))
2885     {
2886         register_extension( "WGL_ARB_make_current_read" );
2887         opengl_funcs.ext.p_wglGetCurrentReadDCARB   = (void *)1;  /* never called */
2888         opengl_funcs.ext.p_wglMakeContextCurrentARB = X11DRV_wglMakeContextCurrentARB;
2889     }
2890
2891     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_multisample")) register_extension( "WGL_ARB_multisample" );
2892
2893     /* In general pbuffer functionality requires support in the X-server. The functionality is
2894      * available either when the GLX_SGIX_pbuffer is present or when the GLX server version is 1.3.
2895      */
2896     if ( glxRequireVersion(3) && has_extension( WineGLInfo.glxExtensions, "GLX_SGIX_pbuffer") )
2897     {
2898         register_extension( "WGL_ARB_pbuffer" );
2899         opengl_funcs.ext.p_wglCreatePbufferARB    = X11DRV_wglCreatePbufferARB;
2900         opengl_funcs.ext.p_wglDestroyPbufferARB   = X11DRV_wglDestroyPbufferARB;
2901         opengl_funcs.ext.p_wglGetPbufferDCARB     = X11DRV_wglGetPbufferDCARB;
2902         opengl_funcs.ext.p_wglQueryPbufferARB     = X11DRV_wglQueryPbufferARB;
2903         opengl_funcs.ext.p_wglReleasePbufferDCARB = X11DRV_wglReleasePbufferDCARB;
2904         opengl_funcs.ext.p_wglSetPbufferAttribARB = X11DRV_wglSetPbufferAttribARB;
2905     }
2906
2907     register_extension( "WGL_ARB_pixel_format" );
2908     opengl_funcs.ext.p_wglChoosePixelFormatARB      = X11DRV_wglChoosePixelFormatARB;
2909     opengl_funcs.ext.p_wglGetPixelFormatAttribfvARB = X11DRV_wglGetPixelFormatAttribfvARB;
2910     opengl_funcs.ext.p_wglGetPixelFormatAttribivARB = X11DRV_wglGetPixelFormatAttribivARB;
2911
2912     /* Support WGL_ARB_render_texture when there's support or pbuffer based emulation */
2913     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_render_texture") ||
2914         (glxRequireVersion(3) && has_extension( WineGLInfo.glxExtensions, "GLX_SGIX_pbuffer") && use_render_texture_emulation))
2915     {
2916         register_extension( "WGL_ARB_render_texture" );
2917         opengl_funcs.ext.p_wglBindTexImageARB    = X11DRV_wglBindTexImageARB;
2918         opengl_funcs.ext.p_wglReleaseTexImageARB = X11DRV_wglReleaseTexImageARB;
2919
2920         /* The WGL version of GLX_NV_float_buffer requires render_texture */
2921         if (has_extension( WineGLInfo.glxExtensions, "GLX_NV_float_buffer"))
2922             register_extension("WGL_NV_float_buffer");
2923
2924         /* Again there's no GLX equivalent for this extension, so depend on the required GL extension */
2925         if (has_extension(WineGLInfo.glExtensions, "GL_NV_texture_rectangle"))
2926             register_extension("WGL_NV_texture_rectangle");
2927     }
2928
2929     /* EXT Extensions */
2930
2931     register_extension( "WGL_EXT_extensions_string" );
2932     opengl_funcs.ext.p_wglGetExtensionsStringEXT = X11DRV_wglGetExtensionsStringEXT;
2933
2934     /* Load this extension even when it isn't backed by a GLX extension because it is has been around for ages.
2935      * Games like Call of Duty and K.O.T.O.R. rely on it. Further our emulation is good enough. */
2936     register_extension( "WGL_EXT_swap_control" );
2937     opengl_funcs.ext.p_wglSwapIntervalEXT = X11DRV_wglSwapIntervalEXT;
2938     opengl_funcs.ext.p_wglGetSwapIntervalEXT = X11DRV_wglGetSwapIntervalEXT;
2939
2940     if (has_extension( WineGLInfo.glxExtensions, "GLX_EXT_framebuffer_sRGB"))
2941         register_extension("WGL_EXT_framebuffer_sRGB");
2942
2943     if (has_extension( WineGLInfo.glxExtensions, "GLX_EXT_fbconfig_packed_float"))
2944         register_extension("WGL_EXT_pixel_format_packed_float");
2945
2946     if (has_extension( WineGLInfo.glxExtensions, "GLX_EXT_swap_control"))
2947         has_swap_control = TRUE;
2948
2949     /* The OpenGL extension GL_NV_vertex_array_range adds wgl/glX functions which aren't exported as 'real' wgl/glX extensions. */
2950     if (has_extension(WineGLInfo.glExtensions, "GL_NV_vertex_array_range"))
2951     {
2952         register_extension( "WGL_NV_vertex_array_range" );
2953         opengl_funcs.ext.p_wglAllocateMemoryNV = pglXAllocateMemoryNV;
2954         opengl_funcs.ext.p_wglFreeMemoryNV = pglXFreeMemoryNV;
2955     }
2956
2957     /* WINE-specific WGL Extensions */
2958
2959     /* In WineD3D we need the ability to set the pixel format more than once (e.g. after a device reset).
2960      * The default wglSetPixelFormat doesn't allow this, so add our own which allows it.
2961      */
2962     register_extension( "WGL_WINE_pixel_format_passthrough" );
2963     opengl_funcs.ext.p_wglSetPixelFormatWINE = X11DRV_wglSetPixelFormatWINE;
2964 }
2965
2966
2967 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
2968 {
2969     wine_tsx11_lock(); 
2970     pglXDestroyGLXPixmap(display, glxpixmap);
2971     wine_tsx11_unlock(); 
2972     return TRUE;
2973 }
2974
2975 /**
2976  * glxdrv_SwapBuffers
2977  *
2978  * Swap the buffers of this DC
2979  */
2980 static BOOL glxdrv_SwapBuffers(PHYSDEV dev)
2981 {
2982   struct glx_physdev *physdev = get_glxdrv_dev( dev );
2983   struct wgl_context *ctx = NtCurrentTeb()->glContext;
2984
2985   TRACE("(%p)\n", dev->hdc);
2986
2987   if (!ctx)
2988   {
2989       WARN("Using a NULL context, skipping\n");
2990       SetLastError(ERROR_INVALID_HANDLE);
2991       return FALSE;
2992   }
2993
2994   if (!physdev->drawable)
2995   {
2996       WARN("Using an invalid drawable, skipping\n");
2997       SetLastError(ERROR_INVALID_HANDLE);
2998       return FALSE;
2999   }
3000
3001   wine_tsx11_lock();
3002   sync_context(ctx);
3003   switch (physdev->type)
3004   {
3005   case DC_GL_PIXMAP_WIN:
3006       if(pglXCopySubBufferMESA) {
3007           int w = physdev->x11dev->dc_rect.right - physdev->x11dev->dc_rect.left;
3008           int h = physdev->x11dev->dc_rect.bottom - physdev->x11dev->dc_rect.top;
3009
3010           /* (glX)SwapBuffers has an implicit glFlush effect, however
3011            * GLX_MESA_copy_sub_buffer doesn't. Make sure GL is flushed before
3012            * copying */
3013           pglFlush();
3014           if(w > 0 && h > 0)
3015               pglXCopySubBufferMESA(gdi_display, physdev->drawable, 0, 0, w, h);
3016           break;
3017       }
3018       /* fall through */
3019   default:
3020       pglXSwapBuffers(gdi_display, physdev->drawable);
3021       break;
3022   }
3023
3024   flush_gl_drawable( physdev );
3025   wine_tsx11_unlock();
3026
3027   /* FPS support */
3028   if (TRACE_ON(fps))
3029   {
3030       static long prev_time, start_time;
3031       static unsigned long frames, frames_total;
3032
3033       DWORD time = GetTickCount();
3034       frames++;
3035       frames_total++;
3036       /* every 1.5 seconds */
3037       if (time - prev_time > 1500) {
3038           TRACE_(fps)("@ approx %.2ffps, total %.2ffps\n",
3039                       1000.0*frames/(time - prev_time), 1000.0*frames_total/(time - start_time));
3040           prev_time = time;
3041           frames = 0;
3042           if(start_time == 0) start_time = time;
3043       }
3044   }
3045
3046   return TRUE;
3047 }
3048
3049 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
3050 {
3051     WineGLPixelFormat *fmt;
3052     XVisualInfo *ret;
3053
3054     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
3055     if(fmt == NULL)
3056         return NULL;
3057
3058     wine_tsx11_lock();
3059     ret = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
3060     wine_tsx11_unlock();
3061     return ret;
3062 }
3063
3064 static BOOL create_glx_dc( PHYSDEV *pdev )
3065 {
3066     /* assume that only the main x11 device implements GetDeviceCaps */
3067     X11DRV_PDEVICE *x11dev = get_x11drv_dev( GET_NEXT_PHYSDEV( *pdev, pGetDeviceCaps ));
3068     struct glx_physdev *physdev = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*physdev) );
3069
3070     if (!physdev) return FALSE;
3071     physdev->x11dev = x11dev;
3072     push_dc_driver( pdev, &physdev->dev, &glxdrv_funcs );
3073     return TRUE;
3074 }
3075
3076 /**********************************************************************
3077  *           glxdrv_CreateDC
3078  */
3079 static BOOL glxdrv_CreateDC( PHYSDEV *pdev, LPCWSTR driver, LPCWSTR device,
3080                              LPCWSTR output, const DEVMODEW* initData )
3081 {
3082     return create_glx_dc( pdev );
3083 }
3084
3085 /**********************************************************************
3086  *           glxdrv_CreateCompatibleDC
3087  */
3088 static BOOL glxdrv_CreateCompatibleDC( PHYSDEV orig, PHYSDEV *pdev )
3089 {
3090     if (orig)  /* chain to next driver first */
3091     {
3092         orig = GET_NEXT_PHYSDEV( orig, pCreateCompatibleDC );
3093         if (!orig->funcs->pCreateCompatibleDC( orig, pdev )) return FALSE;
3094     }
3095     /* otherwise we have been called by x11drv */
3096     return create_glx_dc( pdev );
3097 }
3098
3099 /**********************************************************************
3100  *           glxdrv_DeleteDC
3101  */
3102 static BOOL glxdrv_DeleteDC( PHYSDEV dev )
3103 {
3104     struct glx_physdev *physdev = get_glxdrv_dev( dev );
3105     HeapFree( GetProcessHeap(), 0, physdev );
3106     return TRUE;
3107 }
3108
3109 /**********************************************************************
3110  *           glxdrv_ExtEscape
3111  */
3112 static INT glxdrv_ExtEscape( PHYSDEV dev, INT escape, INT in_count, LPCVOID in_data,
3113                              INT out_count, LPVOID out_data )
3114 {
3115     struct glx_physdev *physdev = get_glxdrv_dev( dev );
3116
3117     dev = GET_NEXT_PHYSDEV( dev, pExtEscape );
3118
3119     if (escape == X11DRV_ESCAPE && in_data && in_count >= sizeof(enum x11drv_escape_codes))
3120     {
3121         switch (*(const enum x11drv_escape_codes *)in_data)
3122         {
3123         case X11DRV_SET_DRAWABLE:
3124             if (in_count >= sizeof(struct x11drv_escape_set_drawable))
3125             {
3126                 const struct x11drv_escape_set_drawable *data = in_data;
3127                 physdev->pixel_format = pixelformat_from_fbconfig_id( data->fbconfig_id );
3128                 physdev->type         = data->gl_type;
3129                 physdev->drawable     = data->gl_drawable;
3130                 physdev->pixmap       = data->pixmap;
3131                 TRACE( "SET_DRAWABLE hdc %p drawable %lx pf %u type %u\n",
3132                        dev->hdc, physdev->drawable, physdev->pixel_format, physdev->type );
3133             }
3134             break;
3135         case X11DRV_GET_DRAWABLE:
3136             if (out_count >= sizeof(struct x11drv_escape_get_drawable))
3137             {
3138                 struct x11drv_escape_get_drawable *data = out_data;
3139                 data->pixel_format = physdev->pixel_format;
3140                 data->gl_type      = physdev->type;
3141                 data->gl_drawable  = physdev->drawable;
3142                 data->pixmap       = physdev->pixmap;
3143             }
3144             break;
3145         case X11DRV_FLUSH_GL_DRAWABLE:
3146             flush_gl_drawable( physdev );
3147             return TRUE;
3148         default:
3149             break;
3150         }
3151     }
3152     return dev->funcs->pExtEscape( dev, escape, in_count, in_data, out_count, out_data );
3153 }
3154
3155 /**********************************************************************
3156  *           glxdrv_wine_get_wgl_driver
3157  */
3158 static struct opengl_funcs * glxdrv_wine_get_wgl_driver( PHYSDEV dev, UINT version )
3159 {
3160     if (version != WINE_WGL_DRIVER_VERSION)
3161     {
3162         ERR( "version mismatch, opengl32 wants %u but driver has %u\n", version, WINE_WGL_DRIVER_VERSION );
3163         return NULL;
3164     }
3165
3166     if (has_opengl()) return &opengl_funcs;
3167
3168     dev = GET_NEXT_PHYSDEV( dev, wine_get_wgl_driver );
3169     return dev->funcs->wine_get_wgl_driver( dev, version );
3170 }
3171
3172 static const struct gdi_dc_funcs glxdrv_funcs =
3173 {
3174     NULL,                               /* pAbortDoc */
3175     NULL,                               /* pAbortPath */
3176     NULL,                               /* pAlphaBlend */
3177     NULL,                               /* pAngleArc */
3178     NULL,                               /* pArc */
3179     NULL,                               /* pArcTo */
3180     NULL,                               /* pBeginPath */
3181     NULL,                               /* pBlendImage */
3182     NULL,                               /* pChord */
3183     NULL,                               /* pCloseFigure */
3184     glxdrv_CreateCompatibleDC,          /* pCreateCompatibleDC */
3185     glxdrv_CreateDC,                    /* pCreateDC */
3186     glxdrv_DeleteDC,                    /* pDeleteDC */
3187     NULL,                               /* pDeleteObject */
3188     glxdrv_DescribePixelFormat,         /* pDescribePixelFormat */
3189     NULL,                               /* pDeviceCapabilities */
3190     NULL,                               /* pEllipse */
3191     NULL,                               /* pEndDoc */
3192     NULL,                               /* pEndPage */
3193     NULL,                               /* pEndPath */
3194     NULL,                               /* pEnumFonts */
3195     NULL,                               /* pEnumICMProfiles */
3196     NULL,                               /* pExcludeClipRect */
3197     NULL,                               /* pExtDeviceMode */
3198     glxdrv_ExtEscape,                   /* pExtEscape */
3199     NULL,                               /* pExtFloodFill */
3200     NULL,                               /* pExtSelectClipRgn */
3201     NULL,                               /* pExtTextOut */
3202     NULL,                               /* pFillPath */
3203     NULL,                               /* pFillRgn */
3204     NULL,                               /* pFlattenPath */
3205     NULL,                               /* pFontIsLinked */
3206     NULL,                               /* pFrameRgn */
3207     NULL,                               /* pGdiComment */
3208     NULL,                               /* pGdiRealizationInfo */
3209     NULL,                               /* pGetBoundsRect */
3210     NULL,                               /* pGetCharABCWidths */
3211     NULL,                               /* pGetCharABCWidthsI */
3212     NULL,                               /* pGetCharWidth */
3213     NULL,                               /* pGetDeviceCaps */
3214     NULL,                               /* pGetDeviceGammaRamp */
3215     NULL,                               /* pGetFontData */
3216     NULL,                               /* pGetFontUnicodeRanges */
3217     NULL,                               /* pGetGlyphIndices */
3218     NULL,                               /* pGetGlyphOutline */
3219     NULL,                               /* pGetICMProfile */
3220     NULL,                               /* pGetImage */
3221     NULL,                               /* pGetKerningPairs */
3222     NULL,                               /* pGetNearestColor */
3223     NULL,                               /* pGetOutlineTextMetrics */
3224     NULL,                               /* pGetPixel */
3225     NULL,                               /* pGetSystemPaletteEntries */
3226     NULL,                               /* pGetTextCharsetInfo */
3227     NULL,                               /* pGetTextExtentExPoint */
3228     NULL,                               /* pGetTextExtentExPointI */
3229     NULL,                               /* pGetTextFace */
3230     NULL,                               /* pGetTextMetrics */
3231     NULL,                               /* pGradientFill */
3232     NULL,                               /* pIntersectClipRect */
3233     NULL,                               /* pInvertRgn */
3234     NULL,                               /* pLineTo */
3235     NULL,                               /* pModifyWorldTransform */
3236     NULL,                               /* pMoveTo */
3237     NULL,                               /* pOffsetClipRgn */
3238     NULL,                               /* pOffsetViewportOrg */
3239     NULL,                               /* pOffsetWindowOrg */
3240     NULL,                               /* pPaintRgn */
3241     NULL,                               /* pPatBlt */
3242     NULL,                               /* pPie */
3243     NULL,                               /* pPolyBezier */
3244     NULL,                               /* pPolyBezierTo */
3245     NULL,                               /* pPolyDraw */
3246     NULL,                               /* pPolyPolygon */
3247     NULL,                               /* pPolyPolyline */
3248     NULL,                               /* pPolygon */
3249     NULL,                               /* pPolyline */
3250     NULL,                               /* pPolylineTo */
3251     NULL,                               /* pPutImage */
3252     NULL,                               /* pRealizeDefaultPalette */
3253     NULL,                               /* pRealizePalette */
3254     NULL,                               /* pRectangle */
3255     NULL,                               /* pResetDC */
3256     NULL,                               /* pRestoreDC */
3257     NULL,                               /* pRoundRect */
3258     NULL,                               /* pSaveDC */
3259     NULL,                               /* pScaleViewportExt */
3260     NULL,                               /* pScaleWindowExt */
3261     NULL,                               /* pSelectBitmap */
3262     NULL,                               /* pSelectBrush */
3263     NULL,                               /* pSelectClipPath */
3264     NULL,                               /* pSelectFont */
3265     NULL,                               /* pSelectPalette */
3266     NULL,                               /* pSelectPen */
3267     NULL,                               /* pSetArcDirection */
3268     NULL,                               /* pSetBkColor */
3269     NULL,                               /* pSetBkMode */
3270     NULL,                               /* pSetBoundsRect */
3271     NULL,                               /* pSetDCBrushColor */
3272     NULL,                               /* pSetDCPenColor */
3273     NULL,                               /* pSetDIBitsToDevice */
3274     NULL,                               /* pSetDeviceClipping */
3275     NULL,                               /* pSetDeviceGammaRamp */
3276     NULL,                               /* pSetLayout */
3277     NULL,                               /* pSetMapMode */
3278     NULL,                               /* pSetMapperFlags */
3279     NULL,                               /* pSetPixel */
3280     glxdrv_SetPixelFormat,              /* pSetPixelFormat */
3281     NULL,                               /* pSetPolyFillMode */
3282     NULL,                               /* pSetROP2 */
3283     NULL,                               /* pSetRelAbs */
3284     NULL,                               /* pSetStretchBltMode */
3285     NULL,                               /* pSetTextAlign */
3286     NULL,                               /* pSetTextCharacterExtra */
3287     NULL,                               /* pSetTextColor */
3288     NULL,                               /* pSetTextJustification */
3289     NULL,                               /* pSetViewportExt */
3290     NULL,                               /* pSetViewportOrg */
3291     NULL,                               /* pSetWindowExt */
3292     NULL,                               /* pSetWindowOrg */
3293     NULL,                               /* pSetWorldTransform */
3294     NULL,                               /* pStartDoc */
3295     NULL,                               /* pStartPage */
3296     NULL,                               /* pStretchBlt */
3297     NULL,                               /* pStretchDIBits */
3298     NULL,                               /* pStrokeAndFillPath */
3299     NULL,                               /* pStrokePath */
3300     glxdrv_SwapBuffers,                 /* pSwapBuffers */
3301     NULL,                               /* pUnrealizePalette */
3302     NULL,                               /* pWidenPath */
3303     glxdrv_wine_get_wgl_driver,         /* wine_get_wgl_driver */
3304     GDI_PRIORITY_GRAPHICS_DRV + 20      /* priority */
3305 };
3306
3307 static struct opengl_funcs opengl_funcs =
3308 {
3309     {
3310         glxdrv_wglCopyContext,              /* p_wglCopyContext */
3311         glxdrv_wglCreateContext,            /* p_wglCreateContext */
3312         glxdrv_wglDeleteContext,            /* p_wglDeleteContext */
3313         glxdrv_wglGetPixelFormat,           /* p_wglGetPixelFormat */
3314         glxdrv_wglGetProcAddress,           /* p_wglGetProcAddress */
3315         glxdrv_wglMakeCurrent,              /* p_wglMakeCurrent */
3316         glxdrv_wglShareLists,               /* p_wglShareLists */
3317     }
3318 };
3319
3320 const struct gdi_dc_funcs *get_glx_driver(void)
3321 {
3322     return &glxdrv_funcs;
3323 }
3324
3325 #else  /* no OpenGL includes */
3326
3327 const struct gdi_dc_funcs *get_glx_driver(void)
3328 {
3329     return NULL;
3330 }
3331
3332 void mark_drawable_dirty(Drawable old, Drawable new)
3333 {
3334 }
3335
3336 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
3337 {
3338     return 0;
3339 }
3340
3341
3342 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
3343 {
3344     return FALSE;
3345 }
3346
3347 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
3348 {
3349     return NULL;
3350 }
3351
3352 #endif /* defined(SONAME_LIBGL) */