gdi32: Allow a driver to implement SelectBitmap but not CreateBitmap.
[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  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #ifdef HAVE_SYS_SOCKET_H
33 #include <sys/socket.h>
34 #endif
35 #ifdef HAVE_SYS_UN_H
36 #include <sys/un.h>
37 #endif
38
39 #include "x11drv.h"
40 #include "winternl.h"
41 #include "wine/library.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(wgl);
45
46 #ifdef SONAME_LIBGL
47
48 WINE_DECLARE_DEBUG_CHANNEL(winediag);
49
50 #undef APIENTRY
51 #undef CALLBACK
52 #undef WINAPI
53
54 #ifdef HAVE_GL_GL_H
55 # include <GL/gl.h>
56 #endif
57 #ifdef HAVE_GL_GLX_H
58 # include <GL/glx.h>
59 #endif
60
61 #include "wine/wgl.h"
62
63 #undef APIENTRY
64 #undef CALLBACK
65 #undef WINAPI
66
67 /* Redefines the constants */
68 #define CALLBACK    __stdcall
69 #define WINAPI      __stdcall
70 #define APIENTRY    WINAPI
71
72
73 WINE_DECLARE_DEBUG_CHANNEL(fps);
74
75 typedef struct wine_glextension {
76     const char *extName;
77     struct {
78         const char *funcName;
79         void *funcAddress;
80     } extEntryPoints[9];
81 } WineGLExtension;
82
83 struct WineGLInfo {
84     const char *glVersion;
85     char *glExtensions;
86
87     int glxVersion[2];
88
89     const char *glxServerVersion;
90     const char *glxServerVendor;
91     const char *glxServerExtensions;
92
93     const char *glxClientVersion;
94     const char *glxClientVendor;
95     const char *glxClientExtensions;
96
97     const char *glxExtensions;
98
99     BOOL glxDirect;
100     char wglExtensions[4096];
101 };
102
103 typedef struct wine_glpixelformat {
104     int         iPixelFormat;
105     GLXFBConfig fbconfig;
106     int         fmt_id;
107     int         render_type;
108     BOOL        offscreenOnly;
109     DWORD       dwFlags; /* We store some PFD_* flags in here for emulated bitmap formats */
110 } WineGLPixelFormat;
111
112 typedef struct wine_glcontext {
113     HDC hdc;
114     BOOL has_been_current;
115     BOOL sharing;
116     DWORD tid;
117     BOOL gl3_context;
118     XVisualInfo *vis;
119     WineGLPixelFormat *fmt;
120     int numAttribs; /* This is needed for delaying wglCreateContextAttribsARB */
121     int attribList[16]; /* This is needed for delaying wglCreateContextAttribsARB */
122     GLXContext ctx;
123     HDC read_hdc;
124     Drawable drawables[2];
125     BOOL refresh_drawables;
126     struct list entry;
127 } Wine_GLContext;
128
129 typedef struct wine_glpbuffer {
130     Drawable   drawable;
131     Display*   display;
132     WineGLPixelFormat* fmt;
133     int        width;
134     int        height;
135     int*       attribList;
136     HDC        hdc;
137
138     int        use_render_texture; /* This is also the internal texture format */
139     int        texture_bind_target;
140     int        texture_bpp;
141     GLint      texture_format;
142     GLuint     texture_target;
143     GLenum     texture_type;
144     GLuint     texture;
145     int        texture_level;
146 } Wine_GLPBuffer;
147
148 static struct list context_list = LIST_INIT( context_list );
149 static struct WineGLInfo WineGLInfo = { 0 };
150 static int use_render_texture_emulation = 1;
151 static int use_render_texture_ati = 0;
152 static BOOL has_swap_control;
153 static int swap_interval = 1;
154
155 #define MAX_EXTENSIONS 16
156 static const WineGLExtension *WineGLExtensionList[MAX_EXTENSIONS];
157 static int WineGLExtensionListSize;
158
159 static void X11DRV_WineGL_LoadExtensions(void);
160 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count);
161 static BOOL glxRequireVersion(int requiredVersion);
162 static BOOL glxRequireExtension(const char *requiredExtension);
163
164 static void dump_PIXELFORMATDESCRIPTOR(const PIXELFORMATDESCRIPTOR *ppfd) {
165   TRACE("  - size / version : %d / %d\n", ppfd->nSize, ppfd->nVersion);
166   TRACE("  - dwFlags : ");
167 #define TEST_AND_DUMP(t,tv) if ((t) & (tv)) TRACE(#tv " ")
168   TEST_AND_DUMP(ppfd->dwFlags, PFD_DEPTH_DONTCARE);
169   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER);
170   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER_DONTCARE);
171   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_WINDOW);
172   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_BITMAP);
173   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_ACCELERATED);
174   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_FORMAT);
175   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_PALETTE);
176   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_SYSTEM_PALETTE);
177   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO);
178   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO_DONTCARE);
179   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_GDI);
180   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_OPENGL);
181   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_COPY);
182   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_EXCHANGE);
183   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_LAYER_BUFFERS);
184   /* PFD_SUPPORT_COMPOSITION is new in Vista, it is similar to composition
185    * under X e.g. COMPOSITE + GLX_EXT_TEXTURE_FROM_PIXMAP. */
186   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_COMPOSITION);
187 #undef TEST_AND_DUMP
188   TRACE("\n");
189
190   TRACE("  - iPixelType : ");
191   switch (ppfd->iPixelType) {
192   case PFD_TYPE_RGBA: TRACE("PFD_TYPE_RGBA"); break;
193   case PFD_TYPE_COLORINDEX: TRACE("PFD_TYPE_COLORINDEX"); break;
194   }
195   TRACE("\n");
196
197   TRACE("  - Color   : %d\n", ppfd->cColorBits);
198   TRACE("  - Red     : %d\n", ppfd->cRedBits);
199   TRACE("  - Green   : %d\n", ppfd->cGreenBits);
200   TRACE("  - Blue    : %d\n", ppfd->cBlueBits);
201   TRACE("  - Alpha   : %d\n", ppfd->cAlphaBits);
202   TRACE("  - Accum   : %d\n", ppfd->cAccumBits);
203   TRACE("  - Depth   : %d\n", ppfd->cDepthBits);
204   TRACE("  - Stencil : %d\n", ppfd->cStencilBits);
205   TRACE("  - Aux     : %d\n", ppfd->cAuxBuffers);
206
207   TRACE("  - iLayerType : ");
208   switch (ppfd->iLayerType) {
209   case PFD_MAIN_PLANE: TRACE("PFD_MAIN_PLANE"); break;
210   case PFD_OVERLAY_PLANE: TRACE("PFD_OVERLAY_PLANE"); break;
211   case (BYTE)PFD_UNDERLAY_PLANE: TRACE("PFD_UNDERLAY_PLANE"); break;
212   }
213   TRACE("\n");
214 }
215
216 #define PUSH1(attribs,att)        do { attribs[nAttribs++] = (att); } while (0)
217 #define PUSH2(attribs,att,value)  do { attribs[nAttribs++] = (att); attribs[nAttribs++] = (value); } while(0)
218
219 #define MAKE_FUNCPTR(f) static typeof(f) * p##f;
220 /* GLX 1.0 */
221 MAKE_FUNCPTR(glXChooseVisual)
222 MAKE_FUNCPTR(glXCopyContext)
223 MAKE_FUNCPTR(glXCreateContext)
224 MAKE_FUNCPTR(glXCreateGLXPixmap)
225 MAKE_FUNCPTR(glXGetCurrentContext)
226 MAKE_FUNCPTR(glXGetCurrentDrawable)
227 MAKE_FUNCPTR(glXDestroyContext)
228 MAKE_FUNCPTR(glXDestroyGLXPixmap)
229 MAKE_FUNCPTR(glXGetConfig)
230 MAKE_FUNCPTR(glXIsDirect)
231 MAKE_FUNCPTR(glXMakeCurrent)
232 MAKE_FUNCPTR(glXSwapBuffers)
233 MAKE_FUNCPTR(glXQueryExtension)
234 MAKE_FUNCPTR(glXQueryVersion)
235
236 /* GLX 1.1 */
237 MAKE_FUNCPTR(glXGetClientString)
238 MAKE_FUNCPTR(glXQueryExtensionsString)
239 MAKE_FUNCPTR(glXQueryServerString)
240
241 /* GLX 1.3 */
242 MAKE_FUNCPTR(glXGetFBConfigs)
243 MAKE_FUNCPTR(glXChooseFBConfig)
244 MAKE_FUNCPTR(glXCreatePbuffer)
245 MAKE_FUNCPTR(glXCreateNewContext)
246 MAKE_FUNCPTR(glXDestroyPbuffer)
247 MAKE_FUNCPTR(glXGetFBConfigAttrib)
248 MAKE_FUNCPTR(glXGetVisualFromFBConfig)
249 MAKE_FUNCPTR(glXMakeContextCurrent)
250 MAKE_FUNCPTR(glXQueryDrawable)
251 MAKE_FUNCPTR(glXGetCurrentReadDrawable)
252
253 /* GLX Extensions */
254 static GLXContext (*pglXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
255 static void* (*pglXGetProcAddressARB)(const GLubyte *);
256 static int   (*pglXSwapIntervalSGI)(int);
257
258 /* ATI GLX Extensions */
259 static BOOL  (*pglXBindTexImageATI)(Display *dpy, GLXPbuffer pbuffer, int buffer);
260 static BOOL  (*pglXReleaseTexImageATI)(Display *dpy, GLXPbuffer pbuffer, int buffer);
261 static BOOL  (*pglXDrawableAttribATI)(Display *dpy, GLXDrawable draw, const int *attribList);
262
263 /* NV GLX Extension */
264 static void* (*pglXAllocateMemoryNV)(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
265 static void  (*pglXFreeMemoryNV)(GLvoid *pointer);
266
267 /* MESA GLX Extensions */
268 static void (*pglXCopySubBufferMESA)(Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
269
270 /* Standard OpenGL */
271 MAKE_FUNCPTR(glBindTexture)
272 MAKE_FUNCPTR(glBitmap)
273 MAKE_FUNCPTR(glCopyTexSubImage1D)
274 MAKE_FUNCPTR(glCopyTexImage2D)
275 MAKE_FUNCPTR(glCopyTexSubImage2D)
276 MAKE_FUNCPTR(glDrawBuffer)
277 MAKE_FUNCPTR(glEndList)
278 MAKE_FUNCPTR(glGetError)
279 MAKE_FUNCPTR(glGetIntegerv)
280 MAKE_FUNCPTR(glGetString)
281 MAKE_FUNCPTR(glNewList)
282 MAKE_FUNCPTR(glPixelStorei)
283 MAKE_FUNCPTR(glReadPixels)
284 MAKE_FUNCPTR(glTexImage2D)
285 MAKE_FUNCPTR(glFinish)
286 MAKE_FUNCPTR(glFlush)
287 #undef MAKE_FUNCPTR
288
289 static int GLXErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
290 {
291     /* In the future we might want to find the exact X or GLX error to report back to the app */
292     return 1;
293 }
294
295 static BOOL infoInitialized = FALSE;
296 static BOOL X11DRV_WineGL_InitOpenglInfo(void)
297 {
298     int screen = DefaultScreen(gdi_display);
299     Window win = 0, root = 0;
300     const char *gl_renderer;
301     const char* str;
302     XVisualInfo *vis;
303     GLXContext ctx = NULL;
304     XSetWindowAttributes attr;
305     BOOL ret = FALSE;
306     int attribList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
307
308     if (infoInitialized)
309         return TRUE;
310     infoInitialized = TRUE;
311
312     attr.override_redirect = True;
313     attr.colormap = None;
314     attr.border_pixel = 0;
315
316     wine_tsx11_lock();
317
318     vis = pglXChooseVisual(gdi_display, screen, attribList);
319     if (vis) {
320 #ifdef __i386__
321         WORD old_fs = wine_get_fs();
322         /* Create a GLX Context. Without one we can't query GL information */
323         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
324         if (wine_get_fs() != old_fs)
325         {
326             wine_set_fs( old_fs );
327             ERR( "%%fs register corrupted, probably broken ATI driver, disabling OpenGL.\n" );
328             ERR( "You need to set the \"UseFastTls\" option to \"2\" in your X config file.\n" );
329             goto done;
330         }
331 #else
332         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
333 #endif
334     }
335     if (!ctx) goto done;
336
337     root = RootWindow( gdi_display, vis->screen );
338     if (vis->visual != DefaultVisual( gdi_display, vis->screen ))
339         attr.colormap = XCreateColormap( gdi_display, root, vis->visual, AllocNone );
340     if ((win = XCreateWindow( gdi_display, root, -1, -1, 1, 1, 0, vis->depth, InputOutput,
341                               vis->visual, CWBorderPixel | CWOverrideRedirect | CWColormap, &attr )))
342         XMapWindow( gdi_display, win );
343     else
344         win = root;
345
346     if(pglXMakeCurrent(gdi_display, win, ctx) == 0)
347     {
348         ERR_(winediag)( "Unable to activate OpenGL context, most likely your OpenGL drivers haven't been installed correctly\n" );
349         goto done;
350     }
351     gl_renderer = (const char *)pglGetString(GL_RENDERER);
352     WineGLInfo.glVersion = (const char *) pglGetString(GL_VERSION);
353     str = (const char *) pglGetString(GL_EXTENSIONS);
354     WineGLInfo.glExtensions = HeapAlloc(GetProcessHeap(), 0, strlen(str)+1);
355     strcpy(WineGLInfo.glExtensions, str);
356
357     /* Get the common GLX version supported by GLX client and server ( major/minor) */
358     pglXQueryVersion(gdi_display, &WineGLInfo.glxVersion[0], &WineGLInfo.glxVersion[1]);
359
360     WineGLInfo.glxServerVersion = pglXQueryServerString(gdi_display, screen, GLX_VERSION);
361     WineGLInfo.glxServerVendor = pglXQueryServerString(gdi_display, screen, GLX_VENDOR);
362     WineGLInfo.glxServerExtensions = pglXQueryServerString(gdi_display, screen, GLX_EXTENSIONS);
363
364     WineGLInfo.glxClientVersion = pglXGetClientString(gdi_display, GLX_VERSION);
365     WineGLInfo.glxClientVendor = pglXGetClientString(gdi_display, GLX_VENDOR);
366     WineGLInfo.glxClientExtensions = pglXGetClientString(gdi_display, GLX_EXTENSIONS);
367
368     WineGLInfo.glxExtensions = pglXQueryExtensionsString(gdi_display, screen);
369     WineGLInfo.glxDirect = pglXIsDirect(gdi_display, ctx);
370
371     TRACE("GL version             : %s.\n", WineGLInfo.glVersion);
372     TRACE("GL renderer            : %s.\n", gl_renderer);
373     TRACE("GLX version            : %d.%d.\n", WineGLInfo.glxVersion[0], WineGLInfo.glxVersion[1]);
374     TRACE("Server GLX version     : %s.\n", WineGLInfo.glxServerVersion);
375     TRACE("Server GLX vendor:     : %s.\n", WineGLInfo.glxServerVendor);
376     TRACE("Client GLX version     : %s.\n", WineGLInfo.glxClientVersion);
377     TRACE("Client GLX vendor:     : %s.\n", WineGLInfo.glxClientVendor);
378     TRACE("Direct rendering enabled: %s\n", WineGLInfo.glxDirect ? "True" : "False");
379
380     if(!WineGLInfo.glxDirect)
381     {
382         int fd = ConnectionNumber(gdi_display);
383         struct sockaddr_un uaddr;
384         unsigned int uaddrlen = sizeof(struct sockaddr_un);
385
386         /* In general indirect rendering on a local X11 server indicates a driver problem.
387          * Detect a local X11 server by checking whether the X11 socket is a Unix socket.
388          */
389         if(!getsockname(fd, (struct sockaddr *)&uaddr, &uaddrlen) && uaddr.sun_family == AF_UNIX)
390             ERR_(winediag)("Direct rendering is disabled, most likely your OpenGL drivers "
391                            "haven't been installed correctly (using GL renderer %s, version %s).\n",
392                            debugstr_a(gl_renderer), debugstr_a(WineGLInfo.glVersion));
393     }
394     else
395     {
396         /* In general you would expect that if direct rendering is returned, that you receive hardware
397          * accelerated OpenGL rendering. The definition of direct rendering is that rendering is performed
398          * client side without sending all GL commands to X using the GLX protocol. When Mesa falls back to
399          * software rendering, it shows direct rendering.
400          *
401          * Depending on the cause of software rendering a different rendering string is shown. In case Mesa fails
402          * to load a DRI module 'Software Rasterizer' is returned. When Mesa is compiled as a OpenGL reference driver
403          * it shows 'Mesa X11'.
404          */
405         if(!strcmp(gl_renderer, "Software Rasterizer") || !strcmp(gl_renderer, "Mesa X11"))
406             ERR_(winediag)("The Mesa OpenGL driver is using software rendering, most likely your OpenGL "
407                            "drivers haven't been installed correctly (using GL renderer %s, version %s).\n",
408                            debugstr_a(gl_renderer), debugstr_a(WineGLInfo.glVersion));
409     }
410     ret = TRUE;
411
412 done:
413     if(vis) XFree(vis);
414     if(ctx) {
415         pglXMakeCurrent(gdi_display, None, NULL);    
416         pglXDestroyContext(gdi_display, ctx);
417     }
418     if (win != root) XDestroyWindow( gdi_display, win );
419     if (attr.colormap) XFreeColormap( gdi_display, attr.colormap );
420     wine_tsx11_unlock();
421     if (!ret) ERR(" couldn't initialize OpenGL, expect problems\n");
422     return ret;
423 }
424
425 void X11DRV_OpenGL_Cleanup(void)
426 {
427     HeapFree(GetProcessHeap(), 0, WineGLInfo.glExtensions);
428     infoInitialized = FALSE;
429 }
430
431 static BOOL has_opengl(void)
432 {
433     static int init_done;
434     static void *opengl_handle;
435
436     char buffer[200];
437     int error_base, event_base;
438
439     if (init_done) return (opengl_handle != NULL);
440     init_done = 1;
441
442     /* No need to load any other libraries as according to the ABI, libGL should be self-sufficient
443        and include all dependencies */
444     opengl_handle = wine_dlopen(SONAME_LIBGL, RTLD_NOW|RTLD_GLOBAL, buffer, sizeof(buffer));
445     if (opengl_handle == NULL)
446     {
447         ERR( "Failed to load libGL: %s\n", buffer );
448         ERR( "OpenGL support is disabled.\n");
449         return FALSE;
450     }
451
452     pglXGetProcAddressARB = wine_dlsym(opengl_handle, "glXGetProcAddressARB", NULL, 0);
453     if (pglXGetProcAddressARB == NULL) {
454         ERR("Could not find glXGetProcAddressARB in libGL, disabling OpenGL.\n");
455         goto failed;
456     }
457
458 #define LOAD_FUNCPTR(f) do if((p##f = (void*)pglXGetProcAddressARB((const unsigned char*)#f)) == NULL) \
459     { \
460         ERR( "%s not found in libGL, disabling OpenGL.\n", #f ); \
461         goto failed; \
462     } while(0)
463
464     /* GLX 1.0 */
465     LOAD_FUNCPTR(glXChooseVisual);
466     LOAD_FUNCPTR(glXCopyContext);
467     LOAD_FUNCPTR(glXCreateContext);
468     LOAD_FUNCPTR(glXCreateGLXPixmap);
469     LOAD_FUNCPTR(glXGetCurrentContext);
470     LOAD_FUNCPTR(glXGetCurrentDrawable);
471     LOAD_FUNCPTR(glXDestroyContext);
472     LOAD_FUNCPTR(glXDestroyGLXPixmap);
473     LOAD_FUNCPTR(glXGetConfig);
474     LOAD_FUNCPTR(glXIsDirect);
475     LOAD_FUNCPTR(glXMakeCurrent);
476     LOAD_FUNCPTR(glXSwapBuffers);
477     LOAD_FUNCPTR(glXQueryExtension);
478     LOAD_FUNCPTR(glXQueryVersion);
479
480     /* GLX 1.1 */
481     LOAD_FUNCPTR(glXGetClientString);
482     LOAD_FUNCPTR(glXQueryExtensionsString);
483     LOAD_FUNCPTR(glXQueryServerString);
484
485     /* GLX 1.3 */
486     LOAD_FUNCPTR(glXCreatePbuffer);
487     LOAD_FUNCPTR(glXCreateNewContext);
488     LOAD_FUNCPTR(glXDestroyPbuffer);
489     LOAD_FUNCPTR(glXMakeContextCurrent);
490     LOAD_FUNCPTR(glXGetCurrentReadDrawable);
491     LOAD_FUNCPTR(glXGetFBConfigs);
492
493     /* Standard OpenGL calls */
494     LOAD_FUNCPTR(glBindTexture);
495     LOAD_FUNCPTR(glBitmap);
496     LOAD_FUNCPTR(glCopyTexSubImage1D);
497     LOAD_FUNCPTR(glCopyTexImage2D);
498     LOAD_FUNCPTR(glCopyTexSubImage2D);
499     LOAD_FUNCPTR(glDrawBuffer);
500     LOAD_FUNCPTR(glEndList);
501     LOAD_FUNCPTR(glGetError);
502     LOAD_FUNCPTR(glGetIntegerv);
503     LOAD_FUNCPTR(glGetString);
504     LOAD_FUNCPTR(glNewList);
505     LOAD_FUNCPTR(glPixelStorei);
506     LOAD_FUNCPTR(glReadPixels);
507     LOAD_FUNCPTR(glTexImage2D);
508     LOAD_FUNCPTR(glFinish);
509     LOAD_FUNCPTR(glFlush);
510 #undef LOAD_FUNCPTR
511
512 /* It doesn't matter if these fail. They'll only be used if the driver reports
513    the associated extension is available (and if a driver reports the extension
514    is available but fails to provide the functions, it's quite broken) */
515 #define LOAD_FUNCPTR(f) p##f = pglXGetProcAddressARB((const GLubyte *)#f)
516     /* ARB GLX Extension */
517     LOAD_FUNCPTR(glXCreateContextAttribsARB);
518     /* SGI GLX Extension */
519     LOAD_FUNCPTR(glXSwapIntervalSGI);
520     /* NV GLX Extension */
521     LOAD_FUNCPTR(glXAllocateMemoryNV);
522     LOAD_FUNCPTR(glXFreeMemoryNV);
523 #undef LOAD_FUNCPTR
524
525     if(!X11DRV_WineGL_InitOpenglInfo()) goto failed;
526
527     wine_tsx11_lock();
528     if (pglXQueryExtension(gdi_display, &error_base, &event_base)) {
529         TRACE("GLX is up and running error_base = %d\n", error_base);
530     } else {
531         wine_tsx11_unlock();
532         ERR( "GLX extension is missing, disabling OpenGL.\n" );
533         goto failed;
534     }
535
536     /* In case of GLX you have direct and indirect rendering. Most of the time direct rendering is used
537      * as in general only that is hardware accelerated. In some cases like in case of remote X indirect
538      * rendering is used.
539      *
540      * The main problem for our OpenGL code is that we need certain GLX calls but their presence
541      * depends on the reported GLX client / server version and on the client / server extension list.
542      * Those don't have to be the same.
543      *
544      * In general the server GLX information lists the capabilities in case of indirect rendering.
545      * When direct rendering is used, the OpenGL client library is responsible for which GLX calls are
546      * available and in that case the client GLX informat can be used.
547      * OpenGL programs should use the 'intersection' of both sets of information which is advertised
548      * in the GLX version/extension list. When a program does this it works for certain for both
549      * direct and indirect rendering.
550      *
551      * The problem we are having in this area is that ATI's Linux drivers are broken. For some reason
552      * they haven't added some very important GLX extensions like GLX_SGIX_fbconfig to their client
553      * extension list which causes this extension not to be listed. (Wine requires this extension).
554      * ATI advertises a GLX client version of 1.3 which implies that this fbconfig extension among
555      * pbuffers is around.
556      *
557      * In order to provide users of Ati's proprietary drivers with OpenGL support, we need to detect
558      * the ATI drivers and from then on use GLX client information for them.
559      */
560
561     if(glxRequireVersion(3)) {
562         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
563         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
564         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
565         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
566     } else if(glxRequireExtension("GLX_SGIX_fbconfig")) {
567         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfigSGIX");
568         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttribSGIX");
569         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfigSGIX");
570
571         /* The mesa libGL client library seems to forward glXQueryDrawable to the Xserver, so only
572          * enable this function when the Xserver understand GLX 1.3 or newer
573          */
574         pglXQueryDrawable = NULL;
575      } else if(strcmp("ATI", WineGLInfo.glxClientVendor) == 0) {
576         TRACE("Overriding ATI GLX capabilities!\n");
577         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
578         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
579         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
580         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
581
582         /* Use client GLX information in case of the ATI drivers. We override the
583          * capabilities over here and not somewhere else as ATI might better their
584          * life in the future. In case they release proper drivers this block of
585          * code won't be called. */
586         WineGLInfo.glxExtensions = WineGLInfo.glxClientExtensions;
587     } else {
588          ERR(" glx_version is %s and GLX_SGIX_fbconfig extension is unsupported. Expect problems.\n", WineGLInfo.glxServerVersion);
589     }
590
591     if(glxRequireExtension("GLX_ATI_render_texture")) {
592         use_render_texture_ati = 1;
593         pglXBindTexImageATI = pglXGetProcAddressARB((const GLubyte *) "glXBindTexImageATI");
594         pglXReleaseTexImageATI = pglXGetProcAddressARB((const GLubyte *) "glXReleaseTexImageATI");
595         pglXDrawableAttribATI = pglXGetProcAddressARB((const GLubyte *) "glXDrawableAttribATI");
596     }
597
598     if(glxRequireExtension("GLX_MESA_copy_sub_buffer")) {
599         pglXCopySubBufferMESA = pglXGetProcAddressARB((const GLubyte *) "glXCopySubBufferMESA");
600     }
601
602     X11DRV_WineGL_LoadExtensions();
603
604     wine_tsx11_unlock();
605     return TRUE;
606
607 failed:
608     wine_dlclose(opengl_handle, NULL, 0);
609     opengl_handle = NULL;
610     return FALSE;
611 }
612
613 static inline void free_context(Wine_GLContext *context)
614 {
615 }
616
617 static inline BOOL is_valid_context( Wine_GLContext *ctx )
618 {
619     Wine_GLContext *ptr;
620     LIST_FOR_EACH_ENTRY( ptr, &context_list, struct wine_glcontext, entry )
621         if (ptr == ctx) return TRUE;
622     return FALSE;
623 }
624
625 static int describeContext(Wine_GLContext* ctx) {
626     int tmp;
627     int ctx_vis_id;
628     TRACE(" Context %p have (vis:%p):\n", ctx, ctx->vis);
629     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_FBCONFIG_ID, &tmp);
630     TRACE(" - FBCONFIG_ID 0x%x\n", tmp);
631     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &tmp);
632     TRACE(" - VISUAL_ID 0x%x\n", tmp);
633     ctx_vis_id = tmp;
634     return ctx_vis_id;
635 }
636
637 static BOOL describeDrawable(X11DRV_PDEVICE *physDev) {
638     int tmp;
639     WineGLPixelFormat *fmt;
640     int fmt_count = 0;
641
642     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, physDev->current_pf, TRUE /* Offscreen */, &fmt_count);
643     if(!fmt) return FALSE;
644
645     TRACE(" HDC %p has:\n", physDev->dev.hdc);
646     TRACE(" - iPixelFormat %d\n", fmt->iPixelFormat);
647     TRACE(" - Drawable %lx\n", physDev->gl_drawable);
648     TRACE(" - FBCONFIG_ID 0x%x\n", fmt->fmt_id);
649
650     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &tmp);
651     TRACE(" - VISUAL_ID 0x%x\n", tmp);
652
653     return TRUE;
654 }
655
656 static int ConvertAttribWGLtoGLX(const int* iWGLAttr, int* oGLXAttr, Wine_GLPBuffer* pbuf) {
657   int nAttribs = 0;
658   unsigned cur = 0; 
659   int pop;
660   int drawattrib = 0;
661   int nvfloatattrib = GLX_DONT_CARE;
662   int pixelattrib = GLX_DONT_CARE;
663
664   /* The list of WGL attributes is allowed to be NULL. We don't return here for NULL
665    * because we need to do fixups for GLX_DRAWABLE_TYPE/GLX_RENDER_TYPE/GLX_FLOAT_COMPONENTS_NV. */
666   while (iWGLAttr && 0 != iWGLAttr[cur]) {
667     TRACE("pAttr[%d] = %x\n", cur, iWGLAttr[cur]);
668
669     switch (iWGLAttr[cur]) {
670     case WGL_AUX_BUFFERS_ARB:
671       pop = iWGLAttr[++cur];
672       PUSH2(oGLXAttr, GLX_AUX_BUFFERS, pop);
673       TRACE("pAttr[%d] = GLX_AUX_BUFFERS: %d\n", cur, pop);
674       break;
675     case WGL_COLOR_BITS_ARB:
676       pop = iWGLAttr[++cur];
677       PUSH2(oGLXAttr, GLX_BUFFER_SIZE, pop);
678       TRACE("pAttr[%d] = GLX_BUFFER_SIZE: %d\n", cur, pop);
679       break;
680     case WGL_BLUE_BITS_ARB:
681       pop = iWGLAttr[++cur];
682       PUSH2(oGLXAttr, GLX_BLUE_SIZE, pop);
683       TRACE("pAttr[%d] = GLX_BLUE_SIZE: %d\n", cur, pop);
684       break;
685     case WGL_RED_BITS_ARB:
686       pop = iWGLAttr[++cur];
687       PUSH2(oGLXAttr, GLX_RED_SIZE, pop);
688       TRACE("pAttr[%d] = GLX_RED_SIZE: %d\n", cur, pop);
689       break;
690     case WGL_GREEN_BITS_ARB:
691       pop = iWGLAttr[++cur];
692       PUSH2(oGLXAttr, GLX_GREEN_SIZE, pop);
693       TRACE("pAttr[%d] = GLX_GREEN_SIZE: %d\n", cur, pop);
694       break;
695     case WGL_ALPHA_BITS_ARB:
696       pop = iWGLAttr[++cur];
697       PUSH2(oGLXAttr, GLX_ALPHA_SIZE, pop);
698       TRACE("pAttr[%d] = GLX_ALPHA_SIZE: %d\n", cur, pop);
699       break;
700     case WGL_DEPTH_BITS_ARB:
701       pop = iWGLAttr[++cur];
702       PUSH2(oGLXAttr, GLX_DEPTH_SIZE, pop);
703       TRACE("pAttr[%d] = GLX_DEPTH_SIZE: %d\n", cur, pop);
704       break;
705     case WGL_STENCIL_BITS_ARB:
706       pop = iWGLAttr[++cur];
707       PUSH2(oGLXAttr, GLX_STENCIL_SIZE, pop);
708       TRACE("pAttr[%d] = GLX_STENCIL_SIZE: %d\n", cur, pop);
709       break;
710     case WGL_DOUBLE_BUFFER_ARB:
711       pop = iWGLAttr[++cur];
712       PUSH2(oGLXAttr, GLX_DOUBLEBUFFER, pop);
713       TRACE("pAttr[%d] = GLX_DOUBLEBUFFER: %d\n", cur, pop);
714       break;
715     case WGL_STEREO_ARB:
716       pop = iWGLAttr[++cur];
717       PUSH2(oGLXAttr, GLX_STEREO, pop);
718       TRACE("pAttr[%d] = GLX_STEREO: %d\n", cur, pop);
719       break;
720
721     case WGL_PIXEL_TYPE_ARB:
722       pop = iWGLAttr[++cur];
723       TRACE("pAttr[%d] = WGL_PIXEL_TYPE_ARB: %d\n", cur, pop);
724       switch (pop) {
725       case WGL_TYPE_COLORINDEX_ARB: pixelattrib = GLX_COLOR_INDEX_BIT; break ;
726       case WGL_TYPE_RGBA_ARB: pixelattrib = GLX_RGBA_BIT; break ;
727       /* 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 */
728       case WGL_TYPE_RGBA_FLOAT_ATI: pixelattrib = GLX_RGBA_FLOAT_BIT; break ;
729       case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT: pixelattrib = GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT; break ;
730       default:
731         ERR("unexpected PixelType(%x)\n", pop); 
732         pop = 0;
733       }
734       break;
735
736     case WGL_SUPPORT_GDI_ARB:
737       /* This flag is set in a WineGLPixelFormat */
738       pop = iWGLAttr[++cur];
739       TRACE("pAttr[%d] = WGL_SUPPORT_GDI_ARB: %d\n", cur, pop);
740       break;
741
742     case WGL_DRAW_TO_BITMAP_ARB:
743       /* This flag is set in a WineGLPixelFormat */
744       pop = iWGLAttr[++cur];
745       TRACE("pAttr[%d] = WGL_DRAW_TO_BITMAP_ARB: %d\n", cur, pop);
746       break;
747
748     case WGL_DRAW_TO_WINDOW_ARB:
749       pop = iWGLAttr[++cur];
750       TRACE("pAttr[%d] = WGL_DRAW_TO_WINDOW_ARB: %d\n", cur, pop);
751       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
752       if (pop) {
753         drawattrib |= GLX_WINDOW_BIT;
754       }
755       break;
756
757     case WGL_DRAW_TO_PBUFFER_ARB:
758       pop = iWGLAttr[++cur];
759       TRACE("pAttr[%d] = WGL_DRAW_TO_PBUFFER_ARB: %d\n", cur, pop);
760       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
761       if (pop) {
762         drawattrib |= GLX_PBUFFER_BIT;
763       }
764       break;
765
766     case WGL_ACCELERATION_ARB:
767       /* This flag is set in a WineGLPixelFormat */
768       pop = iWGLAttr[++cur];
769       TRACE("pAttr[%d] = WGL_ACCELERATION_ARB: %d\n", cur, pop);
770       break;
771
772     case WGL_SUPPORT_OPENGL_ARB:
773       pop = iWGLAttr[++cur];
774       /** nothing to do, if we are here, supposing support Accelerated OpenGL */
775       TRACE("pAttr[%d] = WGL_SUPPORT_OPENGL_ARB: %d\n", cur, pop);
776       break;
777
778     case WGL_SWAP_METHOD_ARB:
779       pop = iWGLAttr[++cur];
780       /* For now we ignore this and just return SWAP_EXCHANGE */
781       TRACE("pAttr[%d] = WGL_SWAP_METHOD_ARB: %#x\n", cur, pop);
782       break;
783
784     case WGL_PBUFFER_LARGEST_ARB:
785       pop = iWGLAttr[++cur];
786       PUSH2(oGLXAttr, GLX_LARGEST_PBUFFER, pop);
787       TRACE("pAttr[%d] = GLX_LARGEST_PBUFFER: %x\n", cur, pop);
788       break;
789
790     case WGL_SAMPLE_BUFFERS_ARB:
791       pop = iWGLAttr[++cur];
792       PUSH2(oGLXAttr, GLX_SAMPLE_BUFFERS_ARB, pop);
793       TRACE("pAttr[%d] = GLX_SAMPLE_BUFFERS_ARB: %x\n", cur, pop);
794       break;
795
796     case WGL_SAMPLES_ARB:
797       pop = iWGLAttr[++cur];
798       PUSH2(oGLXAttr, GLX_SAMPLES_ARB, pop);
799       TRACE("pAttr[%d] = GLX_SAMPLES_ARB: %x\n", cur, pop);
800       break;
801
802     case WGL_TEXTURE_FORMAT_ARB:
803     case WGL_TEXTURE_TARGET_ARB:
804     case WGL_MIPMAP_TEXTURE_ARB:
805       TRACE("WGL_render_texture Attributes: %x as %x\n", iWGLAttr[cur], iWGLAttr[cur + 1]);
806       pop = iWGLAttr[++cur];
807       if (NULL == pbuf) {
808         ERR("trying to use GLX_Pbuffer Attributes without Pbuffer (was %x)\n", iWGLAttr[cur]);
809       }
810       if (use_render_texture_ati) {
811         /** nothing to do here */
812       }
813       else if (!use_render_texture_emulation) {
814         if (WGL_NO_TEXTURE_ARB != pop) {
815           ERR("trying to use WGL_render_texture Attributes without support (was %x)\n", iWGLAttr[cur]);
816           return -1; /** error: don't support it */
817         } else {
818           drawattrib |= GLX_PBUFFER_BIT;
819         }
820       }
821       break ;
822     case WGL_FLOAT_COMPONENTS_NV:
823       nvfloatattrib = iWGLAttr[++cur];
824       TRACE("pAttr[%d] = WGL_FLOAT_COMPONENTS_NV: %x\n", cur, nvfloatattrib);
825       break ;
826     case WGL_BIND_TO_TEXTURE_DEPTH_NV:
827     case WGL_BIND_TO_TEXTURE_RGB_ARB:
828     case WGL_BIND_TO_TEXTURE_RGBA_ARB:
829     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV:
830     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV:
831     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV:
832     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV:
833       pop = iWGLAttr[++cur];
834       /** cannot be converted, see direct handling on 
835        *   - wglGetPixelFormatAttribivARB
836        *  TODO: wglChoosePixelFormat
837        */
838       break ;
839     case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
840       pop = iWGLAttr[++cur];
841       PUSH2(oGLXAttr, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, pop);
842       TRACE("pAttr[%d] = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT: %x\n", cur, pop);
843       break ;
844
845     case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
846       pop = iWGLAttr[++cur];
847       PUSH2(oGLXAttr, GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT, pop);
848       TRACE("pAttr[%d] = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT: %x\n", cur, pop);
849       break ;
850     default:
851       FIXME("unsupported %x WGL Attribute\n", iWGLAttr[cur]);
852       break;
853     }
854     ++cur;
855   }
856
857   /* By default glXChooseFBConfig defaults to GLX_WINDOW_BIT. wglChoosePixelFormatARB searches through
858    * all formats. Unless drawattrib is set to a non-zero value override it with GLX_DONT_CARE, so that
859    * pixmap and pbuffer formats appear as well. */
860   if (!drawattrib) drawattrib = GLX_DONT_CARE;
861   PUSH2(oGLXAttr, GLX_DRAWABLE_TYPE, drawattrib);
862   TRACE("pAttr[?] = GLX_DRAWABLE_TYPE: %#x\n", drawattrib);
863
864   /* By default glXChooseFBConfig uses GLX_RGBA_BIT as the default value. Since wglChoosePixelFormatARB
865    * searches in all formats we have to do the same. For this reason we set GLX_RENDER_TYPE to
866    * GLX_DONT_CARE unless it is overridden. */
867   PUSH2(oGLXAttr, GLX_RENDER_TYPE, pixelattrib);
868   TRACE("pAttr[?] = GLX_RENDER_TYPE: %#x\n", pixelattrib);
869
870   /* Set GLX_FLOAT_COMPONENTS_NV all the time */
871   if(strstr(WineGLInfo.glxExtensions, "GLX_NV_float_buffer")) {
872     PUSH2(oGLXAttr, GLX_FLOAT_COMPONENTS_NV, nvfloatattrib);
873     TRACE("pAttr[?] = GLX_FLOAT_COMPONENTS_NV: %#x\n", nvfloatattrib);
874   }
875
876   return nAttribs;
877 }
878
879 static int get_render_type_from_fbconfig(Display *display, GLXFBConfig fbconfig)
880 {
881     int render_type=0, render_type_bit;
882     pglXGetFBConfigAttrib(display, fbconfig, GLX_RENDER_TYPE, &render_type_bit);
883     switch(render_type_bit)
884     {
885         case GLX_RGBA_BIT:
886             render_type = GLX_RGBA_TYPE;
887             break;
888         case GLX_COLOR_INDEX_BIT:
889             render_type = GLX_COLOR_INDEX_TYPE;
890             break;
891         case GLX_RGBA_FLOAT_BIT:
892             render_type = GLX_RGBA_FLOAT_TYPE;
893             break;
894         case GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT:
895             render_type = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
896             break;
897         default:
898             ERR("Unknown render_type: %x\n", render_type_bit);
899     }
900     return render_type;
901 }
902
903 /* Check whether a fbconfig is suitable for Windows-style bitmap rendering */
904 static BOOL check_fbconfig_bitmap_capability(Display *display, GLXFBConfig fbconfig)
905 {
906     int dbuf, value;
907     pglXGetFBConfigAttrib(display, fbconfig, GLX_DOUBLEBUFFER, &dbuf);
908     pglXGetFBConfigAttrib(gdi_display, fbconfig, GLX_DRAWABLE_TYPE, &value);
909
910     /* Windows only supports bitmap rendering on single buffered formats, further the fbconfig needs to have
911      * the GLX_PIXMAP_BIT set. */
912     return !dbuf && (value & GLX_PIXMAP_BIT);
913 }
914
915 static WineGLPixelFormat *get_formats(Display *display, int *size_ret, int *onscreen_size_ret)
916 {
917     static WineGLPixelFormat *list;
918     static int size, onscreen_size;
919
920     int fmt_id, nCfgs, i, run, bmp_formats;
921     GLXFBConfig* cfgs;
922     XVisualInfo *visinfo;
923
924     wine_tsx11_lock();
925     if (list) goto done;
926
927     cfgs = pglXGetFBConfigs(display, DefaultScreen(display), &nCfgs);
928     if (NULL == cfgs || 0 == nCfgs) {
929         if(cfgs != NULL) XFree(cfgs);
930         wine_tsx11_unlock();
931         ERR("glXChooseFBConfig returns NULL\n");
932         return NULL;
933     }
934
935     /* Bitmap rendering on Windows implies the use of the Microsoft GDI software renderer.
936      * Further most GLX drivers only offer pixmap rendering using indirect rendering (except for modern drivers which support 'AIGLX' / composite).
937      * Indirect rendering can indicate software rendering (on Nvidia it is hw accelerated)
938      * Since bitmap rendering implies the use of software rendering we can safely use indirect rendering for bitmaps.
939      *
940      * Below we count the number of formats which are suitable for bitmap rendering. Windows restricts bitmap rendering to single buffered formats.
941      */
942     for(i=0, bmp_formats=0; i<nCfgs; i++)
943     {
944         if(check_fbconfig_bitmap_capability(display, cfgs[i]))
945             bmp_formats++;
946     }
947     TRACE("Found %d bitmap capable fbconfigs\n", bmp_formats);
948
949     list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (nCfgs + bmp_formats)*sizeof(WineGLPixelFormat));
950
951     /* Fill the pixel format list. Put onscreen formats at the top and offscreen ones at the bottom.
952      * Do this as GLX doesn't guarantee that the list is sorted */
953     for(run=0; run < 2; run++)
954     {
955         for(i=0; i<nCfgs; i++) {
956             pglXGetFBConfigAttrib(display, cfgs[i], GLX_FBCONFIG_ID, &fmt_id);
957             visinfo = pglXGetVisualFromFBConfig(display, cfgs[i]);
958
959             /* The first run we only add onscreen formats (ones which have an associated X Visual).
960              * The second run we only set offscreen formats. */
961             if(!run && visinfo)
962             {
963                 /* We implement child window rendering using offscreen buffers (using composite or an XPixmap).
964                  * The contents is copied to the destination using XCopyArea. For the copying to work
965                  * the depth of the source and destination window should be the same. In general this should
966                  * not be a problem for OpenGL as drivers only advertise formats with a similar depth (or no depth).
967                  * As of the introduction of composition managers at least Nvidia now also offers ARGB visuals
968                  * with a depth of 32 in addition to the default 24 bit. In order to prevent BadMatch errors we only
969                  * list formats with the same depth. */
970                 if(visinfo->depth != screen_depth)
971                 {
972                     XFree(visinfo);
973                     continue;
974                 }
975
976                 TRACE("Found onscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
977                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
978                 list[size].fbconfig = cfgs[i];
979                 list[size].fmt_id = fmt_id;
980                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
981                 list[size].offscreenOnly = FALSE;
982                 list[size].dwFlags = 0;
983                 size++;
984                 onscreen_size++;
985
986                 /* Clone a format if it is bitmap capable for indirect rendering to bitmaps */
987                 if(check_fbconfig_bitmap_capability(display, cfgs[i]))
988                 {
989                     TRACE("Found bitmap capable format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
990                     list[size].iPixelFormat = size+1; /* The index starts at 1 */
991                     list[size].fbconfig = cfgs[i];
992                     list[size].fmt_id = fmt_id;
993                     list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
994                     list[size].offscreenOnly = FALSE;
995                     list[size].dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI | PFD_GENERIC_FORMAT;
996                     size++;
997                     onscreen_size++;
998                 }
999             } else if(run && !visinfo) {
1000                 int window_drawable=0;
1001                 pglXGetFBConfigAttrib(gdi_display, cfgs[i], GLX_DRAWABLE_TYPE, &window_drawable);
1002
1003                 /* Recent Nvidia drivers and DRI drivers offer window drawable formats without a visual.
1004                  * This are formats like 16-bit rgb on a 24-bit desktop. In order to support these formats
1005                  * onscreen we would have to use glXCreateWindow instead of XCreateWindow. Further it will
1006                  * likely make our child window opengl rendering more complicated since likely you can't use
1007                  * XCopyArea on a GLX Window.
1008                  * For now ignore fbconfigs which are window drawable but lack a visual. */
1009                 if(window_drawable & GLX_WINDOW_BIT)
1010                 {
1011                     TRACE("Skipping FBCONFIG_ID 0x%x as an offscreen format because it is window_drawable\n", fmt_id);
1012                     continue;
1013                 }
1014
1015                 TRACE("Found offscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1016                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
1017                 list[size].fbconfig = cfgs[i];
1018                 list[size].fmt_id = fmt_id;
1019                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1020                 list[size].offscreenOnly = TRUE;
1021                 list[size].dwFlags = 0;
1022                 size++;
1023             }
1024
1025             if (visinfo) XFree(visinfo);
1026         }
1027     }
1028
1029     XFree(cfgs);
1030
1031 done:
1032     if (size_ret) *size_ret = size;
1033     if (onscreen_size_ret) *onscreen_size_ret = onscreen_size;
1034     wine_tsx11_unlock();
1035     return list;
1036 }
1037
1038 /* GLX can advertise dozens of different pixelformats including offscreen and onscreen ones.
1039  * In our WGL implementation we only support a subset of these formats namely the format of
1040  * Wine's main visual and offscreen formats (if they are available).
1041  * This function converts a WGL format to its corresponding GLX one. It returns a WineGLPixelFormat
1042  * and it returns the number of supported WGL formats in fmt_count.
1043  */
1044 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count)
1045 {
1046     WineGLPixelFormat *list, *res = NULL;
1047     int size, onscreen_size;
1048
1049     if (!(list = get_formats(display, &size, &onscreen_size ))) return NULL;
1050
1051     /* Check if the pixelformat is valid. Note that it is legal to pass an invalid
1052      * iPixelFormat in case of probing the number of pixelformats.
1053      */
1054     if((iPixelFormat > 0) && (iPixelFormat <= size) &&
1055        (!list[iPixelFormat-1].offscreenOnly || AllowOffscreen)) {
1056         res = &list[iPixelFormat-1];
1057         TRACE("Returning fmt_id=%#x for iPixelFormat=%d\n", res->fmt_id, iPixelFormat);
1058     }
1059
1060     if(AllowOffscreen)
1061         *fmt_count = size;
1062     else
1063         *fmt_count = onscreen_size;
1064
1065     TRACE("Number of returned pixelformats=%d\n", *fmt_count);
1066
1067     return res;
1068 }
1069
1070 /* Search our internal pixelformat list for the WGL format corresponding to the given fbconfig */
1071 static WineGLPixelFormat* ConvertPixelFormatGLXtoWGL(Display *display, int fmt_id, DWORD dwFlags)
1072 {
1073     WineGLPixelFormat *list;
1074     int i, size;
1075
1076     if (!(list = get_formats(display, &size, NULL ))) return NULL;
1077
1078     for(i=0; i<size; i++) {
1079         /* A GLX format can appear multiple times in the pixel format list due to fake formats for bitmap rendering.
1080          * Fake formats might get selected when the user passes the proper flags using the dwFlags parameter. */
1081         if( (list[i].fmt_id == fmt_id) && ((list[i].dwFlags & dwFlags) == dwFlags) ) {
1082             TRACE("Returning iPixelFormat %d for fmt_id 0x%x\n", list[i].iPixelFormat, fmt_id);
1083             return &list[i];
1084         }
1085     }
1086     TRACE("No compatible format found for fmt_id 0x%x\n", fmt_id);
1087     return NULL;
1088 }
1089
1090 int pixelformat_from_fbconfig_id(XID fbconfig_id)
1091 {
1092     WineGLPixelFormat *fmt;
1093
1094     if (!fbconfig_id) return 0;
1095
1096     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
1097     if(fmt)
1098         return fmt->iPixelFormat;
1099     /* This will happen on hwnds without a pixel format set; it's ok */
1100     return 0;
1101 }
1102
1103
1104 /* Mark any allocated context using the glx drawable 'old' to use 'new' */
1105 void mark_drawable_dirty(Drawable old, Drawable new)
1106 {
1107     Wine_GLContext *ctx;
1108     LIST_FOR_EACH_ENTRY( ctx, &context_list, struct wine_glcontext, entry )
1109     {
1110         if (old == ctx->drawables[0]) {
1111             ctx->drawables[0] = new;
1112             ctx->refresh_drawables = TRUE;
1113         }
1114         if (old == ctx->drawables[1]) {
1115             ctx->drawables[1] = new;
1116             ctx->refresh_drawables = TRUE;
1117         }
1118     }
1119 }
1120
1121 /* Given the current context, make sure its drawable is sync'd */
1122 static inline void sync_context(Wine_GLContext *context)
1123 {
1124     if(context && context->refresh_drawables) {
1125         if (glxRequireVersion(3))
1126             pglXMakeContextCurrent(gdi_display, context->drawables[0],
1127                                    context->drawables[1], context->ctx);
1128         else
1129             pglXMakeCurrent(gdi_display, context->drawables[0], context->ctx);
1130         context->refresh_drawables = FALSE;
1131     }
1132 }
1133
1134
1135 static GLXContext create_glxcontext(Display *display, Wine_GLContext *context, GLXContext shareList)
1136 {
1137     GLXContext ctx;
1138
1139     /* We use indirect rendering for rendering to bitmaps. See get_formats for a comment about this. */
1140     BOOL indirect = (context->fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? FALSE : TRUE;
1141
1142     if(context->gl3_context)
1143     {
1144         if(context->numAttribs)
1145             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, context->attribList);
1146         else
1147             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, NULL);
1148     }
1149     else if(context->vis)
1150         ctx = pglXCreateContext(gdi_display, context->vis, shareList, indirect);
1151     else /* Create a GLX Context for a pbuffer */
1152         ctx = pglXCreateNewContext(gdi_display, context->fmt->fbconfig, context->fmt->render_type, shareList, TRUE);
1153
1154     return ctx;
1155 }
1156
1157
1158 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
1159 {
1160     return pglXCreateGLXPixmap(display, vis, parent);
1161 }
1162
1163
1164 static XID create_bitmap_glxpixmap(X11DRV_PDEVICE *physDev, WineGLPixelFormat *fmt)
1165 {
1166     GLXPixmap ret = 0;
1167     XVisualInfo *vis;
1168
1169     wine_tsx11_lock();
1170
1171     vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
1172     if(vis) {
1173         if(vis->depth == physDev->bitmap->depth)
1174             ret = pglXCreateGLXPixmap(gdi_display, vis, physDev->bitmap->pixmap);
1175         XFree(vis);
1176     }
1177     wine_tsx11_unlock();
1178     TRACE("return %lx\n", ret);
1179     return ret;
1180 }
1181
1182 /**
1183  * X11DRV_ChoosePixelFormat
1184  *
1185  * Equivalent to glXChooseVisual.
1186  */
1187 int X11DRV_ChoosePixelFormat(PHYSDEV dev, const PIXELFORMATDESCRIPTOR *ppfd)
1188 {
1189     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
1190     WineGLPixelFormat *list;
1191     int onscreen_size;
1192     int ret = 0;
1193     int value = 0;
1194     int i = 0;
1195     int bestFormat = -1;
1196     int bestDBuffer = -1;
1197     int bestStereo = -1;
1198     int bestColor = -1;
1199     int bestAlpha = -1;
1200     int bestDepth = -1;
1201     int bestStencil = -1;
1202     int bestAux = -1;
1203
1204     if (!has_opengl()) return 0;
1205
1206     if (TRACE_ON(wgl)) {
1207         TRACE("(%p,%p)\n", physDev, ppfd);
1208
1209         dump_PIXELFORMATDESCRIPTOR(ppfd);
1210     }
1211
1212     if (!(list = get_formats(gdi_display, NULL, &onscreen_size ))) return 0;
1213
1214     wine_tsx11_lock();
1215     for(i=0; i<onscreen_size; i++)
1216     {
1217         int dwFlags = 0;
1218         int iPixelType = 0;
1219         int alpha=0, color=0, depth=0, stencil=0, aux=0;
1220         WineGLPixelFormat *fmt = &list[i];
1221
1222         /* Pixel type */
1223         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1224         if (value & GLX_RGBA_BIT)
1225             iPixelType = PFD_TYPE_RGBA;
1226         else
1227             iPixelType = PFD_TYPE_COLORINDEX;
1228
1229         if (ppfd->iPixelType != iPixelType)
1230         {
1231             TRACE("pixel type mismatch for iPixelFormat=%d\n", i+1);
1232             continue;
1233         }
1234
1235         /* Only use bitmap capable for formats for bitmap rendering.
1236          * See get_formats for more info. */
1237         if( (ppfd->dwFlags & PFD_DRAW_TO_BITMAP) != (fmt->dwFlags & PFD_DRAW_TO_BITMAP))
1238         {
1239             TRACE("PFD_DRAW_TO_BITMAP mismatch for iPixelFormat=%d\n", i+1);
1240             continue;
1241         }
1242
1243         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1244         if (value) dwFlags |= PFD_DOUBLEBUFFER;
1245         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value);
1246         if (value) dwFlags |= PFD_STEREO;
1247         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &color); /* cColorBits */
1248         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &alpha); /* cAlphaBits */
1249         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &depth); /* cDepthBits */
1250         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &stencil); /* cStencilBits */
1251         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &aux); /* cAuxBuffers */
1252
1253         /* The behavior of PDF_STEREO/PFD_STEREO_DONTCARE and PFD_DOUBLEBUFFER / PFD_DOUBLEBUFFER_DONTCARE
1254          * is not very clear on MSDN. They specify that ChoosePixelFormat tries to match pixel formats
1255          * with the flag (PFD_STEREO / PFD_DOUBLEBUFFERING) set. Otherwise it says that it tries to match
1256          * formats without the given flag set.
1257          * A test on Windows using a Radeon 9500pro on WinXP (the driver doesn't support Stereo)
1258          * has indicated that a format without stereo is returned when stereo is unavailable.
1259          * So in case PFD_STEREO is set, formats that support it should have priority above formats
1260          * without. In case PFD_STEREO_DONTCARE is set, stereo is ignored.
1261          *
1262          * To summarize the following is most likely the correct behavior:
1263          * stereo not set -> prefer no-stereo formats, else also accept stereo formats
1264          * stereo set -> prefer stereo formats, else also accept no-stereo formats
1265          * stereo don't care -> it doesn't matter whether we get stereo or not
1266          *
1267          * In Wine we will treat no-stereo the same way as don't care because it makes
1268          * format selection even more complicated and second drivers with Stereo advertise
1269          * each format twice anyway.
1270          */
1271
1272         /* Doublebuffer, see the comments above */
1273         if( !(ppfd->dwFlags & PFD_DOUBLEBUFFER_DONTCARE) ) {
1274             if( ((ppfd->dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer) &&
1275                 ((dwFlags & PFD_DOUBLEBUFFER) == (ppfd->dwFlags & PFD_DOUBLEBUFFER)) )
1276                 goto found;
1277
1278             if(bestDBuffer != -1 && (dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer)
1279                 continue;
1280         }
1281
1282         /* Stereo, see the comments above. */
1283         if( !(ppfd->dwFlags & PFD_STEREO_DONTCARE) ) {
1284             if( ((ppfd->dwFlags & PFD_STEREO) != bestStereo) &&
1285                 ((dwFlags & PFD_STEREO) == (ppfd->dwFlags & PFD_STEREO)) )
1286                 goto found;
1287
1288             if(bestStereo != -1 && (dwFlags & PFD_STEREO) != bestStereo)
1289                 continue;
1290         }
1291
1292         /* Below we will do a number of checks to select the 'best' pixelformat.
1293          * We assume the precedence cColorBits > cAlphaBits > cDepthBits > cStencilBits -> cAuxBuffers.
1294          * The code works by trying to match the most important options as close as possible.
1295          * When a reasonable format is found, we will try to match more options.
1296          * It appears (see the opengl32 test) that Windows opengl drivers ignore options
1297          * like cColorBits, cAlphaBits and friends if they are set to 0, so they are considered
1298          * as DONTCARE. At least Serious Sam TSE relies on this behavior. */
1299
1300         if(ppfd->cColorBits) {
1301             if( ((ppfd->cColorBits > bestColor) && (color > bestColor)) ||
1302                 ((color >= ppfd->cColorBits) && (color < bestColor)) )
1303                 goto found;
1304
1305             if(bestColor != color) {  /* Do further checks if the format is compatible */
1306                 TRACE("color mismatch for iPixelFormat=%d\n", i+1);
1307                 continue;
1308             }
1309         }
1310
1311         if(ppfd->cAlphaBits) {
1312             if( ((ppfd->cAlphaBits > bestAlpha) && (alpha > bestAlpha)) ||
1313                 ((alpha >= ppfd->cAlphaBits) && (alpha < bestAlpha)) )
1314                 goto found;
1315
1316             if(bestAlpha != alpha) {
1317                 TRACE("alpha mismatch for iPixelFormat=%d\n", i+1);
1318                 continue;
1319             }
1320         }
1321
1322         if(ppfd->cDepthBits) {
1323             if( ((ppfd->cDepthBits > bestDepth) && (depth > bestDepth)) ||
1324                 ((depth >= ppfd->cDepthBits) && (depth < bestDepth)) )
1325                 goto found;
1326
1327             if(bestDepth != depth) {
1328                 TRACE("depth mismatch for iPixelFormat=%d\n", i+1);
1329                 continue;
1330             }
1331         }
1332
1333         if(ppfd->cStencilBits) {
1334             if( ((ppfd->cStencilBits > bestStencil) && (stencil > bestStencil)) ||
1335                 ((stencil >= ppfd->cStencilBits) && (stencil < bestStencil)) )
1336                 goto found;
1337
1338             if(bestStencil != stencil) {
1339                 TRACE("stencil mismatch for iPixelFormat=%d\n", i+1);
1340                 continue;
1341             }
1342         }
1343
1344         if(ppfd->cAuxBuffers) {
1345             if( ((ppfd->cAuxBuffers > bestAux) && (aux > bestAux)) ||
1346                 ((aux >= ppfd->cAuxBuffers) && (aux < bestAux)) )
1347                 goto found;
1348
1349             if(bestAux != aux) {
1350                 TRACE("aux mismatch for iPixelFormat=%d\n", i+1);
1351                 continue;
1352             }
1353         }
1354         continue;
1355
1356     found:
1357         bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1358         bestStereo = dwFlags & PFD_STEREO;
1359         bestAlpha = alpha;
1360         bestColor = color;
1361         bestDepth = depth;
1362         bestStencil = stencil;
1363         bestAux = aux;
1364         bestFormat = i;
1365     }
1366
1367     if(bestFormat == -1) {
1368         TRACE("No matching mode was found returning 0\n");
1369         ret = 0;
1370     }
1371     else {
1372         ret = bestFormat+1; /* the return value should be a 1-based index */
1373         TRACE("Successfully found a matching mode, returning index: %d %x\n", ret, list[bestFormat].fmt_id);
1374     }
1375
1376     wine_tsx11_unlock();
1377
1378     return ret;
1379 }
1380 /**
1381  * X11DRV_DescribePixelFormat
1382  *
1383  * Get the pixel-format descriptor associated to the given id
1384  */
1385 int X11DRV_DescribePixelFormat(PHYSDEV dev, int iPixelFormat,
1386                                UINT nBytes, PIXELFORMATDESCRIPTOR *ppfd)
1387 {
1388   X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
1389   /*XVisualInfo *vis;*/
1390   int value;
1391   int rb,gb,bb,ab;
1392   WineGLPixelFormat *fmt;
1393   int ret = 0;
1394   int fmt_count = 0;
1395
1396   if (!has_opengl()) return 0;
1397
1398   TRACE("(%p,%d,%d,%p)\n", physDev, iPixelFormat, nBytes, ppfd);
1399
1400   /* 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 */
1401   fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &fmt_count);
1402   if (ppfd == NULL) {
1403       /* The application is only querying the number of pixelformats */
1404       return fmt_count;
1405   } else if(fmt == NULL) {
1406       WARN("unexpected iPixelFormat(%d): not >=1 and <=nFormats(%d), returning NULL!\n", iPixelFormat, fmt_count);
1407       return 0;
1408   }
1409
1410   if (nBytes < sizeof(PIXELFORMATDESCRIPTOR)) {
1411     ERR("Wrong structure size !\n");
1412     /* Should set error */
1413     return 0;
1414   }
1415
1416   ret = fmt_count;
1417
1418   memset(ppfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
1419   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
1420   ppfd->nVersion = 1;
1421
1422   /* These flags are always the same... */
1423   ppfd->dwFlags = PFD_SUPPORT_OPENGL;
1424   /* Now the flags extracted from the Visual */
1425
1426   wine_tsx11_lock();
1427
1428   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1429   if(value & GLX_WINDOW_BIT)
1430       ppfd->dwFlags |= PFD_DRAW_TO_WINDOW;
1431
1432   /* On Windows bitmap rendering is only offered using the GDI Software renderer. We reserve some formats (see get_formats for more info)
1433    * for bitmap rendering since we require indirect rendering for this. Further pixel format logs of a GeforceFX, Geforce8800GT, Radeon HD3400 and a
1434    * 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
1435    * offered the GDI bit either. */
1436   ppfd->dwFlags |= fmt->dwFlags & (PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI);
1437
1438   /* PFD_GENERIC_FORMAT - gdi software rendering
1439    * PFD_GENERIC_ACCELERATED - some parts are accelerated by a display driver (MCD e.g. 3dfx minigl)
1440    * none set - full hardware accelerated by a ICD
1441    *
1442    * We only set PFD_GENERIC_FORMAT on bitmap formats (see get_formats) as that's what ATI and Nvidia Windows drivers do  */
1443   ppfd->dwFlags |= fmt->dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED);
1444
1445   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1446   if (value) {
1447       ppfd->dwFlags |= PFD_DOUBLEBUFFER;
1448       ppfd->dwFlags &= ~PFD_SUPPORT_GDI;
1449   }
1450   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value); if (value) ppfd->dwFlags |= PFD_STEREO;
1451
1452   /* Pixel type */
1453   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1454   if (value & GLX_RGBA_BIT)
1455     ppfd->iPixelType = PFD_TYPE_RGBA;
1456   else
1457     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
1458
1459   /* Color bits */
1460   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &value);
1461   ppfd->cColorBits = value;
1462
1463   /* Red, green, blue and alpha bits / shifts */
1464   if (ppfd->iPixelType == PFD_TYPE_RGBA) {
1465     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RED_SIZE, &rb);
1466     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_GREEN_SIZE, &gb);
1467     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BLUE_SIZE, &bb);
1468     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &ab);
1469
1470     ppfd->cRedBits = rb;
1471     ppfd->cRedShift = gb + bb + ab;
1472     ppfd->cBlueBits = bb;
1473     ppfd->cBlueShift = ab;
1474     ppfd->cGreenBits = gb;
1475     ppfd->cGreenShift = bb + ab;
1476     ppfd->cAlphaBits = ab;
1477     ppfd->cAlphaShift = 0;
1478   } else {
1479     ppfd->cRedBits = 0;
1480     ppfd->cRedShift = 0;
1481     ppfd->cBlueBits = 0;
1482     ppfd->cBlueShift = 0;
1483     ppfd->cGreenBits = 0;
1484     ppfd->cGreenShift = 0;
1485     ppfd->cAlphaBits = 0;
1486     ppfd->cAlphaShift = 0;
1487   }
1488
1489   /* Accum RGBA bits */
1490   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &rb);
1491   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &gb);
1492   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &bb);
1493   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &ab);
1494
1495   ppfd->cAccumBits = rb+gb+bb+ab;
1496   ppfd->cAccumRedBits = rb;
1497   ppfd->cAccumGreenBits = gb;
1498   ppfd->cAccumBlueBits = bb;
1499   ppfd->cAccumAlphaBits = ab;
1500
1501   /* Aux bits */
1502   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &value);
1503   ppfd->cAuxBuffers = value;
1504
1505   /* Depth bits */
1506   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &value);
1507   ppfd->cDepthBits = value;
1508
1509   /* stencil bits */
1510   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &value);
1511   ppfd->cStencilBits = value;
1512
1513   wine_tsx11_unlock();
1514
1515   ppfd->iLayerType = PFD_MAIN_PLANE;
1516
1517   if (TRACE_ON(wgl)) {
1518     dump_PIXELFORMATDESCRIPTOR(ppfd);
1519   }
1520
1521   return ret;
1522 }
1523
1524 /**
1525  * X11DRV_GetPixelFormat
1526  *
1527  * Get the pixel-format id used by this DC
1528  */
1529 int X11DRV_GetPixelFormat(PHYSDEV dev)
1530 {
1531   X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
1532   WineGLPixelFormat *fmt;
1533   int tmp;
1534   TRACE("(%p)\n", physDev);
1535
1536   if (!physDev->current_pf) return 0;  /* not set yet */
1537
1538   fmt = ConvertPixelFormatWGLtoGLX(gdi_display, physDev->current_pf, TRUE, &tmp);
1539   if(!fmt)
1540   {
1541     ERR("Unable to find a WineGLPixelFormat for iPixelFormat=%d\n", physDev->current_pf);
1542     return 0;
1543   }
1544   else if(fmt->offscreenOnly)
1545   {
1546     /* Offscreen formats can't be used with traditional WGL calls.
1547      * As has been verified on Windows GetPixelFormat doesn't fail but returns iPixelFormat=1. */
1548      TRACE("Returning iPixelFormat=1 for offscreen format: %d\n", fmt->iPixelFormat);
1549     return 1;
1550   }
1551
1552   TRACE("(%p): returns %d\n", physDev, physDev->current_pf);
1553   return physDev->current_pf;
1554 }
1555
1556 /* This function is the core of X11DRV_SetPixelFormat and X11DRV_SetPixelFormatWINE.
1557  * Both functions are the same except that X11DRV_SetPixelFormatWINE allows you to
1558  * set the pixel format multiple times. */
1559 static BOOL internal_SetPixelFormat(X11DRV_PDEVICE *physDev,
1560                            int iPixelFormat,
1561                            const PIXELFORMATDESCRIPTOR *ppfd) {
1562     WineGLPixelFormat *fmt;
1563     int value;
1564     HWND hwnd;
1565
1566     /* SetPixelFormat is not allowed on the X root_window e.g. GetDC(0) */
1567     if(physDev->drawable == root_window)
1568     {
1569         ERR("Invalid operation on root_window\n");
1570         return FALSE;
1571     }
1572
1573     /* Check if iPixelFormat is in our list of supported formats to see if it is supported. */
1574     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &value);
1575     if(!fmt) {
1576         ERR("Invalid iPixelFormat: %d\n", iPixelFormat);
1577         return FALSE;
1578     }
1579
1580     wine_tsx11_lock();
1581     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1582     wine_tsx11_unlock();
1583
1584     hwnd = WindowFromDC(physDev->dev.hdc);
1585     if(hwnd) {
1586         if(!(value&GLX_WINDOW_BIT)) {
1587             WARN("Pixel format %d is not compatible for window rendering\n", iPixelFormat);
1588             return FALSE;
1589         }
1590
1591         if(!SendMessageW(hwnd, WM_X11DRV_SET_WIN_FORMAT, fmt->fmt_id, 0)) {
1592             ERR("Couldn't set format of the window, returning failure\n");
1593             return FALSE;
1594         }
1595         /* physDev->current_pf will be set by the DCE update */
1596     }
1597     else if(physDev->bitmap) {
1598         if(!(value&GLX_PIXMAP_BIT)) {
1599             WARN("Pixel format %d is not compatible for bitmap rendering\n", iPixelFormat);
1600             return FALSE;
1601         }
1602
1603         physDev->bitmap->glxpixmap = create_bitmap_glxpixmap(physDev, fmt);
1604         if(!physDev->bitmap->glxpixmap) {
1605             WARN("Couldn't create glxpixmap for pixel format %d\n", iPixelFormat);
1606             return FALSE;
1607         }
1608         physDev->current_pf = iPixelFormat;
1609         physDev->gl_type = DC_GL_BITMAP;
1610     }
1611     else {
1612         FIXME("called on a non-window, non-bitmap object?\n");
1613     }
1614
1615     if (TRACE_ON(wgl)) {
1616         int gl_test = 0;
1617
1618         wine_tsx11_lock();
1619         gl_test = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_FBCONFIG_ID, &value);
1620         if (gl_test) {
1621            ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
1622         } else {
1623             TRACE(" FBConfig have :\n");
1624             TRACE(" - FBCONFIG_ID   0x%x\n", value);
1625             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &value);
1626             TRACE(" - VISUAL_ID     0x%x\n", value);
1627             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1628             TRACE(" - DRAWABLE_TYPE 0x%x\n", value);
1629         }
1630         wine_tsx11_unlock();
1631     }
1632     return TRUE;
1633 }
1634
1635
1636 /**
1637  * X11DRV_SetPixelFormat
1638  *
1639  * Set the pixel-format id used by this DC
1640  */
1641 BOOL X11DRV_SetPixelFormat(PHYSDEV dev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
1642 {
1643     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
1644
1645     TRACE("(%p,%d,%p)\n", physDev, iPixelFormat, ppfd);
1646
1647     if (!has_opengl()) return FALSE;
1648
1649     if(physDev->current_pf)  /* cannot change it if already set */
1650         return (physDev->current_pf == iPixelFormat);
1651
1652     return internal_SetPixelFormat(physDev, iPixelFormat, ppfd);
1653 }
1654
1655 /**
1656  * X11DRV_wglCopyContext
1657  *
1658  * For OpenGL32 wglCopyContext.
1659  */
1660 BOOL X11DRV_wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask)
1661 {
1662     Wine_GLContext *src = (Wine_GLContext*)hglrcSrc;
1663     Wine_GLContext *dst = (Wine_GLContext*)hglrcDst;
1664
1665     TRACE("hglrcSrc: (%p), hglrcDst: (%p), mask: %#x\n", hglrcSrc, hglrcDst, mask);
1666
1667     wine_tsx11_lock();
1668     pglXCopyContext(gdi_display, src->ctx, dst->ctx, mask);
1669     wine_tsx11_unlock();
1670
1671     /* As opposed to wglCopyContext, glXCopyContext doesn't return anything, so hopefully we passed */
1672     return TRUE;
1673 }
1674
1675 /**
1676  * X11DRV_wglCreateContext
1677  *
1678  * For OpenGL32 wglCreateContext.
1679  */
1680 HGLRC X11DRV_wglCreateContext(PHYSDEV dev)
1681 {
1682     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
1683     Wine_GLContext *ret;
1684     WineGLPixelFormat *fmt;
1685     int hdcPF = physDev->current_pf;
1686     int fmt_count = 0;
1687     HDC hdc = dev->hdc;
1688
1689     TRACE("(%p)->(PF:%d)\n", hdc, hdcPF);
1690
1691     if (!has_opengl()) return 0;
1692
1693     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, hdcPF, TRUE /* Offscreen */, &fmt_count);
1694     /* We can render using the iPixelFormat (1) of Wine's Main visual AND using some offscreen formats.
1695      * Note that standard WGL-calls don't recognize offscreen-only formats. For that reason pbuffers
1696      * use a sort of 'proxy' HDC (wglGetPbufferDCARB).
1697      * If this fails something is very wrong on the system. */
1698     if(!fmt) {
1699         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", hdcPF);
1700         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
1701         return NULL;
1702     }
1703
1704     if (!(ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret)))) return 0;
1705
1706     ret->hdc = hdc;
1707     ret->fmt = fmt;
1708     ret->has_been_current = FALSE;
1709     ret->sharing = FALSE;
1710
1711     wine_tsx11_lock();
1712     ret->vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
1713     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
1714     list_add_head( &context_list, &ret->entry );
1715     wine_tsx11_unlock();
1716
1717     TRACE(" creating context %p (GL context creation delayed)\n", ret);
1718     return (HGLRC) ret;
1719 }
1720
1721 /**
1722  * X11DRV_wglDeleteContext
1723  *
1724  * For OpenGL32 wglDeleteContext.
1725  */
1726 BOOL X11DRV_wglDeleteContext(HGLRC hglrc)
1727 {
1728     Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1729
1730     TRACE("(%p)\n", hglrc);
1731
1732     if (!has_opengl()) return 0;
1733
1734     if (!is_valid_context(ctx))
1735     {
1736         WARN("Error deleting context !\n");
1737         SetLastError(ERROR_INVALID_HANDLE);
1738         return FALSE;
1739     }
1740
1741     /* WGL doesn't allow deletion of a context which is current in another thread */
1742     if (ctx->tid != 0 && ctx->tid != GetCurrentThreadId())
1743     {
1744         TRACE("Cannot delete context=%p because it is current in another thread.\n", ctx);
1745         SetLastError(ERROR_BUSY);
1746         return FALSE;
1747     }
1748
1749     /* WGL makes a context not current if it is active before deletion. GLX waits until the context is not current. */
1750     if (ctx == NtCurrentTeb()->glContext)
1751         wglMakeCurrent(ctx->hdc, NULL);
1752
1753     wine_tsx11_lock();
1754     list_remove( &ctx->entry );
1755     if (ctx->ctx) pglXDestroyContext( gdi_display, ctx->ctx );
1756     if (ctx->vis) XFree( ctx->vis );
1757     wine_tsx11_unlock();
1758
1759     HeapFree( GetProcessHeap(), 0, ctx );
1760     return TRUE;
1761 }
1762
1763 /**
1764  * X11DRV_wglGetCurrentReadDCARB
1765  *
1766  * For OpenGL32 wglGetCurrentReadDCARB.
1767  */
1768 static HDC WINAPI X11DRV_wglGetCurrentReadDCARB(void) 
1769 {
1770     HDC ret = 0;
1771     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
1772
1773     if (ctx) ret = ctx->read_hdc;
1774
1775     TRACE(" returning %p (GL drawable %lu)\n", ret, ctx ? ctx->drawables[1] : 0);
1776     return ret;
1777 }
1778
1779 /**
1780  * X11DRV_wglGetProcAddress
1781  *
1782  * For OpenGL32 wglGetProcAddress.
1783  */
1784 PROC X11DRV_wglGetProcAddress(LPCSTR lpszProc)
1785 {
1786     int i, j;
1787     const WineGLExtension *ext;
1788
1789     int padding = 32 - strlen(lpszProc);
1790     if (padding < 0)
1791         padding = 0;
1792
1793     if (!has_opengl()) return NULL;
1794
1795     /* Check the table of WGL extensions to see if we need to return a WGL extension
1796      * or a function pointer to a native OpenGL function. */
1797     if(strncmp(lpszProc, "wgl", 3) != 0) {
1798         return pglXGetProcAddressARB((const GLubyte*)lpszProc);
1799     } else {
1800         TRACE("('%s'):%*s", lpszProc, padding, " ");
1801         for (i = 0; i < WineGLExtensionListSize; ++i) {
1802             ext = WineGLExtensionList[i];
1803             for (j = 0; ext->extEntryPoints[j].funcName; ++j) {
1804                 if (strcmp(ext->extEntryPoints[j].funcName, lpszProc) == 0) {
1805                     TRACE("(%p) - WineGL\n", ext->extEntryPoints[j].funcAddress);
1806                     return ext->extEntryPoints[j].funcAddress;
1807                 }
1808             }
1809         }
1810     }
1811
1812     WARN("(%s) - not found\n", lpszProc);
1813     return NULL;
1814 }
1815
1816 /**
1817  * X11DRV_wglMakeCurrent
1818  *
1819  * For OpenGL32 wglMakeCurrent.
1820  */
1821 BOOL X11DRV_wglMakeCurrent(PHYSDEV dev, HGLRC hglrc)
1822 {
1823     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
1824     BOOL ret;
1825     HDC hdc = dev->hdc;
1826     Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1827
1828     TRACE("(%p,%p)\n", hdc, hglrc);
1829
1830     if (!has_opengl()) return FALSE;
1831
1832     wine_tsx11_lock();
1833     if (hglrc == NULL)
1834     {
1835         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1836         if (prev_ctx) prev_ctx->tid = 0;
1837
1838         ret = pglXMakeCurrent(gdi_display, None, NULL);
1839         NtCurrentTeb()->glContext = NULL;
1840     }
1841     else if (!physDev->current_pf)
1842     {
1843         WARN("Trying to use an invalid drawable\n");
1844         SetLastError(ERROR_INVALID_HANDLE);
1845         ret = FALSE;
1846     }
1847     else if (ctx->fmt->iPixelFormat != physDev->current_pf)
1848     {
1849         WARN( "mismatched pixel format hdc %p %u ctx %p %u\n",
1850               hdc, physDev->current_pf, ctx, ctx->fmt->iPixelFormat );
1851         SetLastError( ERROR_INVALID_PIXEL_FORMAT );
1852         ret = FALSE;
1853     }
1854     else
1855     {
1856         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1857
1858         /* The describe lines below are for debugging purposes only */
1859         if (TRACE_ON(wgl)) {
1860             describeDrawable(physDev);
1861             describeContext(ctx);
1862         }
1863
1864         TRACE(" make current for drawable %lx, ctx %p\n", physDev->gl_drawable, ctx->ctx);
1865         ret = pglXMakeCurrent(gdi_display, physDev->gl_drawable, ctx->ctx);
1866
1867         if (ret)
1868         {
1869             if (prev_ctx) prev_ctx->tid = 0;
1870             NtCurrentTeb()->glContext = ctx;
1871
1872             ctx->has_been_current = TRUE;
1873             ctx->tid = GetCurrentThreadId();
1874             ctx->hdc = hdc;
1875             ctx->read_hdc = hdc;
1876             ctx->drawables[0] = physDev->gl_drawable;
1877             ctx->drawables[1] = physDev->gl_drawable;
1878             ctx->refresh_drawables = FALSE;
1879
1880             if (physDev->gl_type == DC_GL_BITMAP) pglDrawBuffer(GL_FRONT_LEFT);
1881         }
1882         else
1883             SetLastError(ERROR_INVALID_HANDLE);
1884     }
1885     wine_tsx11_unlock();
1886     TRACE(" returning %s\n", (ret ? "True" : "False"));
1887     return ret;
1888 }
1889
1890 /**
1891  * X11DRV_wglMakeContextCurrentARB
1892  *
1893  * For OpenGL32 wglMakeContextCurrentARB
1894  */
1895 BOOL X11DRV_wglMakeContextCurrentARB( PHYSDEV draw_dev, PHYSDEV read_dev, HGLRC hglrc )
1896 {
1897     X11DRV_PDEVICE *pDrawDev = get_x11drv_dev( draw_dev );
1898     X11DRV_PDEVICE *pReadDev = get_x11drv_dev( read_dev );
1899     BOOL ret;
1900
1901     TRACE("(%p,%p,%p)\n", pDrawDev, pReadDev, hglrc);
1902
1903     if (!has_opengl()) return 0;
1904
1905     wine_tsx11_lock();
1906     if (hglrc == NULL)
1907     {
1908         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1909         if (prev_ctx) prev_ctx->tid = 0;
1910
1911         ret = pglXMakeCurrent(gdi_display, None, NULL);
1912         NtCurrentTeb()->glContext = NULL;
1913     }
1914     else if (!pDrawDev->current_pf)
1915     {
1916         WARN("Trying to use an invalid drawable\n");
1917         SetLastError(ERROR_INVALID_HANDLE);
1918         ret = FALSE;
1919     }
1920     else
1921     {
1922         if (NULL == pglXMakeContextCurrent) {
1923             ret = FALSE;
1924         } else {
1925             Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1926
1927             ret = pglXMakeContextCurrent(gdi_display, pDrawDev->gl_drawable, pReadDev->gl_drawable, ctx->ctx);
1928             if (ret)
1929             {
1930                 Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1931                 if (prev_ctx) prev_ctx->tid = 0;
1932
1933                 ctx->has_been_current = TRUE;
1934                 ctx->tid = GetCurrentThreadId();
1935                 ctx->hdc = draw_dev->hdc;
1936                 ctx->read_hdc = read_dev->hdc;
1937                 ctx->drawables[0] = pDrawDev->gl_drawable;
1938                 ctx->drawables[1] = pReadDev->gl_drawable;
1939                 ctx->refresh_drawables = FALSE;
1940                 NtCurrentTeb()->glContext = ctx;
1941             }
1942             else
1943                 SetLastError(ERROR_INVALID_HANDLE);
1944         }
1945     }
1946     wine_tsx11_unlock();
1947
1948     TRACE(" returning %s\n", (ret ? "True" : "False"));
1949     return ret;
1950 }
1951
1952 /**
1953  * X11DRV_wglShareLists
1954  *
1955  * For OpenGL32 wglShareLists.
1956  */
1957 BOOL X11DRV_wglShareLists(HGLRC hglrc1, HGLRC hglrc2)
1958 {
1959     Wine_GLContext *org  = (Wine_GLContext *) hglrc1;
1960     Wine_GLContext *dest = (Wine_GLContext *) hglrc2;
1961
1962     TRACE("(%p, %p)\n", org, dest);
1963
1964     if (!has_opengl()) return FALSE;
1965
1966     /* Sharing of display lists works differently in GLX and WGL. In case of GLX it is done
1967      * at context creation time but in case of WGL it is done using wglShareLists.
1968      * In the past we tried to emulate wglShareLists by delaying GLX context creation until
1969      * either a wglMakeCurrent or wglShareLists. This worked fine for most apps but it causes
1970      * issues for OpenGL 3 because there wglCreateContextAttribsARB can fail in a lot of cases,
1971      * so there delaying context creation doesn't work.
1972      *
1973      * The new approach is to create a GLX context in wglCreateContext / wglCreateContextAttribsARB
1974      * and when a program requests sharing we recreate the destination context if it hasn't been made
1975      * current or when it hasn't shared display lists before.
1976      */
1977
1978     if((org->has_been_current && dest->has_been_current) || dest->has_been_current)
1979     {
1980         ERR("Could not share display lists, one of the contexts has been current already !\n");
1981         return FALSE;
1982     }
1983     else if(dest->sharing)
1984     {
1985         ERR("Could not share display lists because hglrc2 has already shared lists before\n");
1986         return FALSE;
1987     }
1988     else
1989     {
1990         if((GetObjectType(org->hdc) == OBJ_MEMDC) ^ (GetObjectType(dest->hdc) == OBJ_MEMDC))
1991         {
1992             WARN("Attempting to share a context between a direct and indirect rendering context, expect issues!\n");
1993         }
1994
1995         wine_tsx11_lock();
1996         describeContext(org);
1997         describeContext(dest);
1998
1999         /* Re-create the GLX context and share display lists */
2000         pglXDestroyContext(gdi_display, dest->ctx);
2001         dest->ctx = create_glxcontext(gdi_display, dest, org->ctx);
2002         wine_tsx11_unlock();
2003         TRACE(" re-created an OpenGL context (%p) for Wine context %p sharing lists with OpenGL ctx %p\n", dest->ctx, dest, org->ctx);
2004
2005         org->sharing = TRUE;
2006         dest->sharing = TRUE;
2007         return TRUE;
2008     }
2009     return FALSE;
2010 }
2011
2012 static BOOL internal_wglUseFontBitmaps(HDC hdc, DWORD first, DWORD count, DWORD listBase, DWORD (WINAPI *GetGlyphOutline_ptr)(HDC,UINT,UINT,LPGLYPHMETRICS,DWORD,LPVOID,const MAT2*))
2013 {
2014      /* We are running using client-side rendering fonts... */
2015      GLYPHMETRICS gm;
2016      unsigned int glyph, size = 0;
2017      void *bitmap = NULL, *gl_bitmap = NULL;
2018      int org_alignment;
2019
2020      wine_tsx11_lock();
2021      pglGetIntegerv(GL_UNPACK_ALIGNMENT, &org_alignment);
2022      pglPixelStorei(GL_UNPACK_ALIGNMENT, 4);
2023      wine_tsx11_unlock();
2024
2025      for (glyph = first; glyph < first + count; glyph++) {
2026          static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
2027          unsigned int needed_size = GetGlyphOutline_ptr(hdc, glyph, GGO_BITMAP, &gm, 0, NULL, &identity);
2028          unsigned int height, width_int;
2029
2030          TRACE("Glyph : %3d / List : %d\n", glyph, listBase);
2031          if (needed_size == GDI_ERROR) {
2032              TRACE("  - needed size : %d (GDI_ERROR)\n", needed_size);
2033              goto error;
2034          } else {
2035              TRACE("  - needed size : %d\n", needed_size);
2036          }
2037
2038          if (needed_size > size) {
2039              size = needed_size;
2040              HeapFree(GetProcessHeap(), 0, bitmap);
2041              HeapFree(GetProcessHeap(), 0, gl_bitmap);
2042              bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
2043              gl_bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
2044          }
2045          if (GetGlyphOutline_ptr(hdc, glyph, GGO_BITMAP, &gm, size, bitmap, &identity) == GDI_ERROR)
2046              goto error;
2047          if (TRACE_ON(wgl)) {
2048              unsigned int height, width, bitmask;
2049              unsigned char *bitmap_ = bitmap;
2050
2051              TRACE("  - bbox : %d x %d\n", gm.gmBlackBoxX, gm.gmBlackBoxY);
2052              TRACE("  - origin : (%d , %d)\n", gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
2053              TRACE("  - increment : %d - %d\n", gm.gmCellIncX, gm.gmCellIncY);
2054              if (needed_size != 0) {
2055                  TRACE("  - bitmap :\n");
2056                  for (height = 0; height < gm.gmBlackBoxY; height++) {
2057                      TRACE("      ");
2058                      for (width = 0, bitmask = 0x80; width < gm.gmBlackBoxX; width++, bitmask >>= 1) {
2059                          if (bitmask == 0) {
2060                              bitmap_ += 1;
2061                              bitmask = 0x80;
2062                          }
2063                          if (*bitmap_ & bitmask)
2064                              TRACE("*");
2065                          else
2066                              TRACE(" ");
2067                      }
2068                      bitmap_ += (4 - ((UINT_PTR)bitmap_ & 0x03));
2069                      TRACE("\n");
2070                  }
2071              }
2072          }
2073
2074          /* In OpenGL, the bitmap is drawn from the bottom to the top... So we need to invert the
2075          * glyph for it to be drawn properly.
2076          */
2077          if (needed_size != 0) {
2078              width_int = (gm.gmBlackBoxX + 31) / 32;
2079              for (height = 0; height < gm.gmBlackBoxY; height++) {
2080                  unsigned int width;
2081                  for (width = 0; width < width_int; width++) {
2082                      ((int *) gl_bitmap)[(gm.gmBlackBoxY - height - 1) * width_int + width] =
2083                      ((int *) bitmap)[height * width_int + width];
2084                  }
2085              }
2086          }
2087
2088          wine_tsx11_lock();
2089          pglNewList(listBase++, GL_COMPILE);
2090          if (needed_size != 0) {
2091              pglBitmap(gm.gmBlackBoxX, gm.gmBlackBoxY,
2092                      0 - gm.gmptGlyphOrigin.x, (int) gm.gmBlackBoxY - gm.gmptGlyphOrigin.y,
2093                      gm.gmCellIncX, gm.gmCellIncY,
2094                      gl_bitmap);
2095          } else {
2096              /* This is the case of 'empty' glyphs like the space character */
2097              pglBitmap(0, 0, 0, 0, gm.gmCellIncX, gm.gmCellIncY, NULL);
2098          }
2099          pglEndList();
2100          wine_tsx11_unlock();
2101      }
2102
2103      wine_tsx11_lock();
2104      pglPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
2105      wine_tsx11_unlock();
2106
2107      HeapFree(GetProcessHeap(), 0, bitmap);
2108      HeapFree(GetProcessHeap(), 0, gl_bitmap);
2109      return TRUE;
2110
2111   error:
2112      wine_tsx11_lock();
2113      pglPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
2114      wine_tsx11_unlock();
2115
2116      HeapFree(GetProcessHeap(), 0, bitmap);
2117      HeapFree(GetProcessHeap(), 0, gl_bitmap);
2118      return FALSE;
2119 }
2120
2121 /**
2122  * X11DRV_wglUseFontBitmapsA
2123  *
2124  * For OpenGL32 wglUseFontBitmapsA.
2125  */
2126 BOOL X11DRV_wglUseFontBitmapsA(PHYSDEV dev, DWORD first, DWORD count, DWORD listBase)
2127 {
2128      TRACE("(%p, %d, %d, %d)\n", dev->hdc, first, count, listBase);
2129
2130      if (!has_opengl()) return FALSE;
2131      return internal_wglUseFontBitmaps(dev->hdc, first, count, listBase, GetGlyphOutlineA);
2132 }
2133
2134 /**
2135  * X11DRV_wglUseFontBitmapsW
2136  *
2137  * For OpenGL32 wglUseFontBitmapsW.
2138  */
2139 BOOL X11DRV_wglUseFontBitmapsW(PHYSDEV dev, DWORD first, DWORD count, DWORD listBase)
2140 {
2141      TRACE("(%p, %d, %d, %d)\n", dev->hdc, first, count, listBase);
2142
2143      if (!has_opengl()) return FALSE;
2144      return internal_wglUseFontBitmaps(dev->hdc, first, count, listBase, GetGlyphOutlineW);
2145 }
2146
2147 /* WGL helper function which handles differences in glGetIntegerv from WGL and GLX */
2148 static void WINAPI X11DRV_wglGetIntegerv(GLenum pname, GLint* params)
2149 {
2150     wine_tsx11_lock();
2151     switch(pname)
2152     {
2153     case GL_DEPTH_BITS:
2154         {
2155             Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2156
2157             pglGetIntegerv(pname, params);
2158             /**
2159              * if we cannot find a Wine Context
2160              * we only have the default wine desktop context,
2161              * so if we have only a 24 depth say we have 32
2162              */
2163             if (!ctx && *params == 24) {
2164                 *params = 32;
2165             }
2166             TRACE("returns GL_DEPTH_BITS as '%d'\n", *params);
2167             break;
2168         }
2169     case GL_ALPHA_BITS:
2170         {
2171             Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2172
2173             pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_ALPHA_SIZE, params);
2174             TRACE("returns GL_ALPHA_BITS as '%d'\n", *params);
2175             break;
2176         }
2177     default:
2178         pglGetIntegerv(pname, params);
2179         break;
2180     }
2181     wine_tsx11_unlock();
2182 }
2183
2184 void flush_gl_drawable(X11DRV_PDEVICE *physDev)
2185 {
2186     RECT rect;
2187     int w = physDev->dc_rect.right - physDev->dc_rect.left;
2188     int h = physDev->dc_rect.bottom - physDev->dc_rect.top;
2189     Drawable src = physDev->gl_drawable;
2190
2191     if (w <= 0 || h <= 0) return;
2192
2193     switch (physDev->gl_type)
2194     {
2195     case DC_GL_PIXMAP_WIN:
2196         src = physDev->pixmap;
2197         /* fall through */
2198     case DC_GL_CHILD_WIN:
2199         /* The GL drawable may be lagged behind if we don't flush first, so
2200          * flush the display make sure we copy up-to-date data */
2201         wine_tsx11_lock();
2202         XFlush(gdi_display);
2203         XSetFunction(gdi_display, physDev->gc, GXcopy);
2204         XCopyArea(gdi_display, src, physDev->drawable, physDev->gc, 0, 0, w, h,
2205                   physDev->dc_rect.left, physDev->dc_rect.top);
2206         wine_tsx11_unlock();
2207         SetRect( &rect, 0, 0, w, h );
2208         add_device_bounds( physDev, &rect );
2209     default:
2210         break;
2211     }
2212 }
2213
2214
2215 static void WINAPI X11DRV_wglFinish(void)
2216 {
2217     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2218     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
2219
2220     wine_tsx11_lock();
2221     sync_context(ctx);
2222     pglFinish();
2223     wine_tsx11_unlock();
2224     if (ctx) ExtEscape(ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
2225 }
2226
2227 static void WINAPI X11DRV_wglFlush(void)
2228 {
2229     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2230     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
2231
2232     wine_tsx11_lock();
2233     sync_context(ctx);
2234     pglFlush();
2235     wine_tsx11_unlock();
2236     if (ctx) ExtEscape(ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
2237 }
2238
2239 /**
2240  * X11DRV_wglCreateContextAttribsARB
2241  *
2242  * WGL_ARB_create_context: wglCreateContextAttribsARB
2243  */
2244 HGLRC X11DRV_wglCreateContextAttribsARB(PHYSDEV dev, HGLRC hShareContext, const int* attribList)
2245 {
2246     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
2247     Wine_GLContext *ret;
2248     WineGLPixelFormat *fmt;
2249     int hdcPF = physDev->current_pf;
2250     int fmt_count = 0;
2251
2252     TRACE("(%p %p %p)\n", physDev, hShareContext, attribList);
2253
2254     if (!has_opengl()) return 0;
2255
2256     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, hdcPF, TRUE /* Offscreen */, &fmt_count);
2257     /* wglCreateContextAttribsARB supports ALL pixel formats, so also offscreen ones.
2258      * If this fails something is very wrong on the system. */
2259     if(!fmt)
2260     {
2261         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", hdcPF);
2262         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2263         return NULL;
2264     }
2265
2266     if (!(ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret)))) return 0;
2267
2268     ret->hdc = dev->hdc;
2269     ret->fmt = fmt;
2270     ret->vis = NULL; /* glXCreateContextAttribsARB requires a fbconfig instead of a visual */
2271     ret->gl3_context = TRUE;
2272
2273     ret->numAttribs = 0;
2274     if(attribList)
2275     {
2276         int *pAttribList = (int*)attribList;
2277         int *pContextAttribList = &ret->attribList[0];
2278         /* attribList consists of pairs {token, value] terminated with 0 */
2279         while(pAttribList[0] != 0)
2280         {
2281             TRACE("%#x %#x\n", pAttribList[0], pAttribList[1]);
2282             switch(pAttribList[0])
2283             {
2284                 case WGL_CONTEXT_MAJOR_VERSION_ARB:
2285                     pContextAttribList[0] = GLX_CONTEXT_MAJOR_VERSION_ARB;
2286                     pContextAttribList[1] = pAttribList[1];
2287                     break;
2288                 case WGL_CONTEXT_MINOR_VERSION_ARB:
2289                     pContextAttribList[0] = GLX_CONTEXT_MINOR_VERSION_ARB;
2290                     pContextAttribList[1] = pAttribList[1];
2291                     break;
2292                 case WGL_CONTEXT_LAYER_PLANE_ARB:
2293                     break;
2294                 case WGL_CONTEXT_FLAGS_ARB:
2295                     pContextAttribList[0] = GLX_CONTEXT_FLAGS_ARB;
2296                     pContextAttribList[1] = pAttribList[1];
2297                     break;
2298                 case WGL_CONTEXT_PROFILE_MASK_ARB:
2299                     pContextAttribList[0] = GLX_CONTEXT_PROFILE_MASK_ARB;
2300                     pContextAttribList[1] = pAttribList[1];
2301                     break;
2302                 default:
2303                     ERR("Unhandled attribList pair: %#x %#x\n", pAttribList[0], pAttribList[1]);
2304             }
2305
2306             ret->numAttribs++;
2307             pAttribList += 2;
2308             pContextAttribList += 2;
2309         }
2310     }
2311
2312     wine_tsx11_lock();
2313     X11DRV_expect_error(gdi_display, GLXErrorHandler, NULL);
2314     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
2315
2316     XSync(gdi_display, False);
2317     if(X11DRV_check_error() || !ret->ctx)
2318     {
2319         /* In the future we should convert the GLX error to a win32 one here if needed */
2320         ERR("Context creation failed\n");
2321         HeapFree( GetProcessHeap(), 0, ret );
2322         wine_tsx11_unlock();
2323         return NULL;
2324     }
2325
2326     list_add_head( &context_list, &ret->entry );
2327     wine_tsx11_unlock();
2328     TRACE(" creating context %p\n", ret);
2329     return (HGLRC) ret;
2330 }
2331
2332 /**
2333  * X11DRV_wglGetExtensionsStringARB
2334  *
2335  * WGL_ARB_extensions_string: wglGetExtensionsStringARB
2336  */
2337 static const char * WINAPI X11DRV_wglGetExtensionsStringARB(HDC hdc) {
2338     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
2339     return WineGLInfo.wglExtensions;
2340 }
2341
2342 /**
2343  * X11DRV_wglCreatePbufferARB
2344  *
2345  * WGL_ARB_pbuffer: wglCreatePbufferARB
2346  */
2347 static HPBUFFERARB WINAPI X11DRV_wglCreatePbufferARB(HDC hdc, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList)
2348 {
2349     Wine_GLPBuffer* object = NULL;
2350     WineGLPixelFormat *fmt = NULL;
2351     int nCfgs = 0;
2352     int attribs[256];
2353     int nAttribs = 0;
2354
2355     TRACE("(%p, %d, %d, %d, %p)\n", hdc, iPixelFormat, iWidth, iHeight, piAttribList);
2356
2357     if (0 >= iPixelFormat) {
2358         ERR("(%p): unexpected iPixelFormat(%d) <= 0, returns NULL\n", hdc, iPixelFormat);
2359         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2360         return NULL; /* unexpected error */
2361     }
2362
2363     /* Convert the WGL pixelformat to a GLX format, if it fails then the format is invalid */
2364     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nCfgs);
2365     if(!fmt) {
2366         ERR("(%p): unexpected iPixelFormat(%d) > nFormats(%d), returns NULL\n", hdc, iPixelFormat, nCfgs);
2367         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2368         goto create_failed; /* unexpected error */
2369     }
2370
2371     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Wine_GLPBuffer));
2372     if (NULL == object) {
2373         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2374         goto create_failed; /* unexpected error */
2375     }
2376     object->hdc = hdc;
2377     object->display = gdi_display;
2378     object->width = iWidth;
2379     object->height = iHeight;
2380     object->fmt = fmt;
2381
2382     PUSH2(attribs, GLX_PBUFFER_WIDTH,  iWidth);
2383     PUSH2(attribs, GLX_PBUFFER_HEIGHT, iHeight); 
2384     while (piAttribList && 0 != *piAttribList) {
2385         int attr_v;
2386         switch (*piAttribList) {
2387             case WGL_PBUFFER_LARGEST_ARB: {
2388                 ++piAttribList;
2389                 attr_v = *piAttribList;
2390                 TRACE("WGL_LARGEST_PBUFFER_ARB = %d\n", attr_v);
2391                 PUSH2(attribs, GLX_LARGEST_PBUFFER, attr_v);
2392                 break;
2393             }
2394
2395             case WGL_TEXTURE_FORMAT_ARB: {
2396                 ++piAttribList;
2397                 attr_v = *piAttribList;
2398                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_FORMAT_ARB as %x\n", attr_v);
2399                 if (use_render_texture_ati) {
2400                     int type = 0;
2401                     switch (attr_v) {
2402                         case WGL_NO_TEXTURE_ARB: type = GLX_NO_TEXTURE_ATI; break ;
2403                         case WGL_TEXTURE_RGB_ARB: type = GLX_TEXTURE_RGB_ATI; break ;
2404                         case WGL_TEXTURE_RGBA_ARB: type = GLX_TEXTURE_RGBA_ATI; break ;
2405                         default:
2406                             SetLastError(ERROR_INVALID_DATA);
2407                             goto create_failed;
2408                     }
2409                     object->use_render_texture = 1;
2410                     PUSH2(attribs, GLX_TEXTURE_FORMAT_ATI, type);
2411                 } else {
2412                     if (WGL_NO_TEXTURE_ARB == attr_v) {
2413                         object->use_render_texture = 0;
2414                     } else {
2415                         if (!use_render_texture_emulation) {
2416                             SetLastError(ERROR_INVALID_DATA);
2417                             goto create_failed;
2418                         }
2419                         switch (attr_v) {
2420                             case WGL_TEXTURE_RGB_ARB:
2421                                 object->use_render_texture = GL_RGB;
2422                                 object->texture_bpp = 3;
2423                                 object->texture_format = GL_RGB;
2424                                 object->texture_type = GL_UNSIGNED_BYTE;
2425                                 break;
2426                             case WGL_TEXTURE_RGBA_ARB:
2427                                 object->use_render_texture = GL_RGBA;
2428                                 object->texture_bpp = 4;
2429                                 object->texture_format = GL_RGBA;
2430                                 object->texture_type = GL_UNSIGNED_BYTE;
2431                                 break;
2432
2433                             /* WGL_FLOAT_COMPONENTS_NV */
2434                             case WGL_TEXTURE_FLOAT_R_NV:
2435                                 object->use_render_texture = GL_FLOAT_R_NV;
2436                                 object->texture_bpp = 4;
2437                                 object->texture_format = GL_RED;
2438                                 object->texture_type = GL_FLOAT;
2439                                 break;
2440                             case WGL_TEXTURE_FLOAT_RG_NV:
2441                                 object->use_render_texture = GL_FLOAT_RG_NV;
2442                                 object->texture_bpp = 8;
2443                                 object->texture_format = GL_LUMINANCE_ALPHA;
2444                                 object->texture_type = GL_FLOAT;
2445                                 break;
2446                             case WGL_TEXTURE_FLOAT_RGB_NV:
2447                                 object->use_render_texture = GL_FLOAT_RGB_NV;
2448                                 object->texture_bpp = 12;
2449                                 object->texture_format = GL_RGB;
2450                                 object->texture_type = GL_FLOAT;
2451                                 break;
2452                             case WGL_TEXTURE_FLOAT_RGBA_NV:
2453                                 object->use_render_texture = GL_FLOAT_RGBA_NV;
2454                                 object->texture_bpp = 16;
2455                                 object->texture_format = GL_RGBA;
2456                                 object->texture_type = GL_FLOAT;
2457                                 break;
2458                             default:
2459                                 ERR("Unknown texture format: %x\n", attr_v);
2460                                 SetLastError(ERROR_INVALID_DATA);
2461                                 goto create_failed;
2462                         }
2463                     }
2464                 }
2465                 break;
2466             }
2467
2468             case WGL_TEXTURE_TARGET_ARB: {
2469                 ++piAttribList;
2470                 attr_v = *piAttribList;
2471                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_TARGET_ARB as %x\n", attr_v);
2472                 if (use_render_texture_ati) {
2473                     int type = 0;
2474                     switch (attr_v) {
2475                         case WGL_NO_TEXTURE_ARB: type = GLX_NO_TEXTURE_ATI; break ;
2476                         case WGL_TEXTURE_CUBE_MAP_ARB: type = GLX_TEXTURE_CUBE_MAP_ATI; break ;
2477                         case WGL_TEXTURE_1D_ARB: type = GLX_TEXTURE_1D_ATI; break ;
2478                         case WGL_TEXTURE_2D_ARB: type = GLX_TEXTURE_2D_ATI; break ;
2479                         default:
2480                             SetLastError(ERROR_INVALID_DATA);
2481                             goto create_failed;
2482                     }
2483                     PUSH2(attribs, GLX_TEXTURE_TARGET_ATI, type);
2484                 } else {
2485                     if (WGL_NO_TEXTURE_ARB == attr_v) {
2486                         object->texture_target = 0;
2487                     } else {
2488                         if (!use_render_texture_emulation) {
2489                             SetLastError(ERROR_INVALID_DATA);
2490                             goto create_failed;
2491                         }
2492                         switch (attr_v) {
2493                             case WGL_TEXTURE_CUBE_MAP_ARB: {
2494                                 if (iWidth != iHeight) {
2495                                     SetLastError(ERROR_INVALID_DATA);
2496                                     goto create_failed;
2497                                 }
2498                                 object->texture_target = GL_TEXTURE_CUBE_MAP;
2499                                 object->texture_bind_target = GL_TEXTURE_BINDING_CUBE_MAP;
2500                                break;
2501                             }
2502                             case WGL_TEXTURE_1D_ARB: {
2503                                 if (1 != iHeight) {
2504                                     SetLastError(ERROR_INVALID_DATA);
2505                                     goto create_failed;
2506                                 }
2507                                 object->texture_target = GL_TEXTURE_1D;
2508                                 object->texture_bind_target = GL_TEXTURE_BINDING_1D;
2509                                 break;
2510                             }
2511                             case WGL_TEXTURE_2D_ARB: {
2512                                 object->texture_target = GL_TEXTURE_2D;
2513                                 object->texture_bind_target = GL_TEXTURE_BINDING_2D;
2514                                 break;
2515                             }
2516                             case WGL_TEXTURE_RECTANGLE_NV: {
2517                                 object->texture_target = GL_TEXTURE_RECTANGLE_NV;
2518                                 object->texture_bind_target = GL_TEXTURE_BINDING_RECTANGLE_NV;
2519                                 break;
2520                             }
2521                             default:
2522                                 ERR("Unknown texture target: %x\n", attr_v);
2523                                 SetLastError(ERROR_INVALID_DATA);
2524                                 goto create_failed;
2525                         }
2526                     }
2527                 }
2528                 break;
2529             }
2530
2531             case WGL_MIPMAP_TEXTURE_ARB: {
2532                 ++piAttribList;
2533                 attr_v = *piAttribList;
2534                 TRACE("WGL_render_texture Attribute: WGL_MIPMAP_TEXTURE_ARB as %x\n", attr_v);
2535                 if (use_render_texture_ati) {
2536                     PUSH2(attribs, GLX_MIPMAP_TEXTURE_ATI, attr_v);
2537                 } else {
2538                     if (!use_render_texture_emulation) {
2539                         SetLastError(ERROR_INVALID_DATA);
2540                         goto create_failed;
2541                     }
2542                 }
2543                 break;
2544             }
2545         }
2546         ++piAttribList;
2547     }
2548
2549     PUSH1(attribs, None);
2550     wine_tsx11_lock();
2551     object->drawable = pglXCreatePbuffer(gdi_display, fmt->fbconfig, attribs);
2552     wine_tsx11_unlock();
2553     TRACE("new Pbuffer drawable as %lx\n", object->drawable);
2554     if (!object->drawable) {
2555         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2556         goto create_failed; /* unexpected error */
2557     }
2558     TRACE("->(%p)\n", object);
2559     return object;
2560
2561 create_failed:
2562     HeapFree(GetProcessHeap(), 0, object);
2563     TRACE("->(FAILED)\n");
2564     return NULL;
2565 }
2566
2567 /**
2568  * X11DRV_wglDestroyPbufferARB
2569  *
2570  * WGL_ARB_pbuffer: wglDestroyPbufferARB
2571  */
2572 static GLboolean WINAPI X11DRV_wglDestroyPbufferARB(HPBUFFERARB hPbuffer)
2573 {
2574     Wine_GLPBuffer* object = hPbuffer;
2575     TRACE("(%p)\n", hPbuffer);
2576     if (NULL == object) {
2577         SetLastError(ERROR_INVALID_HANDLE);
2578         return GL_FALSE;
2579     }
2580     wine_tsx11_lock();
2581     pglXDestroyPbuffer(object->display, object->drawable);
2582     wine_tsx11_unlock();
2583     HeapFree(GetProcessHeap(), 0, object);
2584     return GL_TRUE;
2585 }
2586
2587 /**
2588  * X11DRV_wglGetPbufferDCARB
2589  *
2590  * WGL_ARB_pbuffer: wglGetPbufferDCARB
2591  * The function wglGetPbufferDCARB returns a device context for a pbuffer.
2592  * Gdi32 implements the part of this function which creates a device context.
2593  * This part associates the physDev with the X drawable of the pbuffer.
2594  */
2595 HDC X11DRV_wglGetPbufferDCARB(PHYSDEV dev, HPBUFFERARB hPbuffer)
2596 {
2597     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
2598     Wine_GLPBuffer* object = hPbuffer;
2599
2600     if (NULL == object) {
2601         SetLastError(ERROR_INVALID_HANDLE);
2602         return NULL;
2603     }
2604
2605     /* The function wglGetPbufferDCARB returns a DC to which the pbuffer can be connected.
2606      * All formats in our pixelformat list are compatible with each other and the main drawable. */
2607     physDev->current_pf = object->fmt->iPixelFormat;
2608     physDev->drawable = object->drawable;
2609     physDev->gl_drawable = object->drawable;
2610     physDev->gl_type = DC_GL_PBUFFER;
2611     SetRect( &physDev->drawable_rect, 0, 0, object->width, object->height );
2612     physDev->dc_rect = physDev->drawable_rect;
2613
2614     TRACE("(%p)->(%p)\n", hPbuffer, dev->hdc);
2615     return dev->hdc;
2616 }
2617
2618 /**
2619  * X11DRV_wglQueryPbufferARB
2620  *
2621  * WGL_ARB_pbuffer: wglQueryPbufferARB
2622  */
2623 static GLboolean WINAPI X11DRV_wglQueryPbufferARB(HPBUFFERARB hPbuffer, int iAttribute, int *piValue)
2624 {
2625     Wine_GLPBuffer* object = hPbuffer;
2626     TRACE("(%p, 0x%x, %p)\n", hPbuffer, iAttribute, piValue);
2627     if (NULL == object) {
2628         SetLastError(ERROR_INVALID_HANDLE);
2629         return GL_FALSE;
2630     }
2631     switch (iAttribute) {
2632         case WGL_PBUFFER_WIDTH_ARB:
2633             wine_tsx11_lock();
2634             pglXQueryDrawable(object->display, object->drawable, GLX_WIDTH, (unsigned int*) piValue);
2635             wine_tsx11_unlock();
2636             break;
2637         case WGL_PBUFFER_HEIGHT_ARB:
2638             wine_tsx11_lock();
2639             pglXQueryDrawable(object->display, object->drawable, GLX_HEIGHT, (unsigned int*) piValue);
2640             wine_tsx11_unlock();
2641             break;
2642
2643         case WGL_PBUFFER_LOST_ARB:
2644             /* GLX Pbuffers cannot be lost by default. We can support this by
2645              * setting GLX_PRESERVED_CONTENTS to False and using glXSelectEvent
2646              * to receive pixel buffer clobber events, however that may or may
2647              * not give any benefit */
2648             *piValue = GL_FALSE;
2649             break;
2650
2651         case WGL_TEXTURE_FORMAT_ARB:
2652             if (use_render_texture_ati) {
2653                 unsigned int tmp;
2654                 int type = WGL_NO_TEXTURE_ARB;
2655                 wine_tsx11_lock();
2656                 pglXQueryDrawable(object->display, object->drawable, GLX_TEXTURE_FORMAT_ATI, &tmp);
2657                 wine_tsx11_unlock();
2658                 switch (tmp) {
2659                     case GLX_NO_TEXTURE_ATI: type = WGL_NO_TEXTURE_ARB; break ;
2660                     case GLX_TEXTURE_RGB_ATI: type = WGL_TEXTURE_RGB_ARB; break ;
2661                     case GLX_TEXTURE_RGBA_ATI: type = WGL_TEXTURE_RGBA_ARB; break ;
2662                 }
2663                 *piValue = type;
2664             } else {
2665                 if (!object->use_render_texture) {
2666                     *piValue = WGL_NO_TEXTURE_ARB;
2667                 } else {
2668                     if (!use_render_texture_emulation) {
2669                         SetLastError(ERROR_INVALID_HANDLE);
2670                         return GL_FALSE;
2671                     }
2672                     switch(object->use_render_texture) {
2673                         case GL_RGB:
2674                             *piValue = WGL_TEXTURE_RGB_ARB;
2675                             break;
2676                         case GL_RGBA:
2677                             *piValue = WGL_TEXTURE_RGBA_ARB;
2678                             break;
2679                         /* WGL_FLOAT_COMPONENTS_NV */
2680                         case GL_FLOAT_R_NV:
2681                             *piValue = WGL_TEXTURE_FLOAT_R_NV;
2682                             break;
2683                         case GL_FLOAT_RG_NV:
2684                             *piValue = WGL_TEXTURE_FLOAT_RG_NV;
2685                             break;
2686                         case GL_FLOAT_RGB_NV:
2687                             *piValue = WGL_TEXTURE_FLOAT_RGB_NV;
2688                             break;
2689                         case GL_FLOAT_RGBA_NV:
2690                             *piValue = WGL_TEXTURE_FLOAT_RGBA_NV;
2691                             break;
2692                         default:
2693                             ERR("Unknown texture format: %x\n", object->use_render_texture);
2694                     }
2695                 }
2696             }
2697             break;
2698
2699         case WGL_TEXTURE_TARGET_ARB:
2700             if (use_render_texture_ati) {
2701                 unsigned int tmp;
2702                 int type = WGL_NO_TEXTURE_ARB;
2703                 wine_tsx11_lock();
2704                 pglXQueryDrawable(object->display, object->drawable, GLX_TEXTURE_TARGET_ATI, &tmp);
2705                 wine_tsx11_unlock();
2706                 switch (tmp) {
2707                     case GLX_NO_TEXTURE_ATI: type = WGL_NO_TEXTURE_ARB; break ;
2708                     case GLX_TEXTURE_CUBE_MAP_ATI: type = WGL_TEXTURE_CUBE_MAP_ARB; break ;
2709                     case GLX_TEXTURE_1D_ATI: type = WGL_TEXTURE_1D_ARB; break ;
2710                     case GLX_TEXTURE_2D_ATI: type = WGL_TEXTURE_2D_ARB; break ;
2711                 }
2712                 *piValue = type;
2713             } else {
2714             if (!object->texture_target) {
2715                 *piValue = WGL_NO_TEXTURE_ARB;
2716             } else {
2717                 if (!use_render_texture_emulation) {
2718                     SetLastError(ERROR_INVALID_DATA);      
2719                     return GL_FALSE;
2720                 }
2721                 switch (object->texture_target) {
2722                     case GL_TEXTURE_1D:       *piValue = WGL_TEXTURE_1D_ARB; break;
2723                     case GL_TEXTURE_2D:       *piValue = WGL_TEXTURE_2D_ARB; break;
2724                     case GL_TEXTURE_CUBE_MAP: *piValue = WGL_TEXTURE_CUBE_MAP_ARB; break;
2725                     case GL_TEXTURE_RECTANGLE_NV: *piValue = WGL_TEXTURE_RECTANGLE_NV; break;
2726                 }
2727             }
2728         }
2729         break;
2730
2731     case WGL_MIPMAP_TEXTURE_ARB:
2732         if (use_render_texture_ati) {
2733             wine_tsx11_lock();
2734             pglXQueryDrawable(object->display, object->drawable, GLX_MIPMAP_TEXTURE_ATI, (unsigned int*) piValue);
2735             wine_tsx11_unlock();
2736         } else {
2737             *piValue = GL_FALSE; /** don't support that */
2738             FIXME("unsupported WGL_ARB_render_texture attribute query for 0x%x\n", iAttribute);
2739         }
2740         break;
2741
2742     default:
2743         FIXME("unexpected attribute %x\n", iAttribute);
2744         break;
2745     }
2746
2747     return GL_TRUE;
2748 }
2749
2750 /**
2751  * X11DRV_wglReleasePbufferDCARB
2752  *
2753  * WGL_ARB_pbuffer: wglReleasePbufferDCARB
2754  */
2755 static int WINAPI X11DRV_wglReleasePbufferDCARB(HPBUFFERARB hPbuffer, HDC hdc)
2756 {
2757     TRACE("(%p, %p)\n", hPbuffer, hdc);
2758     return DeleteDC(hdc);
2759 }
2760
2761 /**
2762  * X11DRV_wglSetPbufferAttribARB
2763  *
2764  * WGL_ARB_pbuffer: wglSetPbufferAttribARB
2765  */
2766 static GLboolean WINAPI X11DRV_wglSetPbufferAttribARB(HPBUFFERARB hPbuffer, const int *piAttribList)
2767 {
2768     Wine_GLPBuffer* object = hPbuffer;
2769     GLboolean ret = GL_FALSE;
2770
2771     WARN("(%p, %p): alpha-testing, report any problem\n", hPbuffer, piAttribList);
2772     if (NULL == object) {
2773         SetLastError(ERROR_INVALID_HANDLE);
2774         return GL_FALSE;
2775     }
2776     if (!object->use_render_texture) {
2777         SetLastError(ERROR_INVALID_HANDLE);
2778         return GL_FALSE;
2779     }
2780     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
2781         return GL_TRUE;
2782     }
2783     if (NULL != pglXDrawableAttribATI) {
2784         if (use_render_texture_ati) {
2785             FIXME("Need conversion for GLX_ATI_render_texture\n");
2786         }
2787         wine_tsx11_lock();
2788         ret = pglXDrawableAttribATI(object->display, object->drawable, piAttribList);
2789         wine_tsx11_unlock();
2790     }
2791     return ret;
2792 }
2793
2794 /**
2795  * X11DRV_wglChoosePixelFormatARB
2796  *
2797  * WGL_ARB_pixel_format: wglChoosePixelFormatARB
2798  */
2799 static GLboolean WINAPI X11DRV_wglChoosePixelFormatARB(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats)
2800 {
2801     int gl_test = 0;
2802     int attribs[256];
2803     int nAttribs = 0;
2804     GLXFBConfig* cfgs = NULL;
2805     int nCfgs = 0;
2806     int it;
2807     int fmt_id;
2808     WineGLPixelFormat *fmt;
2809     UINT pfmt_it = 0;
2810     int run;
2811     int i;
2812     DWORD dwFlags = 0;
2813
2814     TRACE("(%p, %p, %p, %d, %p, %p): hackish\n", hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats);
2815     if (NULL != pfAttribFList) {
2816         FIXME("unused pfAttribFList\n");
2817     }
2818
2819     nAttribs = ConvertAttribWGLtoGLX(piAttribIList, attribs, NULL);
2820     if (-1 == nAttribs) {
2821         WARN("Cannot convert WGL to GLX attributes\n");
2822         return GL_FALSE;
2823     }
2824     PUSH1(attribs, None);
2825
2826     /* There is no 1:1 mapping between GLX and WGL formats because we duplicate some GLX formats for bitmap rendering (see get_formats).
2827      * Flags like PFD_SUPPORT_GDI, PFD_DRAW_TO_BITMAP and others are a property of the WineGLPixelFormat. We don't query these attributes
2828      * using glXChooseFBConfig but we filter the result of glXChooseFBConfig later on by passing a dwFlags to 'ConvertPixelFormatGLXtoWGL'. */
2829     for(i=0; piAttribIList[i] != 0; i+=2)
2830     {
2831         switch(piAttribIList[i])
2832         {
2833             case WGL_DRAW_TO_BITMAP_ARB:
2834                 if(piAttribIList[i+1])
2835                     dwFlags |= PFD_DRAW_TO_BITMAP;
2836                 break;
2837             case WGL_ACCELERATION_ARB:
2838                 switch(piAttribIList[i+1])
2839                 {
2840                     case WGL_NO_ACCELERATION_ARB:
2841                         dwFlags |= PFD_GENERIC_FORMAT;
2842                         break;
2843                     case WGL_GENERIC_ACCELERATION_ARB:
2844                         dwFlags |= PFD_GENERIC_ACCELERATED;
2845                         break;
2846                     case WGL_FULL_ACCELERATION_ARB:
2847                         /* Nothing to do */
2848                         break;
2849                 }
2850                 break;
2851             case WGL_SUPPORT_GDI_ARB:
2852                 if(piAttribIList[i+1])
2853                     dwFlags |= PFD_SUPPORT_GDI;
2854                 break;
2855         }
2856     }
2857
2858     /* Search for FB configurations matching the requirements in attribs */
2859     wine_tsx11_lock();
2860     cfgs = pglXChooseFBConfig(gdi_display, DefaultScreen(gdi_display), attribs, &nCfgs);
2861     if (NULL == cfgs) {
2862         wine_tsx11_unlock();
2863         WARN("Compatible Pixel Format not found\n");
2864         return GL_FALSE;
2865     }
2866
2867     /* Loop through all matching formats and check if they are suitable.
2868     * Note that this function should at max return nMaxFormats different formats */
2869     for(run=0; run < 2; run++)
2870     {
2871         for (it = 0; it < nCfgs; ++it) {
2872             gl_test = pglXGetFBConfigAttrib(gdi_display, cfgs[it], GLX_FBCONFIG_ID, &fmt_id);
2873             if (gl_test) {
2874                 ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
2875                 continue;
2876             }
2877
2878             /* Search for the format in our list of compatible formats */
2879             fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fmt_id, dwFlags);
2880             if(!fmt)
2881                 continue;
2882
2883             /* During the first run we only want onscreen formats and during the second only offscreen 'XOR' */
2884             if( ((run == 0) && fmt->offscreenOnly) || ((run == 1) && !fmt->offscreenOnly) )
2885                 continue;
2886
2887             if(pfmt_it < nMaxFormats) {
2888                 piFormats[pfmt_it] = fmt->iPixelFormat;
2889                 TRACE("at %d/%d found FBCONFIG_ID 0x%x (%d)\n", it + 1, nCfgs, fmt_id, piFormats[pfmt_it]);
2890             }
2891             pfmt_it++;
2892         }
2893     }
2894
2895     *nNumFormats = pfmt_it;
2896     /** free list */
2897     XFree(cfgs);
2898     wine_tsx11_unlock();
2899     return GL_TRUE;
2900 }
2901
2902 /**
2903  * X11DRV_wglGetPixelFormatAttribivARB
2904  *
2905  * WGL_ARB_pixel_format: wglGetPixelFormatAttribivARB
2906  */
2907 static GLboolean WINAPI X11DRV_wglGetPixelFormatAttribivARB(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues)
2908 {
2909     UINT i;
2910     WineGLPixelFormat *fmt = NULL;
2911     int hTest;
2912     int tmp;
2913     int curGLXAttr = 0;
2914     int nWGLFormats = 0;
2915
2916     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues);
2917
2918     if (0 < iLayerPlane) {
2919         FIXME("unsupported iLayerPlane(%d) > 0, returns FALSE\n", iLayerPlane);
2920         return GL_FALSE;
2921     }
2922
2923     /* Convert the WGL pixelformat to a GLX one, if this fails then most likely the iPixelFormat isn't supported.
2924     * We don't have to fail yet as a program can specify an invalid iPixelFormat (lets say 0) if it wants to query
2925     * the number of supported WGL formats. Whether the iPixelFormat is valid is handled in the for-loop below. */
2926     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nWGLFormats);
2927     if(!fmt) {
2928         WARN("Unable to convert iPixelFormat %d to a GLX one!\n", iPixelFormat);
2929     }
2930
2931     wine_tsx11_lock();
2932     for (i = 0; i < nAttributes; ++i) {
2933         const int curWGLAttr = piAttributes[i];
2934         TRACE("pAttr[%d] = %x\n", i, curWGLAttr);
2935
2936         switch (curWGLAttr) {
2937             case WGL_NUMBER_PIXEL_FORMATS_ARB:
2938                 piValues[i] = nWGLFormats; 
2939                 continue;
2940
2941             case WGL_SUPPORT_OPENGL_ARB:
2942                 piValues[i] = GL_TRUE; 
2943                 continue;
2944
2945             case WGL_ACCELERATION_ARB:
2946                 curGLXAttr = GLX_CONFIG_CAVEAT;
2947                 if (!fmt) goto pix_error;
2948                 if(fmt->dwFlags & PFD_GENERIC_FORMAT)
2949                     piValues[i] = WGL_NO_ACCELERATION_ARB;
2950                 else if(fmt->dwFlags & PFD_GENERIC_ACCELERATED)
2951                     piValues[i] = WGL_GENERIC_ACCELERATION_ARB;
2952                 else
2953                     piValues[i] = WGL_FULL_ACCELERATION_ARB;
2954                 continue;
2955
2956             case WGL_TRANSPARENT_ARB:
2957                 curGLXAttr = GLX_TRANSPARENT_TYPE;
2958                 if (!fmt) goto pix_error;
2959                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2960                 if (hTest) goto get_error;
2961                     piValues[i] = GL_FALSE;
2962                 if (GLX_NONE != tmp) piValues[i] = GL_TRUE;
2963                     continue;
2964
2965             case WGL_PIXEL_TYPE_ARB:
2966                 curGLXAttr = GLX_RENDER_TYPE;
2967                 if (!fmt) goto pix_error;
2968                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2969                 if (hTest) goto get_error;
2970                 TRACE("WGL_PIXEL_TYPE_ARB: GLX_RENDER_TYPE = 0x%x\n", tmp);
2971                 if      (tmp & GLX_RGBA_BIT)           { piValues[i] = WGL_TYPE_RGBA_ARB; }
2972                 else if (tmp & GLX_COLOR_INDEX_BIT)    { piValues[i] = WGL_TYPE_COLORINDEX_ARB; }
2973                 else if (tmp & GLX_RGBA_FLOAT_BIT)     { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
2974                 else if (tmp & GLX_RGBA_FLOAT_ATI_BIT) { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
2975                 else if (tmp & GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT) { piValues[i] = WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT; }
2976                 else {
2977                     ERR("unexpected RenderType(%x)\n", tmp);
2978                     piValues[i] = WGL_TYPE_RGBA_ARB;
2979                 }
2980                 continue;
2981
2982             case WGL_COLOR_BITS_ARB:
2983                 curGLXAttr = GLX_BUFFER_SIZE;
2984                 break;
2985
2986             case WGL_BIND_TO_TEXTURE_RGB_ARB:
2987                 if (use_render_texture_ati) {
2988                     curGLXAttr = GLX_BIND_TO_TEXTURE_RGB_ATI;
2989                     break;
2990                 }
2991             case WGL_BIND_TO_TEXTURE_RGBA_ARB:
2992                 if (use_render_texture_ati) {
2993                     curGLXAttr = GLX_BIND_TO_TEXTURE_RGBA_ATI;
2994                     break;
2995                 }
2996                 if (!use_render_texture_emulation) {
2997                     piValues[i] = GL_FALSE;
2998                     continue;   
2999                 }
3000                 curGLXAttr = GLX_RENDER_TYPE;
3001                 if (!fmt) goto pix_error;
3002                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
3003                 if (hTest) goto get_error;
3004                 if (GLX_COLOR_INDEX_BIT == tmp) {
3005                     piValues[i] = GL_FALSE;  
3006                     continue;
3007                 }
3008                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
3009                 if (hTest) goto get_error;
3010                 piValues[i] = (tmp & GLX_PBUFFER_BIT) ? GL_TRUE : GL_FALSE;
3011                 continue;
3012
3013             case WGL_BLUE_BITS_ARB:
3014                 curGLXAttr = GLX_BLUE_SIZE;
3015                 break;
3016             case WGL_RED_BITS_ARB:
3017                 curGLXAttr = GLX_RED_SIZE;
3018                 break;
3019             case WGL_GREEN_BITS_ARB:
3020                 curGLXAttr = GLX_GREEN_SIZE;
3021                 break;
3022             case WGL_ALPHA_BITS_ARB:
3023                 curGLXAttr = GLX_ALPHA_SIZE;
3024                 break;
3025             case WGL_DEPTH_BITS_ARB:
3026                 curGLXAttr = GLX_DEPTH_SIZE;
3027                 break;
3028             case WGL_STENCIL_BITS_ARB:
3029                 curGLXAttr = GLX_STENCIL_SIZE;
3030                 break;
3031             case WGL_DOUBLE_BUFFER_ARB:
3032                 curGLXAttr = GLX_DOUBLEBUFFER;
3033                 break;
3034             case WGL_STEREO_ARB:
3035                 curGLXAttr = GLX_STEREO;
3036                 break;
3037             case WGL_AUX_BUFFERS_ARB:
3038                 curGLXAttr = GLX_AUX_BUFFERS;
3039                 break;
3040
3041             case WGL_SUPPORT_GDI_ARB:
3042                 if (!fmt) goto pix_error;
3043                 piValues[i] = (fmt->dwFlags & PFD_SUPPORT_GDI) ? TRUE : FALSE;
3044                 continue;
3045
3046             case WGL_DRAW_TO_BITMAP_ARB:
3047                 if (!fmt) goto pix_error;
3048                 piValues[i] = (fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? TRUE : FALSE;
3049                 continue;
3050
3051             case WGL_DRAW_TO_WINDOW_ARB:
3052             case WGL_DRAW_TO_PBUFFER_ARB:
3053                 if (!fmt) goto pix_error;
3054                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
3055                 if (hTest) goto get_error;
3056                 if((curWGLAttr == WGL_DRAW_TO_WINDOW_ARB && (tmp&GLX_WINDOW_BIT)) ||
3057                    (curWGLAttr == WGL_DRAW_TO_PBUFFER_ARB && (tmp&GLX_PBUFFER_BIT)))
3058                     piValues[i] = GL_TRUE;
3059                 else
3060                     piValues[i] = GL_FALSE;
3061                 continue;
3062
3063             case WGL_SWAP_METHOD_ARB:
3064                 /* For now return SWAP_EXCHANGE_ARB which is the best type of buffer switch available.
3065                  * Later on we can also use GLX_OML_swap_method on drivers which support this. At this
3066                  * point only ATI offers this.
3067                  */
3068                 piValues[i] = WGL_SWAP_EXCHANGE_ARB;
3069                 break;
3070
3071             case WGL_PBUFFER_LARGEST_ARB:
3072                 curGLXAttr = GLX_LARGEST_PBUFFER;
3073                 break;
3074
3075             case WGL_SAMPLE_BUFFERS_ARB:
3076                 curGLXAttr = GLX_SAMPLE_BUFFERS_ARB;
3077                 break;
3078
3079             case WGL_SAMPLES_ARB:
3080                 curGLXAttr = GLX_SAMPLES_ARB;
3081                 break;
3082
3083             case WGL_FLOAT_COMPONENTS_NV:
3084                 curGLXAttr = GLX_FLOAT_COMPONENTS_NV;
3085                 break;
3086
3087             case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
3088                 curGLXAttr = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT;
3089                 break;
3090
3091             case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
3092                 curGLXAttr = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
3093                 break;
3094
3095             case WGL_ACCUM_RED_BITS_ARB:
3096                 curGLXAttr = GLX_ACCUM_RED_SIZE;
3097                 break;
3098             case WGL_ACCUM_GREEN_BITS_ARB:
3099                 curGLXAttr = GLX_ACCUM_GREEN_SIZE;
3100                 break;
3101             case WGL_ACCUM_BLUE_BITS_ARB:
3102                 curGLXAttr = GLX_ACCUM_BLUE_SIZE;
3103                 break;
3104             case WGL_ACCUM_ALPHA_BITS_ARB:
3105                 curGLXAttr = GLX_ACCUM_ALPHA_SIZE;
3106                 break;
3107             case WGL_ACCUM_BITS_ARB:
3108                 if (!fmt) goto pix_error;
3109                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &tmp);
3110                 if (hTest) goto get_error;
3111                 piValues[i] = tmp;
3112                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &tmp);
3113                 if (hTest) goto get_error;
3114                 piValues[i] += tmp;
3115                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &tmp);
3116                 if (hTest) goto get_error;
3117                 piValues[i] += tmp;
3118                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &tmp);
3119                 if (hTest) goto get_error;
3120                 piValues[i] += tmp;
3121                 continue;
3122
3123             default:
3124                 FIXME("unsupported %x WGL Attribute\n", curWGLAttr);
3125         }
3126
3127         /* Retrieve a GLX FBConfigAttrib when the attribute to query is valid and
3128          * iPixelFormat != 0. When iPixelFormat is 0 the only value which makes
3129          * sense to query is WGL_NUMBER_PIXEL_FORMATS_ARB.
3130          *
3131          * TODO: properly test the behavior of wglGetPixelFormatAttrib*v on Windows
3132          *       and check which options can work using iPixelFormat=0 and which not.
3133          *       A problem would be that this function is an extension. This would
3134          *       mean that the behavior could differ between different vendors (ATI, Nvidia, ..).
3135          */
3136         if (0 != curGLXAttr && iPixelFormat != 0) {
3137             if (!fmt) goto pix_error;
3138             hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, piValues + i);
3139             if (hTest) goto get_error;
3140             curGLXAttr = 0;
3141         } else { 
3142             piValues[i] = GL_FALSE; 
3143         }
3144     }
3145     wine_tsx11_unlock();
3146     return GL_TRUE;
3147
3148 get_error:
3149     wine_tsx11_unlock();
3150     ERR("(%p): unexpected failure on GetFBConfigAttrib(%x) returns FALSE\n", hdc, curGLXAttr);
3151     return GL_FALSE;
3152
3153 pix_error:
3154     wine_tsx11_unlock();
3155     ERR("(%p): unexpected iPixelFormat(%d) vs nFormats(%d), returns FALSE\n", hdc, iPixelFormat, nWGLFormats);
3156     return GL_FALSE;
3157 }
3158
3159 /**
3160  * X11DRV_wglGetPixelFormatAttribfvARB
3161  *
3162  * WGL_ARB_pixel_format: wglGetPixelFormatAttribfvARB
3163  */
3164 static GLboolean WINAPI X11DRV_wglGetPixelFormatAttribfvARB(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues)
3165 {
3166     int *attr;
3167     int ret;
3168     UINT i;
3169
3170     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues);
3171
3172     /* Allocate a temporary array to store integer values */
3173     attr = HeapAlloc(GetProcessHeap(), 0, nAttributes * sizeof(int));
3174     if (!attr) {
3175         ERR("couldn't allocate %d array\n", nAttributes);
3176         return GL_FALSE;
3177     }
3178
3179     /* Piggy-back on wglGetPixelFormatAttribivARB */
3180     ret = X11DRV_wglGetPixelFormatAttribivARB(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, attr);
3181     if (ret) {
3182         /* Convert integer values to float. Should also check for attributes
3183            that can give decimal values here */
3184         for (i=0; i<nAttributes;i++) {
3185             pfValues[i] = attr[i];
3186         }
3187     }
3188
3189     HeapFree(GetProcessHeap(), 0, attr);
3190     return ret;
3191 }
3192
3193 /**
3194  * X11DRV_wglBindTexImageARB
3195  *
3196  * WGL_ARB_render_texture: wglBindTexImageARB
3197  */
3198 static GLboolean WINAPI X11DRV_wglBindTexImageARB(HPBUFFERARB hPbuffer, int iBuffer)
3199 {
3200     Wine_GLPBuffer* object = hPbuffer;
3201     GLboolean ret = GL_FALSE;
3202
3203     TRACE("(%p, %d)\n", hPbuffer, iBuffer);
3204     if (NULL == object) {
3205         SetLastError(ERROR_INVALID_HANDLE);
3206         return GL_FALSE;
3207     }
3208     if (!object->use_render_texture) {
3209         SetLastError(ERROR_INVALID_HANDLE);
3210         return GL_FALSE;
3211     }
3212
3213     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
3214         static int init = 0;
3215         int prev_binded_texture = 0;
3216         GLXContext prev_context;
3217         Drawable prev_drawable;
3218         GLXContext tmp_context;
3219
3220         wine_tsx11_lock();
3221         prev_context = pglXGetCurrentContext();
3222         prev_drawable = pglXGetCurrentDrawable();
3223
3224         /* Our render_texture emulation is basic and lacks some features (1D/Cube support).
3225            This is mostly due to lack of demos/games using them. Further the use of glReadPixels
3226            isn't ideal performance wise but I wasn't able to get other ways working.
3227         */
3228         if(!init) {
3229             init = 1; /* Only show the FIXME once for performance reasons */
3230             FIXME("partial stub!\n");
3231         }
3232
3233         TRACE("drawable=%lx, context=%p\n", object->drawable, prev_context);
3234         tmp_context = pglXCreateNewContext(gdi_display, object->fmt->fbconfig, object->fmt->render_type, prev_context, True);
3235
3236         pglGetIntegerv(object->texture_bind_target, &prev_binded_texture);
3237
3238         /* Switch to our pbuffer */
3239         pglXMakeCurrent(gdi_display, object->drawable, tmp_context);
3240
3241         /* Make sure that the prev_binded_texture is set as the current texture state isn't shared between contexts.
3242          * After that upload the pbuffer texture data. */
3243         pglBindTexture(object->texture_target, prev_binded_texture);
3244         pglCopyTexImage2D(object->texture_target, 0, object->use_render_texture, 0, 0, object->width, object->height, 0);
3245
3246         /* Switch back to the original drawable and upload the pbuffer-texture */
3247         pglXMakeCurrent(object->display, prev_drawable, prev_context);
3248         pglXDestroyContext(gdi_display, tmp_context);
3249         wine_tsx11_unlock();
3250         return GL_TRUE;
3251     }
3252
3253     if (NULL != pglXBindTexImageATI) {
3254         int buffer;
3255
3256         switch(iBuffer)
3257         {
3258             case WGL_FRONT_LEFT_ARB:
3259                 buffer = GLX_FRONT_LEFT_ATI;
3260                 break;
3261             case WGL_FRONT_RIGHT_ARB:
3262                 buffer = GLX_FRONT_RIGHT_ATI;
3263                 break;
3264             case WGL_BACK_LEFT_ARB:
3265                 buffer = GLX_BACK_LEFT_ATI;
3266                 break;
3267             case WGL_BACK_RIGHT_ARB:
3268                 buffer = GLX_BACK_RIGHT_ATI;
3269                 break;
3270             default:
3271                 ERR("Unknown iBuffer=%#x\n", iBuffer);
3272                 return FALSE;
3273         }
3274
3275         /* In the sample 'ogl_offscreen_rendering_3' from codesampler.net I get garbage on the screen.
3276          * I'm not sure if that's a bug in the ATI extension or in the program. I think that the program
3277          * expected a single buffering format since it didn't ask for double buffering. A buffer swap
3278          * fixed the program. I don't know what the correct behavior is. On the other hand that demo
3279          * works fine using our pbuffer emulation path.
3280          */
3281         wine_tsx11_lock();
3282         ret = pglXBindTexImageATI(object->display, object->drawable, buffer);
3283         wine_tsx11_unlock();
3284     }
3285     return ret;
3286 }
3287
3288 /**
3289  * X11DRV_wglReleaseTexImageARB
3290  *
3291  * WGL_ARB_render_texture: wglReleaseTexImageARB
3292  */
3293 static GLboolean WINAPI X11DRV_wglReleaseTexImageARB(HPBUFFERARB hPbuffer, int iBuffer)
3294 {
3295     Wine_GLPBuffer* object = hPbuffer;
3296     GLboolean ret = GL_FALSE;
3297
3298     TRACE("(%p, %d)\n", hPbuffer, iBuffer);
3299     if (NULL == object) {
3300         SetLastError(ERROR_INVALID_HANDLE);
3301         return GL_FALSE;
3302     }
3303     if (!object->use_render_texture) {
3304         SetLastError(ERROR_INVALID_HANDLE);
3305         return GL_FALSE;
3306     }
3307     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
3308         return GL_TRUE;
3309     }
3310     if (NULL != pglXReleaseTexImageATI) {
3311         int buffer;
3312
3313         switch(iBuffer)
3314         {
3315             case WGL_FRONT_LEFT_ARB:
3316                 buffer = GLX_FRONT_LEFT_ATI;
3317                 break;
3318             case WGL_FRONT_RIGHT_ARB:
3319                 buffer = GLX_FRONT_RIGHT_ATI;
3320                 break;
3321             case WGL_BACK_LEFT_ARB:
3322                 buffer = GLX_BACK_LEFT_ATI;
3323                 break;
3324             case WGL_BACK_RIGHT_ARB:
3325                 buffer = GLX_BACK_RIGHT_ATI;
3326                 break;
3327             default:
3328                 ERR("Unknown iBuffer=%#x\n", iBuffer);
3329                 return FALSE;
3330         }
3331         wine_tsx11_lock();
3332         ret = pglXReleaseTexImageATI(object->display, object->drawable, buffer);
3333         wine_tsx11_unlock();
3334     }
3335     return ret;
3336 }
3337
3338 /**
3339  * X11DRV_wglGetExtensionsStringEXT
3340  *
3341  * WGL_EXT_extensions_string: wglGetExtensionsStringEXT
3342  */
3343 static const char * WINAPI X11DRV_wglGetExtensionsStringEXT(void) {
3344     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
3345     return WineGLInfo.wglExtensions;
3346 }
3347
3348 /**
3349  * X11DRV_wglGetSwapIntervalEXT
3350  *
3351  * WGL_EXT_swap_control: wglGetSwapIntervalEXT
3352  */
3353 static int WINAPI X11DRV_wglGetSwapIntervalEXT(VOID) {
3354     /* GLX_SGI_swap_control doesn't have any provisions for getting the swap
3355      * interval, so the swap interval has to be tracked. */
3356     TRACE("()\n");
3357     return swap_interval;
3358 }
3359
3360 /**
3361  * X11DRV_wglSwapIntervalEXT
3362  *
3363  * WGL_EXT_swap_control: wglSwapIntervalEXT
3364  */
3365 static BOOL WINAPI X11DRV_wglSwapIntervalEXT(int interval) {
3366     BOOL ret = TRUE;
3367
3368     TRACE("(%d)\n", interval);
3369
3370     if (interval < 0)
3371     {
3372         SetLastError(ERROR_INVALID_DATA);
3373         return FALSE;
3374     }
3375     else if (!has_swap_control && interval == 0)
3376     {
3377         /* wglSwapIntervalEXT considers an interval value of zero to mean that
3378          * vsync should be disabled, but glXSwapIntervalSGI considers such a
3379          * value to be an error. Just silently ignore the request for now. */
3380         WARN("Request to disable vertical sync is not handled\n");
3381         swap_interval = 0;
3382     }
3383     else
3384     {
3385         if (pglXSwapIntervalSGI)
3386         {
3387             wine_tsx11_lock();
3388             ret = !pglXSwapIntervalSGI(interval);
3389             wine_tsx11_unlock();
3390         }
3391         else
3392             WARN("GLX_SGI_swap_control extension is not available\n");
3393
3394         if (ret)
3395             swap_interval = interval;
3396         else
3397             SetLastError(ERROR_DC_NOT_FOUND);
3398     }
3399
3400     return ret;
3401 }
3402
3403 /**
3404  * X11DRV_wglAllocateMemoryNV
3405  *
3406  * WGL_NV_vertex_array_range: wglAllocateMemoryNV
3407  */
3408 static void* WINAPI X11DRV_wglAllocateMemoryNV(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority) {
3409     void *ret = NULL;
3410     TRACE("(%d, %f, %f, %f)\n", size, readfreq, writefreq, priority );
3411
3412     if (pglXAllocateMemoryNV)
3413     {
3414         wine_tsx11_lock();
3415         ret = pglXAllocateMemoryNV(size, readfreq, writefreq, priority);
3416         wine_tsx11_unlock();
3417     }
3418     return ret;
3419 }
3420
3421 /**
3422  * X11DRV_wglFreeMemoryNV
3423  *
3424  * WGL_NV_vertex_array_range: wglFreeMemoryNV
3425  */
3426 static void WINAPI X11DRV_wglFreeMemoryNV(GLvoid* pointer) {
3427     TRACE("(%p)\n", pointer);
3428     if (pglXFreeMemoryNV == NULL)
3429         return;
3430
3431     wine_tsx11_lock();
3432     pglXFreeMemoryNV(pointer);
3433     wine_tsx11_unlock();
3434 }
3435
3436 /**
3437  * X11DRV_wglSetPixelFormatWINE
3438  *
3439  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
3440  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
3441  */
3442 BOOL X11DRV_wglSetPixelFormatWINE(PHYSDEV dev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
3443 {
3444     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
3445
3446     TRACE("(%p,%d,%p)\n", physDev, iPixelFormat, ppfd);
3447
3448     if (!has_opengl()) return FALSE;
3449
3450     if (physDev->current_pf == iPixelFormat) return TRUE;
3451
3452     /* Relay to the core SetPixelFormat */
3453     TRACE("Changing iPixelFormat from %d to %d\n", physDev->current_pf, iPixelFormat);
3454     return internal_SetPixelFormat(physDev, iPixelFormat, ppfd);
3455 }
3456
3457 /**
3458  * glxRequireVersion (internal)
3459  *
3460  * Check if the supported GLX version matches requiredVersion.
3461  */
3462 static BOOL glxRequireVersion(int requiredVersion)
3463 {
3464     /* Both requiredVersion and glXVersion[1] contains the minor GLX version */
3465     if(requiredVersion <= WineGLInfo.glxVersion[1])
3466         return TRUE;
3467
3468     return FALSE;
3469 }
3470
3471 static BOOL glxRequireExtension(const char *requiredExtension)
3472 {
3473     if (strstr(WineGLInfo.glxExtensions, requiredExtension) == NULL) {
3474         return FALSE;
3475     }
3476
3477     return TRUE;
3478 }
3479
3480 static void register_extension_string(const char *ext)
3481 {
3482     if (WineGLInfo.wglExtensions[0])
3483         strcat(WineGLInfo.wglExtensions, " ");
3484     strcat(WineGLInfo.wglExtensions, ext);
3485
3486     TRACE("'%s'\n", ext);
3487 }
3488
3489 static BOOL register_extension(const WineGLExtension * ext)
3490 {
3491     int i;
3492
3493     assert( WineGLExtensionListSize < MAX_EXTENSIONS );
3494     WineGLExtensionList[WineGLExtensionListSize++] = ext;
3495
3496     register_extension_string(ext->extName);
3497
3498     for (i = 0; ext->extEntryPoints[i].funcName; ++i)
3499         TRACE("    - '%s'\n", ext->extEntryPoints[i].funcName);
3500
3501     return TRUE;
3502 }
3503
3504 static const WineGLExtension WGL_internal_functions =
3505 {
3506   "",
3507   {
3508     { "wglGetIntegerv", X11DRV_wglGetIntegerv },
3509     { "wglFinish", X11DRV_wglFinish },
3510     { "wglFlush", X11DRV_wglFlush },
3511   }
3512 };
3513
3514
3515 static const WineGLExtension WGL_ARB_create_context =
3516 {
3517   "WGL_ARB_create_context",
3518   {
3519     { "wglCreateContextAttribsARB", X11DRV_wglCreateContextAttribsARB },
3520   }
3521 };
3522
3523 static const WineGLExtension WGL_ARB_extensions_string =
3524 {
3525   "WGL_ARB_extensions_string",
3526   {
3527     { "wglGetExtensionsStringARB", X11DRV_wglGetExtensionsStringARB },
3528   }
3529 };
3530
3531 static const WineGLExtension WGL_ARB_make_current_read =
3532 {
3533   "WGL_ARB_make_current_read",
3534   {
3535     { "wglGetCurrentReadDCARB", X11DRV_wglGetCurrentReadDCARB },
3536     { "wglMakeContextCurrentARB", X11DRV_wglMakeContextCurrentARB },
3537   }
3538 };
3539
3540 static const WineGLExtension WGL_ARB_multisample =
3541 {
3542   "WGL_ARB_multisample",
3543 };
3544
3545 static const WineGLExtension WGL_ARB_pbuffer =
3546 {
3547   "WGL_ARB_pbuffer",
3548   {
3549     { "wglCreatePbufferARB", X11DRV_wglCreatePbufferARB },
3550     { "wglDestroyPbufferARB", X11DRV_wglDestroyPbufferARB },
3551     { "wglGetPbufferDCARB", X11DRV_wglGetPbufferDCARB },
3552     { "wglQueryPbufferARB", X11DRV_wglQueryPbufferARB },
3553     { "wglReleasePbufferDCARB", X11DRV_wglReleasePbufferDCARB },
3554     { "wglSetPbufferAttribARB", X11DRV_wglSetPbufferAttribARB },
3555   }
3556 };
3557
3558 static const WineGLExtension WGL_ARB_pixel_format =
3559 {
3560   "WGL_ARB_pixel_format",
3561   {
3562     { "wglChoosePixelFormatARB", X11DRV_wglChoosePixelFormatARB },
3563     { "wglGetPixelFormatAttribfvARB", X11DRV_wglGetPixelFormatAttribfvARB },
3564     { "wglGetPixelFormatAttribivARB", X11DRV_wglGetPixelFormatAttribivARB },
3565   }
3566 };
3567
3568 static const WineGLExtension WGL_ARB_render_texture =
3569 {
3570   "WGL_ARB_render_texture",
3571   {
3572     { "wglBindTexImageARB", X11DRV_wglBindTexImageARB },
3573     { "wglReleaseTexImageARB", X11DRV_wglReleaseTexImageARB },
3574   }
3575 };
3576
3577 static const WineGLExtension WGL_EXT_extensions_string =
3578 {
3579   "WGL_EXT_extensions_string",
3580   {
3581     { "wglGetExtensionsStringEXT", X11DRV_wglGetExtensionsStringEXT },
3582   }
3583 };
3584
3585 static const WineGLExtension WGL_EXT_swap_control =
3586 {
3587   "WGL_EXT_swap_control",
3588   {
3589     { "wglSwapIntervalEXT", X11DRV_wglSwapIntervalEXT },
3590     { "wglGetSwapIntervalEXT", X11DRV_wglGetSwapIntervalEXT },
3591   }
3592 };
3593
3594 static const WineGLExtension WGL_NV_vertex_array_range =
3595 {
3596   "WGL_NV_vertex_array_range",
3597   {
3598     { "wglAllocateMemoryNV", X11DRV_wglAllocateMemoryNV },
3599     { "wglFreeMemoryNV", X11DRV_wglFreeMemoryNV },
3600   }
3601 };
3602
3603 static const WineGLExtension WGL_WINE_pixel_format_passthrough =
3604 {
3605   "WGL_WINE_pixel_format_passthrough",
3606   {
3607     { "wglSetPixelFormatWINE", X11DRV_wglSetPixelFormatWINE },
3608   }
3609 };
3610
3611 /**
3612  * X11DRV_WineGL_LoadExtensions
3613  */
3614 static void X11DRV_WineGL_LoadExtensions(void)
3615 {
3616     WineGLInfo.wglExtensions[0] = 0;
3617
3618     /* Load Wine internal functions */
3619     register_extension(&WGL_internal_functions);
3620
3621     /* ARB Extensions */
3622
3623     if(glxRequireExtension("GLX_ARB_create_context"))
3624     {
3625         register_extension(&WGL_ARB_create_context);
3626
3627         if(glxRequireExtension("GLX_ARB_create_context_profile"))
3628             register_extension_string("WGL_ARB_create_context_profile");
3629     }
3630
3631     if(glxRequireExtension("GLX_ARB_fbconfig_float"))
3632     {
3633         register_extension_string("WGL_ARB_pixel_format_float");
3634         register_extension_string("WGL_ATI_pixel_format_float");
3635     }
3636
3637     register_extension(&WGL_ARB_extensions_string);
3638
3639     if (glxRequireVersion(3))
3640         register_extension(&WGL_ARB_make_current_read);
3641
3642     if (glxRequireExtension("GLX_ARB_multisample"))
3643         register_extension(&WGL_ARB_multisample);
3644
3645     /* In general pbuffer functionality requires support in the X-server. The functionality is
3646      * available either when the GLX_SGIX_pbuffer is present or when the GLX server version is 1.3.
3647      * All display drivers except for Nvidia's use the GLX module from Xfree86/Xorg which only
3648      * supports GLX 1.2. The endresult is that only Nvidia's drivers support pbuffers.
3649      *
3650      * The only other drive which has pbuffer support is Ati's FGLRX driver. They provide clientside GLX 1.3 support
3651      * without support in the X-server (which other Mesa based drivers require).
3652      *
3653      * Support pbuffers when the GLX version is 1.3 and GLX_SGIX_pbuffer is available. Further pbuffers can
3654      * also be supported when GLX_ATI_render_texture is available. This extension depends on pbuffers, so when it
3655      * is available pbuffers must be available too. */
3656     if ( (glxRequireVersion(3) && glxRequireExtension("GLX_SGIX_pbuffer")) || glxRequireExtension("GLX_ATI_render_texture"))
3657         register_extension(&WGL_ARB_pbuffer);
3658
3659     register_extension(&WGL_ARB_pixel_format);
3660
3661     /* Support WGL_ARB_render_texture when there's support or pbuffer based emulation */
3662     if (glxRequireExtension("GLX_ATI_render_texture") ||
3663         glxRequireExtension("GLX_ARB_render_texture") ||
3664         (glxRequireVersion(3) && glxRequireExtension("GLX_SGIX_pbuffer") && use_render_texture_emulation))
3665     {
3666         register_extension(&WGL_ARB_render_texture);
3667
3668         /* The WGL version of GLX_NV_float_buffer requires render_texture */
3669         if(glxRequireExtension("GLX_NV_float_buffer"))
3670             register_extension_string("WGL_NV_float_buffer");
3671
3672         /* Again there's no GLX equivalent for this extension, so depend on the required GL extension */
3673         if(strstr(WineGLInfo.glExtensions, "GL_NV_texture_rectangle") != NULL)
3674             register_extension_string("WGL_NV_texture_rectangle");
3675     }
3676
3677     /* EXT Extensions */
3678
3679     register_extension(&WGL_EXT_extensions_string);
3680
3681     /* Load this extension even when it isn't backed by a GLX extension because it is has been around for ages.
3682      * Games like Call of Duty and K.O.T.O.R. rely on it. Further our emulation is good enough. */
3683     register_extension(&WGL_EXT_swap_control);
3684
3685     if(glxRequireExtension("GLX_EXT_framebuffer_sRGB"))
3686         register_extension_string("WGL_EXT_framebuffer_sRGB");
3687
3688     if(glxRequireExtension("GLX_EXT_fbconfig_packed_float"))
3689         register_extension_string("WGL_EXT_pixel_format_packed_float");
3690
3691     if (glxRequireExtension("GLX_EXT_swap_control"))
3692         has_swap_control = TRUE;
3693
3694     /* The OpenGL extension GL_NV_vertex_array_range adds wgl/glX functions which aren't exported as 'real' wgl/glX extensions. */
3695     if(strstr(WineGLInfo.glExtensions, "GL_NV_vertex_array_range") != NULL)
3696         register_extension(&WGL_NV_vertex_array_range);
3697
3698     /* WINE-specific WGL Extensions */
3699
3700     /* In WineD3D we need the ability to set the pixel format more than once (e.g. after a device reset).
3701      * The default wglSetPixelFormat doesn't allow this, so add our own which allows it.
3702      */
3703     register_extension(&WGL_WINE_pixel_format_passthrough);
3704 }
3705
3706
3707 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
3708 {
3709     wine_tsx11_lock(); 
3710     pglXDestroyGLXPixmap(display, glxpixmap);
3711     wine_tsx11_unlock(); 
3712     return TRUE;
3713 }
3714
3715 /**
3716  * X11DRV_SwapBuffers
3717  *
3718  * Swap the buffers of this DC
3719  */
3720 BOOL X11DRV_SwapBuffers(PHYSDEV dev)
3721 {
3722   X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
3723   Wine_GLContext *ctx = NtCurrentTeb()->glContext;
3724
3725   if (!has_opengl()) return FALSE;
3726
3727   TRACE("(%p)\n", physDev);
3728
3729   if (!ctx)
3730   {
3731       WARN("Using a NULL context, skipping\n");
3732       SetLastError(ERROR_INVALID_HANDLE);
3733       return FALSE;
3734   }
3735
3736   if (!physDev->gl_drawable)
3737   {
3738       WARN("Using an invalid drawable, skipping\n");
3739       SetLastError(ERROR_INVALID_HANDLE);
3740       return FALSE;
3741   }
3742
3743   wine_tsx11_lock();
3744   sync_context(ctx);
3745   switch (physDev->gl_type)
3746   {
3747   case DC_GL_PIXMAP_WIN:
3748       if(pglXCopySubBufferMESA) {
3749           int w = physDev->dc_rect.right - physDev->dc_rect.left;
3750           int h = physDev->dc_rect.bottom - physDev->dc_rect.top;
3751
3752           /* (glX)SwapBuffers has an implicit glFlush effect, however
3753            * GLX_MESA_copy_sub_buffer doesn't. Make sure GL is flushed before
3754            * copying */
3755           pglFlush();
3756           if(w > 0 && h > 0)
3757               pglXCopySubBufferMESA(gdi_display, physDev->gl_drawable, 0, 0, w, h);
3758           break;
3759       }
3760       /* fall through */
3761   default:
3762       pglXSwapBuffers(gdi_display, physDev->gl_drawable);
3763       break;
3764   }
3765
3766   flush_gl_drawable(physDev);
3767   wine_tsx11_unlock();
3768
3769   /* FPS support */
3770   if (TRACE_ON(fps))
3771   {
3772       static long prev_time, start_time;
3773       static unsigned long frames, frames_total;
3774
3775       DWORD time = GetTickCount();
3776       frames++;
3777       frames_total++;
3778       /* every 1.5 seconds */
3779       if (time - prev_time > 1500) {
3780           TRACE_(fps)("@ approx %.2ffps, total %.2ffps\n",
3781                       1000.0*frames/(time - prev_time), 1000.0*frames_total/(time - start_time));
3782           prev_time = time;
3783           frames = 0;
3784           if(start_time == 0) start_time = time;
3785       }
3786   }
3787
3788   return TRUE;
3789 }
3790
3791 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
3792 {
3793     WineGLPixelFormat *fmt;
3794     XVisualInfo *ret;
3795
3796     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
3797     if(fmt == NULL)
3798         return NULL;
3799
3800     wine_tsx11_lock();
3801     ret = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
3802     wine_tsx11_unlock();
3803     return ret;
3804 }
3805
3806 #else  /* no OpenGL includes */
3807
3808 void X11DRV_OpenGL_Cleanup(void)
3809 {
3810 }
3811
3812 static inline void opengl_error(void)
3813 {
3814     static int warned;
3815     if (!warned++) ERR("No OpenGL support compiled in.\n");
3816 }
3817
3818 int pixelformat_from_fbconfig_id(XID fbconfig_id)
3819 {
3820     return 0;
3821 }
3822
3823 void mark_drawable_dirty(Drawable old, Drawable new)
3824 {
3825 }
3826
3827 void flush_gl_drawable(X11DRV_PDEVICE *physDev)
3828 {
3829 }
3830
3831 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
3832 {
3833     return 0;
3834 }
3835
3836 /***********************************************************************
3837  *              ChoosePixelFormat (X11DRV.@)
3838  */
3839 int X11DRV_ChoosePixelFormat(PHYSDEV dev, const PIXELFORMATDESCRIPTOR *ppfd)
3840 {
3841   opengl_error();
3842   return 0;
3843 }
3844
3845 /***********************************************************************
3846  *              DescribePixelFormat (X11DRV.@)
3847  */
3848 int X11DRV_DescribePixelFormat(PHYSDEV dev, int iPixelFormat, UINT nBytes, PIXELFORMATDESCRIPTOR *ppfd)
3849 {
3850   opengl_error();
3851   return 0;
3852 }
3853
3854 /***********************************************************************
3855  *              GetPixelFormat (X11DRV.@)
3856  */
3857 int X11DRV_GetPixelFormat(PHYSDEV dev)
3858 {
3859   opengl_error();
3860   return 0;
3861 }
3862
3863 /***********************************************************************
3864  *              SetPixelFormat (X11DRV.@)
3865  */
3866 BOOL X11DRV_SetPixelFormat(PHYSDEV dev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
3867 {
3868   opengl_error();
3869   return FALSE;
3870 }
3871
3872 /***********************************************************************
3873  *              SwapBuffers (X11DRV.@)
3874  */
3875 BOOL X11DRV_SwapBuffers(PHYSDEV dev)
3876 {
3877   opengl_error();
3878   return FALSE;
3879 }
3880
3881 /**
3882  * X11DRV_wglCopyContext
3883  *
3884  * For OpenGL32 wglCopyContext.
3885  */
3886 BOOL X11DRV_wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask)
3887 {
3888     opengl_error();
3889     return FALSE;
3890 }
3891
3892 /**
3893  * X11DRV_wglCreateContext
3894  *
3895  * For OpenGL32 wglCreateContext.
3896  */
3897 HGLRC X11DRV_wglCreateContext(PHYSDEV dev)
3898 {
3899     opengl_error();
3900     return NULL;
3901 }
3902
3903 /**
3904  * X11DRV_wglCreateContextAttribsARB
3905  *
3906  * WGL_ARB_create_context: wglCreateContextAttribsARB
3907  */
3908 HGLRC X11DRV_wglCreateContextAttribsARB(PHYSDEV dev, HGLRC hShareContext, const int* attribList)
3909 {
3910     opengl_error();
3911     return NULL;
3912 }
3913
3914 /**
3915  * X11DRV_wglDeleteContext
3916  *
3917  * For OpenGL32 wglDeleteContext.
3918  */
3919 BOOL X11DRV_wglDeleteContext(HGLRC hglrc)
3920 {
3921     opengl_error();
3922     return FALSE;
3923 }
3924
3925 /**
3926  * X11DRV_wglGetProcAddress
3927  *
3928  * For OpenGL32 wglGetProcAddress.
3929  */
3930 PROC X11DRV_wglGetProcAddress(LPCSTR lpszProc)
3931 {
3932     opengl_error();
3933     return NULL;
3934 }
3935
3936 HDC X11DRV_wglGetPbufferDCARB(PHYSDEV dev, void *hPbuffer)
3937 {
3938     opengl_error();
3939     return NULL;
3940 }
3941
3942 BOOL X11DRV_wglMakeContextCurrentARB(PHYSDEV draw_dev, PHYSDEV read_dev, HGLRC hglrc)
3943 {
3944     opengl_error();
3945     return FALSE;
3946 }
3947
3948 /**
3949  * X11DRV_wglMakeCurrent
3950  *
3951  * For OpenGL32 wglMakeCurrent.
3952  */
3953 BOOL X11DRV_wglMakeCurrent(PHYSDEV dev, HGLRC hglrc)
3954 {
3955     opengl_error();
3956     return FALSE;
3957 }
3958
3959 /**
3960  * X11DRV_wglShareLists
3961  *
3962  * For OpenGL32 wglShareLists.
3963  */
3964 BOOL X11DRV_wglShareLists(HGLRC hglrc1, HGLRC hglrc2)
3965 {
3966     opengl_error();
3967     return FALSE;
3968 }
3969
3970 /**
3971  * X11DRV_wglUseFontBitmapsA
3972  *
3973  * For OpenGL32 wglUseFontBitmapsA.
3974  */
3975 BOOL X11DRV_wglUseFontBitmapsA(PHYSDEV dev, DWORD first, DWORD count, DWORD listBase)
3976 {
3977     opengl_error();
3978     return FALSE;
3979 }
3980
3981 /**
3982  * X11DRV_wglUseFontBitmapsW
3983  *
3984  * For OpenGL32 wglUseFontBitmapsW.
3985  */
3986 BOOL X11DRV_wglUseFontBitmapsW(PHYSDEV dev, DWORD first, DWORD count, DWORD listBase)
3987 {
3988     opengl_error();
3989     return FALSE;
3990 }
3991
3992 /**
3993  * X11DRV_wglSetPixelFormatWINE
3994  *
3995  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
3996  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
3997  */
3998 BOOL X11DRV_wglSetPixelFormatWINE(PHYSDEV dev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
3999 {
4000     opengl_error();
4001     return FALSE;
4002 }
4003
4004 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
4005 {
4006     return FALSE;
4007 }
4008
4009 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
4010 {
4011     return NULL;
4012 }
4013
4014 #endif /* defined(SONAME_LIBGL) */