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