oleaut32: Use a saner calling convention for the marshaller asm thunks.
[wine] / dlls / opengl32 / wgl.c
1 /* Window-specific OpenGL functions implementation.
2  *
3  * Copyright (c) 1999 Lionel Ulmer
4  * Copyright (c) 2005 Raphael Junqueira
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <stdarg.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "opengl_ext.h"
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winuser.h"
32 #include "winreg.h"
33 #include "wingdi.h"
34 #include "winternl.h"
35 #include "winnt.h"
36
37 #define WGL_WGLEXT_PROTOTYPES
38 #include "wine/wglext.h"
39 #include "wine/gdi_driver.h"
40 #include "wine/wgl_driver.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(wgl);
44 WINE_DECLARE_DEBUG_CHANNEL(fps);
45
46 extern struct opengl_funcs null_opengl_funcs;
47
48 /* handle management */
49
50 #define MAX_WGL_HANDLES 1024
51
52 enum wgl_handle_type
53 {
54     HANDLE_CONTEXT = 0 << 12,
55     HANDLE_PBUFFER = 1 << 12,
56     HANDLE_TYPE_MASK = 15 << 12
57 };
58
59 struct opengl_context
60 {
61     DWORD               tid;         /* thread that the context is current in */
62     HDC                 draw_dc;     /* current drawing DC */
63     HDC                 read_dc;     /* current reading DC */
64     GLubyte            *extensions;  /* extension string */
65     struct wgl_context *drv_ctx;     /* driver context */
66 };
67
68 struct wgl_handle
69 {
70     UINT                 handle;
71     struct opengl_funcs *funcs;
72     union
73     {
74         struct opengl_context *context;  /* for HANDLE_CONTEXT */
75         struct wgl_pbuffer    *pbuffer;  /* for HANDLE_PBUFFER */
76         struct wgl_handle     *next;     /* for free handles */
77     } u;
78 };
79
80 static struct wgl_handle wgl_handles[MAX_WGL_HANDLES];
81 static struct wgl_handle *next_free;
82 static unsigned int handle_count;
83
84 static CRITICAL_SECTION wgl_section;
85 static CRITICAL_SECTION_DEBUG critsect_debug =
86 {
87     0, 0, &wgl_section,
88     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
89       0, 0, { (DWORD_PTR)(__FILE__ ": wgl_section") }
90 };
91 static CRITICAL_SECTION wgl_section = { &critsect_debug, -1, 0, 0, 0, 0 };
92
93 static inline struct opengl_funcs *get_dc_funcs( HDC hdc )
94 {
95     struct opengl_funcs *funcs = __wine_get_wgl_driver( hdc, WINE_WGL_DRIVER_VERSION );
96     if (funcs == (void *)-1) funcs = &null_opengl_funcs;
97     return funcs;
98 }
99
100 static inline HANDLE next_handle( struct wgl_handle *ptr, enum wgl_handle_type type )
101 {
102     WORD generation = HIWORD( ptr->handle ) + 1;
103     if (!generation) generation++;
104     ptr->handle = MAKELONG( ptr - wgl_handles, generation ) | type;
105     return ULongToHandle( ptr->handle );
106 }
107
108 /* the current context is assumed valid and doesn't need locking */
109 static inline struct wgl_handle *get_current_context_ptr(void)
110 {
111     if (!NtCurrentTeb()->glCurrentRC) return NULL;
112     return &wgl_handles[LOWORD(NtCurrentTeb()->glCurrentRC) & ~HANDLE_TYPE_MASK];
113 }
114
115 static struct wgl_handle *get_handle_ptr( HANDLE handle, enum wgl_handle_type type )
116 {
117     unsigned int index = LOWORD( handle ) & ~HANDLE_TYPE_MASK;
118
119     EnterCriticalSection( &wgl_section );
120     if (index < handle_count && ULongToHandle(wgl_handles[index].handle) == handle)
121         return &wgl_handles[index];
122
123     LeaveCriticalSection( &wgl_section );
124     SetLastError( ERROR_INVALID_HANDLE );
125     return NULL;
126 }
127
128 static void release_handle_ptr( struct wgl_handle *ptr )
129 {
130     if (ptr) LeaveCriticalSection( &wgl_section );
131 }
132
133 static HANDLE alloc_handle( enum wgl_handle_type type, struct opengl_funcs *funcs, void *user_ptr )
134 {
135     HANDLE handle = 0;
136     struct wgl_handle *ptr = NULL;
137
138     EnterCriticalSection( &wgl_section );
139     if ((ptr = next_free))
140         next_free = next_free->u.next;
141     else if (handle_count < MAX_WGL_HANDLES)
142         ptr = &wgl_handles[handle_count++];
143
144     if (ptr)
145     {
146         ptr->funcs = funcs;
147         ptr->u.context = user_ptr;
148         handle = next_handle( ptr, type );
149     }
150     else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
151     LeaveCriticalSection( &wgl_section );
152     return handle;
153 }
154
155 static void free_handle_ptr( struct wgl_handle *ptr )
156 {
157     ptr->handle |= 0xffff;
158     ptr->u.next = next_free;
159     ptr->funcs = NULL;
160     next_free = ptr;
161     LeaveCriticalSection( &wgl_section );
162 }
163
164 /***********************************************************************
165  *              wglCopyContext (OPENGL32.@)
166  */
167 BOOL WINAPI wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask)
168 {
169     struct wgl_handle *src, *dst;
170     BOOL ret = FALSE;
171
172     if (!(src = get_handle_ptr( hglrcSrc, HANDLE_CONTEXT ))) return FALSE;
173     if ((dst = get_handle_ptr( hglrcDst, HANDLE_CONTEXT )))
174     {
175         if (src->funcs != dst->funcs) SetLastError( ERROR_INVALID_HANDLE );
176         else ret = src->funcs->wgl.p_wglCopyContext( src->u.context->drv_ctx,
177                                                      dst->u.context->drv_ctx, mask );
178     }
179     release_handle_ptr( dst );
180     release_handle_ptr( src );
181     return ret;
182 }
183
184 /***********************************************************************
185  *              wglDeleteContext (OPENGL32.@)
186  */
187 BOOL WINAPI wglDeleteContext(HGLRC hglrc)
188 {
189     struct wgl_handle *ptr = get_handle_ptr( hglrc, HANDLE_CONTEXT );
190
191     if (!ptr) return FALSE;
192
193     if (ptr->u.context->tid && ptr->u.context->tid != GetCurrentThreadId())
194     {
195         SetLastError( ERROR_BUSY );
196         release_handle_ptr( ptr );
197         return FALSE;
198     }
199     if (hglrc == NtCurrentTeb()->glCurrentRC) wglMakeCurrent( 0, 0 );
200     ptr->funcs->wgl.p_wglDeleteContext( ptr->u.context->drv_ctx );
201     HeapFree( GetProcessHeap(), 0, ptr->u.context->extensions );
202     HeapFree( GetProcessHeap(), 0, ptr->u.context );
203     free_handle_ptr( ptr );
204     return TRUE;
205 }
206
207 /***********************************************************************
208  *              wglMakeCurrent (OPENGL32.@)
209  */
210 BOOL WINAPI wglMakeCurrent(HDC hdc, HGLRC hglrc)
211 {
212     BOOL ret = TRUE;
213     struct wgl_handle *ptr, *prev = get_current_context_ptr();
214
215     if (hglrc)
216     {
217         if (!(ptr = get_handle_ptr( hglrc, HANDLE_CONTEXT ))) return FALSE;
218         if (!ptr->u.context->tid || ptr->u.context->tid == GetCurrentThreadId())
219         {
220             ret = ptr->funcs->wgl.p_wglMakeCurrent( hdc, ptr->u.context->drv_ctx );
221             if (ret)
222             {
223                 if (prev) prev->u.context->tid = 0;
224                 ptr->u.context->tid = GetCurrentThreadId();
225                 ptr->u.context->draw_dc = hdc;
226                 ptr->u.context->read_dc = hdc;
227                 NtCurrentTeb()->glCurrentRC = hglrc;
228                 NtCurrentTeb()->glTable = ptr->funcs;
229             }
230         }
231         else
232         {
233             SetLastError( ERROR_BUSY );
234             ret = FALSE;
235         }
236         release_handle_ptr( ptr );
237     }
238     else if (prev)
239     {
240         if (!prev->funcs->wgl.p_wglMakeCurrent( 0, NULL )) return FALSE;
241         prev->u.context->tid = 0;
242         NtCurrentTeb()->glCurrentRC = 0;
243         NtCurrentTeb()->glTable = &null_opengl_funcs;
244     }
245     else if (!hdc)
246     {
247         SetLastError( ERROR_INVALID_HANDLE );
248         ret = FALSE;
249     }
250     return ret;
251 }
252
253 /***********************************************************************
254  *              wglCreateContextAttribsARB
255  *
256  * Provided by the WGL_ARB_create_context extension.
257  */
258 HGLRC WINAPI wglCreateContextAttribsARB( HDC hdc, HGLRC share, const int *attribs )
259 {
260     HGLRC ret = 0;
261     struct wgl_context *drv_ctx;
262     struct wgl_handle *share_ptr = NULL;
263     struct opengl_context *context;
264     struct opengl_funcs *funcs = get_dc_funcs( hdc );
265
266     if (!funcs || !funcs->ext.p_wglCreateContextAttribsARB) return 0;
267     if (share && !(share_ptr = get_handle_ptr( share, HANDLE_CONTEXT ))) return 0;
268     if ((drv_ctx = funcs->ext.p_wglCreateContextAttribsARB( hdc,
269                                               share_ptr ? share_ptr->u.context->drv_ctx : NULL, attribs )))
270     {
271         if ((context = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*context) )))
272         {
273             context->drv_ctx = drv_ctx;
274             if (!(ret = alloc_handle( HANDLE_CONTEXT, funcs, context )))
275                 HeapFree( GetProcessHeap(), 0, context );
276         }
277         if (!ret) funcs->wgl.p_wglDeleteContext( drv_ctx );
278     }
279     release_handle_ptr( share_ptr );
280     return ret;
281
282 }
283
284 /***********************************************************************
285  *              wglMakeContextCurrentARB
286  *
287  * Provided by the WGL_ARB_make_current_read extension.
288  */
289 BOOL WINAPI wglMakeContextCurrentARB( HDC draw_hdc, HDC read_hdc, HGLRC hglrc )
290 {
291     BOOL ret = TRUE;
292     struct wgl_handle *ptr, *prev = get_current_context_ptr();
293
294     if (hglrc)
295     {
296         if (!(ptr = get_handle_ptr( hglrc, HANDLE_CONTEXT ))) return FALSE;
297         if (!ptr->u.context->tid || ptr->u.context->tid == GetCurrentThreadId())
298         {
299             ret = (ptr->funcs->ext.p_wglMakeContextCurrentARB &&
300                    ptr->funcs->ext.p_wglMakeContextCurrentARB( draw_hdc, read_hdc,
301                                                                ptr->u.context->drv_ctx ));
302             if (ret)
303             {
304                 if (prev) prev->u.context->tid = 0;
305                 ptr->u.context->tid = GetCurrentThreadId();
306                 ptr->u.context->draw_dc = draw_hdc;
307                 ptr->u.context->read_dc = read_hdc;
308                 NtCurrentTeb()->glCurrentRC = hglrc;
309                 NtCurrentTeb()->glTable = ptr->funcs;
310             }
311         }
312         else
313         {
314             SetLastError( ERROR_BUSY );
315             ret = FALSE;
316         }
317         release_handle_ptr( ptr );
318     }
319     else if (prev)
320     {
321         if (!prev->funcs->wgl.p_wglMakeCurrent( 0, NULL )) return FALSE;
322         prev->u.context->tid = 0;
323         NtCurrentTeb()->glCurrentRC = 0;
324         NtCurrentTeb()->glTable = &null_opengl_funcs;
325     }
326     return ret;
327 }
328
329 /***********************************************************************
330  *              wglGetCurrentReadDCARB
331  *
332  * Provided by the WGL_ARB_make_current_read extension.
333  */
334 HDC WINAPI wglGetCurrentReadDCARB(void)
335 {
336     struct wgl_handle *ptr = get_current_context_ptr();
337
338     if (!ptr) return 0;
339     return ptr->u.context->read_dc;
340 }
341
342 /***********************************************************************
343  *              wglShareLists (OPENGL32.@)
344  */
345 BOOL WINAPI wglShareLists(HGLRC hglrcSrc, HGLRC hglrcDst)
346 {
347     BOOL ret = FALSE;
348     struct wgl_handle *src, *dst;
349
350     if (!(src = get_handle_ptr( hglrcSrc, HANDLE_CONTEXT ))) return FALSE;
351     if ((dst = get_handle_ptr( hglrcDst, HANDLE_CONTEXT )))
352     {
353         if (src->funcs != dst->funcs) SetLastError( ERROR_INVALID_HANDLE );
354         else ret = src->funcs->wgl.p_wglShareLists( src->u.context->drv_ctx, dst->u.context->drv_ctx );
355     }
356     release_handle_ptr( dst );
357     release_handle_ptr( src );
358     return ret;
359 }
360
361 /***********************************************************************
362  *              wglGetCurrentDC (OPENGL32.@)
363  */
364 HDC WINAPI wglGetCurrentDC(void)
365 {
366     struct wgl_handle *ptr = get_current_context_ptr();
367
368     if (!ptr) return 0;
369     return ptr->u.context->draw_dc;
370 }
371
372 /***********************************************************************
373  *              wglCreateContext (OPENGL32.@)
374  */
375 HGLRC WINAPI wglCreateContext(HDC hdc)
376 {
377     HGLRC ret = 0;
378     struct wgl_context *drv_ctx;
379     struct opengl_context *context;
380     struct opengl_funcs *funcs = get_dc_funcs( hdc );
381
382     if (!funcs) return 0;
383     if (!(drv_ctx = funcs->wgl.p_wglCreateContext( hdc ))) return 0;
384     if ((context = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*context) )))
385     {
386         context->drv_ctx = drv_ctx;
387         if (!(ret = alloc_handle( HANDLE_CONTEXT, funcs, context )))
388             HeapFree( GetProcessHeap(), 0, context );
389     }
390     if (!ret) funcs->wgl.p_wglDeleteContext( drv_ctx );
391     return ret;
392 }
393
394 /***********************************************************************
395  *              wglGetCurrentContext (OPENGL32.@)
396  */
397 HGLRC WINAPI wglGetCurrentContext(void)
398 {
399     return NtCurrentTeb()->glCurrentRC;
400 }
401
402 /***********************************************************************
403  *              wglDescribePixelFormat (OPENGL32.@)
404  */
405 INT WINAPI wglDescribePixelFormat(HDC hdc, INT format, UINT size, PIXELFORMATDESCRIPTOR *descr )
406 {
407     struct opengl_funcs *funcs = get_dc_funcs( hdc );
408     if (!funcs) return 0;
409     return funcs->wgl.p_wglDescribePixelFormat( hdc, format, size, descr );
410 }
411
412 /***********************************************************************
413  *              wglChoosePixelFormat (OPENGL32.@)
414  */
415 INT WINAPI wglChoosePixelFormat(HDC hdc, const PIXELFORMATDESCRIPTOR* ppfd)
416 {
417     PIXELFORMATDESCRIPTOR format, best;
418     int i, count, best_format;
419     int bestDBuffer = -1, bestStereo = -1;
420
421     TRACE_(wgl)( "%p %p: size %u version %u flags %u type %u color %u %u,%u,%u,%u "
422                  "accum %u depth %u stencil %u aux %u\n",
423                  hdc, ppfd, ppfd->nSize, ppfd->nVersion, ppfd->dwFlags, ppfd->iPixelType,
424                  ppfd->cColorBits, ppfd->cRedBits, ppfd->cGreenBits, ppfd->cBlueBits, ppfd->cAlphaBits,
425                  ppfd->cAccumBits, ppfd->cDepthBits, ppfd->cStencilBits, ppfd->cAuxBuffers );
426
427     count = wglDescribePixelFormat( hdc, 0, 0, NULL );
428     if (!count) return 0;
429
430     best_format = 0;
431     best.dwFlags = 0;
432     best.cAlphaBits = -1;
433     best.cColorBits = -1;
434     best.cDepthBits = -1;
435     best.cStencilBits = -1;
436     best.cAuxBuffers = -1;
437
438     for (i = 1; i <= count; i++)
439     {
440         if (!wglDescribePixelFormat( hdc, i, sizeof(format), &format )) continue;
441
442         if (ppfd->iPixelType != format.iPixelType)
443         {
444             TRACE( "pixel type mismatch for iPixelFormat=%d\n", i );
445             continue;
446         }
447
448         /* only use bitmap capable for formats for bitmap rendering */
449         if( (ppfd->dwFlags & PFD_DRAW_TO_BITMAP) != (format.dwFlags & PFD_DRAW_TO_BITMAP))
450         {
451             TRACE( "PFD_DRAW_TO_BITMAP mismatch for iPixelFormat=%d\n", i );
452             continue;
453         }
454
455         /* The behavior of PDF_STEREO/PFD_STEREO_DONTCARE and PFD_DOUBLEBUFFER / PFD_DOUBLEBUFFER_DONTCARE
456          * is not very clear on MSDN. They specify that ChoosePixelFormat tries to match pixel formats
457          * with the flag (PFD_STEREO / PFD_DOUBLEBUFFERING) set. Otherwise it says that it tries to match
458          * formats without the given flag set.
459          * A test on Windows using a Radeon 9500pro on WinXP (the driver doesn't support Stereo)
460          * has indicated that a format without stereo is returned when stereo is unavailable.
461          * So in case PFD_STEREO is set, formats that support it should have priority above formats
462          * without. In case PFD_STEREO_DONTCARE is set, stereo is ignored.
463          *
464          * To summarize the following is most likely the correct behavior:
465          * stereo not set -> prefer non-stereo formats, but also accept stereo formats
466          * stereo set -> prefer stereo formats, but also accept non-stereo formats
467          * stereo don't care -> it doesn't matter whether we get stereo or not
468          *
469          * In Wine we will treat non-stereo the same way as don't care because it makes
470          * format selection even more complicated and second drivers with Stereo advertise
471          * each format twice anyway.
472          */
473
474         /* Doublebuffer, see the comments above */
475         if (!(ppfd->dwFlags & PFD_DOUBLEBUFFER_DONTCARE))
476         {
477             if (((ppfd->dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer) &&
478                 ((format.dwFlags & PFD_DOUBLEBUFFER) == (ppfd->dwFlags & PFD_DOUBLEBUFFER)))
479                 goto found;
480
481             if (bestDBuffer != -1 && (format.dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer) continue;
482         }
483
484         /* Stereo, see the comments above. */
485         if (!(ppfd->dwFlags & PFD_STEREO_DONTCARE))
486         {
487             if (((ppfd->dwFlags & PFD_STEREO) != bestStereo) &&
488                 ((format.dwFlags & PFD_STEREO) == (ppfd->dwFlags & PFD_STEREO)))
489                 goto found;
490
491             if (bestStereo != -1 && (format.dwFlags & PFD_STEREO) != bestStereo) continue;
492         }
493
494         /* Below we will do a number of checks to select the 'best' pixelformat.
495          * We assume the precedence cColorBits > cAlphaBits > cDepthBits > cStencilBits -> cAuxBuffers.
496          * The code works by trying to match the most important options as close as possible.
497          * When a reasonable format is found, we will try to match more options.
498          * It appears (see the opengl32 test) that Windows opengl drivers ignore options
499          * like cColorBits, cAlphaBits and friends if they are set to 0, so they are considered
500          * as DONTCARE. At least Serious Sam TSE relies on this behavior. */
501
502         if (ppfd->cColorBits)
503         {
504             if (((ppfd->cColorBits > best.cColorBits) && (format.cColorBits > best.cColorBits)) ||
505                 ((format.cColorBits >= ppfd->cColorBits) && (format.cColorBits < best.cColorBits)))
506                 goto found;
507
508             if (best.cColorBits != format.cColorBits)  /* Do further checks if the format is compatible */
509             {
510                 TRACE( "color mismatch for iPixelFormat=%d\n", i );
511                 continue;
512             }
513         }
514         if (ppfd->cAlphaBits)
515         {
516             if (((ppfd->cAlphaBits > best.cAlphaBits) && (format.cAlphaBits > best.cAlphaBits)) ||
517                 ((format.cAlphaBits >= ppfd->cAlphaBits) && (format.cAlphaBits < best.cAlphaBits)))
518                 goto found;
519
520             if (best.cAlphaBits != format.cAlphaBits)
521             {
522                 TRACE( "alpha mismatch for iPixelFormat=%d\n", i );
523                 continue;
524             }
525         }
526         if (ppfd->cDepthBits)
527         {
528             if (((ppfd->cDepthBits > best.cDepthBits) && (format.cDepthBits > best.cDepthBits)) ||
529                 ((format.cDepthBits >= ppfd->cDepthBits) && (format.cDepthBits < best.cDepthBits)))
530                 goto found;
531
532             if (best.cDepthBits != format.cDepthBits)
533             {
534                 TRACE( "depth mismatch for iPixelFormat=%d\n", i );
535                 continue;
536             }
537         }
538         if (ppfd->cStencilBits)
539         {
540             if (((ppfd->cStencilBits > best.cStencilBits) && (format.cStencilBits > best.cStencilBits)) ||
541                 ((format.cStencilBits >= ppfd->cStencilBits) && (format.cStencilBits < best.cStencilBits)))
542                 goto found;
543
544             if (best.cStencilBits != format.cStencilBits)
545             {
546                 TRACE( "stencil mismatch for iPixelFormat=%d\n", i );
547                 continue;
548             }
549         }
550         if (ppfd->cAuxBuffers)
551         {
552             if (((ppfd->cAuxBuffers > best.cAuxBuffers) && (format.cAuxBuffers > best.cAuxBuffers)) ||
553                 ((format.cAuxBuffers >= ppfd->cAuxBuffers) && (format.cAuxBuffers < best.cAuxBuffers)))
554                 goto found;
555
556             if (best.cAuxBuffers != format.cAuxBuffers)
557             {
558                 TRACE( "aux mismatch for iPixelFormat=%d\n", i );
559                 continue;
560             }
561         }
562         continue;
563
564     found:
565         best_format = i;
566         best = format;
567         bestDBuffer = format.dwFlags & PFD_DOUBLEBUFFER;
568         bestStereo = format.dwFlags & PFD_STEREO;
569     }
570
571     TRACE( "returning %u\n", best_format );
572     return best_format;
573 }
574
575 /***********************************************************************
576  *              wglGetPixelFormat (OPENGL32.@)
577  */
578 INT WINAPI wglGetPixelFormat(HDC hdc)
579 {
580     struct opengl_funcs *funcs = get_dc_funcs( hdc );
581     if (!funcs) return 0;
582     return funcs->wgl.p_wglGetPixelFormat( hdc );
583 }
584
585 /***********************************************************************
586  *               wglSetPixelFormat(OPENGL32.@)
587  */
588 BOOL WINAPI wglSetPixelFormat( HDC hdc, INT format, const PIXELFORMATDESCRIPTOR *descr )
589 {
590     struct opengl_funcs *funcs = get_dc_funcs( hdc );
591     if (!funcs) return 0;
592     return funcs->wgl.p_wglSetPixelFormat( hdc, format, descr );
593 }
594
595 /***********************************************************************
596  *              wglSwapBuffers (OPENGL32.@)
597  */
598 BOOL WINAPI DECLSPEC_HOTPATCH wglSwapBuffers( HDC hdc )
599 {
600     const struct opengl_funcs *funcs = get_dc_funcs( hdc );
601
602     if (!funcs || !funcs->wgl.p_wglSwapBuffers) return FALSE;
603     if (!funcs->wgl.p_wglSwapBuffers( hdc )) return FALSE;
604
605     if (TRACE_ON(fps))
606     {
607         static long prev_time, start_time;
608         static unsigned long frames, frames_total;
609
610         DWORD time = GetTickCount();
611         frames++;
612         frames_total++;
613         /* every 1.5 seconds */
614         if (time - prev_time > 1500)
615         {
616             TRACE_(fps)("@ approx %.2ffps, total %.2ffps\n",
617                         1000.0*frames/(time - prev_time), 1000.0*frames_total/(time - start_time));
618             prev_time = time;
619             frames = 0;
620             if (start_time == 0) start_time = time;
621         }
622     }
623     return TRUE;
624 }
625
626 /***********************************************************************
627  *              wglCreateLayerContext (OPENGL32.@)
628  */
629 HGLRC WINAPI wglCreateLayerContext(HDC hdc,
630                                    int iLayerPlane) {
631   TRACE("(%p,%d)\n", hdc, iLayerPlane);
632
633   if (iLayerPlane == 0) {
634       return wglCreateContext(hdc);
635   }
636   FIXME("no handler for layer %d\n", iLayerPlane);
637
638   return NULL;
639 }
640
641 /***********************************************************************
642  *              wglDescribeLayerPlane (OPENGL32.@)
643  */
644 BOOL WINAPI wglDescribeLayerPlane(HDC hdc,
645                                   int iPixelFormat,
646                                   int iLayerPlane,
647                                   UINT nBytes,
648                                   LPLAYERPLANEDESCRIPTOR plpd) {
649   FIXME("(%p,%d,%d,%d,%p)\n", hdc, iPixelFormat, iLayerPlane, nBytes, plpd);
650
651   return FALSE;
652 }
653
654 /***********************************************************************
655  *              wglGetLayerPaletteEntries (OPENGL32.@)
656  */
657 int WINAPI wglGetLayerPaletteEntries(HDC hdc,
658                                      int iLayerPlane,
659                                      int iStart,
660                                      int cEntries,
661                                      const COLORREF *pcr) {
662   FIXME("(): stub!\n");
663
664   return 0;
665 }
666
667 /* check if the extension is present in the list */
668 static BOOL has_extension( const char *list, const char *ext )
669 {
670     size_t len = strlen( ext );
671
672     while (list)
673     {
674         while (*list == ' ') list++;
675         if (!strncmp( list, ext, len ) && (!list[len] || list[len] == ' ')) return TRUE;
676         list = strchr( list, ' ' );
677     }
678     return FALSE;
679 }
680
681 static int compar(const void *elt_a, const void *elt_b) {
682   return strcmp(((const OpenGL_extension *) elt_a)->name,
683                 ((const OpenGL_extension *) elt_b)->name);
684 }
685
686 /* Check if a GL extension is supported */
687 static BOOL is_extension_supported(const char* extension)
688 {
689     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
690     const char *gl_ext_string = (const char*)glGetString(GL_EXTENSIONS);
691
692     TRACE("Checking for extension '%s'\n", extension);
693
694     if(!gl_ext_string) {
695         ERR("No OpenGL extensions found, check if your OpenGL setup is correct!\n");
696         return FALSE;
697     }
698
699     /* We use the GetProcAddress function from the display driver to retrieve function pointers
700      * for OpenGL and WGL extensions. In case of winex11.drv the OpenGL extension lookup is done
701      * using glXGetProcAddress. This function is quite unreliable in the sense that its specs don't
702      * require the function to return NULL when an extension isn't found. For this reason we check
703      * if the OpenGL extension required for the function we are looking up is supported. */
704
705     /* Check if the extension is part of the GL extension string to see if it is supported. */
706     if (has_extension(gl_ext_string, extension))
707         return TRUE;
708
709     /* In general an OpenGL function starts as an ARB/EXT extension and at some stage
710      * it becomes part of the core OpenGL library and can be reached without the ARB/EXT
711      * suffix as well. In the extension table, these functions contain GL_VERSION_major_minor.
712      * Check if we are searching for a core GL function */
713     if(strncmp(extension, "GL_VERSION_", 11) == 0)
714     {
715         const GLubyte *gl_version = funcs->gl.p_glGetString(GL_VERSION);
716         const char *version = extension + 11; /* Move past 'GL_VERSION_' */
717
718         if(!gl_version) {
719             ERR("No OpenGL version found!\n");
720             return FALSE;
721         }
722
723         /* Compare the major/minor version numbers of the native OpenGL library and what is required by the function.
724          * The gl_version string is guaranteed to have at least a major/minor and sometimes it has a release number as well. */
725         if( (gl_version[0] >= version[0]) || ((gl_version[0] == version[0]) && (gl_version[2] >= version[2])) ) {
726             return TRUE;
727         }
728         WARN("The function requires OpenGL version '%c.%c' while your drivers only provide '%c.%c'\n", version[0], version[2], gl_version[0], gl_version[2]);
729     }
730
731     return FALSE;
732 }
733
734 /***********************************************************************
735  *              wglGetProcAddress (OPENGL32.@)
736  */
737 PROC WINAPI wglGetProcAddress( LPCSTR name )
738 {
739     struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
740     void **func_ptr;
741     OpenGL_extension  ext;
742     const OpenGL_extension *ext_ret;
743
744     if (!name) return NULL;
745
746     /* Without an active context opengl32 doesn't know to what
747      * driver it has to dispatch wglGetProcAddress.
748      */
749     if (!get_current_context_ptr())
750     {
751         WARN("No active WGL context found\n");
752         return NULL;
753     }
754
755     ext.name = name;
756     ext_ret = bsearch(&ext, extension_registry, extension_registry_size, sizeof(ext), compar);
757     if (!ext_ret)
758     {
759         WARN("Function %s unknown\n", name);
760         return NULL;
761     }
762
763     func_ptr = (void **)&funcs->ext + (ext_ret - extension_registry);
764     if (!*func_ptr)
765     {
766         void *driver_func = funcs->wgl.p_wglGetProcAddress( name );
767
768         if (!is_extension_supported(ext_ret->extension))
769             WARN("Extension %s required for %s not supported\n", ext_ret->extension, name);
770
771         if (driver_func == NULL)
772         {
773             WARN("Function %s not supported by driver\n", name);
774             return NULL;
775         }
776         *func_ptr = driver_func;
777     }
778
779     TRACE("returning %s -> %p\n", name, ext_ret->func);
780     return ext_ret->func;
781 }
782
783 /***********************************************************************
784  *              wglRealizeLayerPalette (OPENGL32.@)
785  */
786 BOOL WINAPI wglRealizeLayerPalette(HDC hdc,
787                                    int iLayerPlane,
788                                    BOOL bRealize) {
789   FIXME("()\n");
790
791   return FALSE;
792 }
793
794 /***********************************************************************
795  *              wglSetLayerPaletteEntries (OPENGL32.@)
796  */
797 int WINAPI wglSetLayerPaletteEntries(HDC hdc,
798                                      int iLayerPlane,
799                                      int iStart,
800                                      int cEntries,
801                                      const COLORREF *pcr) {
802   FIXME("(): stub!\n");
803
804   return 0;
805 }
806
807 /***********************************************************************
808  *              wglSwapLayerBuffers (OPENGL32.@)
809  */
810 BOOL WINAPI wglSwapLayerBuffers(HDC hdc,
811                                 UINT fuPlanes) {
812   TRACE("(%p, %08x)\n", hdc, fuPlanes);
813
814   if (fuPlanes & WGL_SWAP_MAIN_PLANE) {
815     if (!wglSwapBuffers( hdc )) return FALSE;
816     fuPlanes &= ~WGL_SWAP_MAIN_PLANE;
817   }
818
819   if (fuPlanes) {
820     WARN("Following layers unhandled: %08x\n", fuPlanes);
821   }
822
823   return TRUE;
824 }
825
826 /***********************************************************************
827  *              wglAllocateMemoryNV
828  *
829  * Provided by the WGL_NV_vertex_array_range extension.
830  */
831 void * WINAPI wglAllocateMemoryNV( GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority )
832 {
833     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
834
835     if (!funcs->ext.p_wglAllocateMemoryNV) return NULL;
836     return funcs->ext.p_wglAllocateMemoryNV( size, readfreq, writefreq, priority );
837 }
838
839 /***********************************************************************
840  *              wglFreeMemoryNV
841  *
842  * Provided by the WGL_NV_vertex_array_range extension.
843  */
844 void WINAPI wglFreeMemoryNV( void *pointer )
845 {
846     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
847
848     if (funcs->ext.p_wglFreeMemoryNV) funcs->ext.p_wglFreeMemoryNV( pointer );
849 }
850
851 /***********************************************************************
852  *              wglBindTexImageARB
853  *
854  * Provided by the WGL_ARB_render_texture extension.
855  */
856 BOOL WINAPI wglBindTexImageARB( HPBUFFERARB handle, int buffer )
857 {
858     struct wgl_handle *ptr = get_handle_ptr( handle, HANDLE_PBUFFER );
859     BOOL ret;
860
861     if (!ptr) return FALSE;
862     ret = ptr->funcs->ext.p_wglBindTexImageARB( ptr->u.pbuffer, buffer );
863     release_handle_ptr( ptr );
864     return ret;
865 }
866
867 /***********************************************************************
868  *              wglReleaseTexImageARB
869  *
870  * Provided by the WGL_ARB_render_texture extension.
871  */
872 BOOL WINAPI wglReleaseTexImageARB( HPBUFFERARB handle, int buffer )
873 {
874     struct wgl_handle *ptr = get_handle_ptr( handle, HANDLE_PBUFFER );
875     BOOL ret;
876
877     if (!ptr) return FALSE;
878     ret = ptr->funcs->ext.p_wglReleaseTexImageARB( ptr->u.pbuffer, buffer );
879     release_handle_ptr( ptr );
880     return ret;
881 }
882
883 /***********************************************************************
884  *              wglSetPbufferAttribARB
885  *
886  * Provided by the WGL_ARB_render_texture extension.
887  */
888 BOOL WINAPI wglSetPbufferAttribARB( HPBUFFERARB handle, const int *attribs )
889 {
890     struct wgl_handle *ptr = get_handle_ptr( handle, HANDLE_PBUFFER );
891     BOOL ret;
892
893     if (!ptr) return FALSE;
894     ret = ptr->funcs->ext.p_wglSetPbufferAttribARB( ptr->u.pbuffer, attribs );
895     release_handle_ptr( ptr );
896     return ret;
897 }
898
899 /***********************************************************************
900  *              wglChoosePixelFormatARB
901  *
902  * Provided by the WGL_ARB_pixel_format extension.
903  */
904 BOOL WINAPI wglChoosePixelFormatARB( HDC hdc, const int *iattribs, const FLOAT *fattribs,
905                                      UINT max, int *formats, UINT *count )
906 {
907     const struct opengl_funcs *funcs = get_dc_funcs( hdc );
908
909     if (!funcs || !funcs->ext.p_wglChoosePixelFormatARB) return FALSE;
910     return funcs->ext.p_wglChoosePixelFormatARB( hdc, iattribs, fattribs, max, formats, count );
911 }
912
913 /***********************************************************************
914  *              wglGetPixelFormatAttribivARB
915  *
916  * Provided by the WGL_ARB_pixel_format extension.
917  */
918 BOOL WINAPI wglGetPixelFormatAttribivARB( HDC hdc, int format, int layer, UINT count, const int *attribs,
919                                           int *values )
920 {
921     const struct opengl_funcs *funcs = get_dc_funcs( hdc );
922
923     if (!funcs || !funcs->ext.p_wglGetPixelFormatAttribivARB) return FALSE;
924     return funcs->ext.p_wglGetPixelFormatAttribivARB( hdc, format, layer, count, attribs, values );
925 }
926
927 /***********************************************************************
928  *              wglGetPixelFormatAttribfvARB
929  *
930  * Provided by the WGL_ARB_pixel_format extension.
931  */
932 BOOL WINAPI wglGetPixelFormatAttribfvARB( HDC hdc, int format, int layer, UINT count, const int *attribs,
933                                           FLOAT *values )
934 {
935     const struct opengl_funcs *funcs = get_dc_funcs( hdc );
936
937     if (!funcs || !funcs->ext.p_wglGetPixelFormatAttribfvARB) return FALSE;
938     return funcs->ext.p_wglGetPixelFormatAttribfvARB( hdc, format, layer, count, attribs, values );
939 }
940
941 /***********************************************************************
942  *              wglCreatePbufferARB
943  *
944  * Provided by the WGL_ARB_pbuffer extension.
945  */
946 HPBUFFERARB WINAPI wglCreatePbufferARB( HDC hdc, int format, int width, int height, const int *attribs )
947 {
948     HPBUFFERARB ret = 0;
949     struct wgl_pbuffer *pbuffer;
950     struct opengl_funcs *funcs = get_dc_funcs( hdc );
951
952     if (!funcs || !funcs->ext.p_wglCreatePbufferARB) return 0;
953     if (!(pbuffer = funcs->ext.p_wglCreatePbufferARB( hdc, format, width, height, attribs ))) return 0;
954     ret = alloc_handle( HANDLE_PBUFFER, funcs, pbuffer );
955     if (!ret) funcs->ext.p_wglDestroyPbufferARB( pbuffer );
956     return ret;
957 }
958
959 /***********************************************************************
960  *              wglGetPbufferDCARB
961  *
962  * Provided by the WGL_ARB_pbuffer extension.
963  */
964 HDC WINAPI wglGetPbufferDCARB( HPBUFFERARB handle )
965 {
966     struct wgl_handle *ptr = get_handle_ptr( handle, HANDLE_PBUFFER );
967     HDC ret;
968
969     if (!ptr) return 0;
970     ret = ptr->funcs->ext.p_wglGetPbufferDCARB( ptr->u.pbuffer );
971     release_handle_ptr( ptr );
972     return ret;
973 }
974
975 /***********************************************************************
976  *              wglReleasePbufferDCARB
977  *
978  * Provided by the WGL_ARB_pbuffer extension.
979  */
980 int WINAPI wglReleasePbufferDCARB( HPBUFFERARB handle, HDC hdc )
981 {
982     struct wgl_handle *ptr = get_handle_ptr( handle, HANDLE_PBUFFER );
983     BOOL ret;
984
985     if (!ptr) return FALSE;
986     ret = ptr->funcs->ext.p_wglReleasePbufferDCARB( ptr->u.pbuffer, hdc );
987     release_handle_ptr( ptr );
988     return ret;
989 }
990
991 /***********************************************************************
992  *              wglDestroyPbufferARB
993  *
994  * Provided by the WGL_ARB_pbuffer extension.
995  */
996 BOOL WINAPI wglDestroyPbufferARB( HPBUFFERARB handle )
997 {
998     struct wgl_handle *ptr = get_handle_ptr( handle, HANDLE_PBUFFER );
999
1000     if (!ptr) return FALSE;
1001     ptr->funcs->ext.p_wglDestroyPbufferARB( ptr->u.pbuffer );
1002     free_handle_ptr( ptr );
1003     return TRUE;
1004 }
1005
1006 /***********************************************************************
1007  *              wglQueryPbufferARB
1008  *
1009  * Provided by the WGL_ARB_pbuffer extension.
1010  */
1011 BOOL WINAPI wglQueryPbufferARB( HPBUFFERARB handle, int attrib, int *value )
1012 {
1013     struct wgl_handle *ptr = get_handle_ptr( handle, HANDLE_PBUFFER );
1014     BOOL ret;
1015
1016     if (!ptr) return FALSE;
1017     ret = ptr->funcs->ext.p_wglQueryPbufferARB( ptr->u.pbuffer, attrib, value );
1018     release_handle_ptr( ptr );
1019     return ret;
1020 }
1021
1022 /***********************************************************************
1023  *              wglGetExtensionsStringARB
1024  *
1025  * Provided by the WGL_ARB_extensions_string extension.
1026  */
1027 const char * WINAPI wglGetExtensionsStringARB( HDC hdc )
1028 {
1029     const struct opengl_funcs *funcs = get_dc_funcs( hdc );
1030
1031     if (!funcs || !funcs->ext.p_wglGetExtensionsStringARB) return NULL;
1032     return (const char *)funcs->ext.p_wglGetExtensionsStringARB( hdc );
1033 }
1034
1035 /***********************************************************************
1036  *              wglGetExtensionsStringEXT
1037  *
1038  * Provided by the WGL_EXT_extensions_string extension.
1039  */
1040 const char * WINAPI wglGetExtensionsStringEXT(void)
1041 {
1042     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1043
1044     if (!funcs->ext.p_wglGetExtensionsStringEXT) return NULL;
1045     return (const char *)funcs->ext.p_wglGetExtensionsStringEXT();
1046 }
1047
1048 /***********************************************************************
1049  *              wglSwapIntervalEXT
1050  *
1051  * Provided by the WGL_EXT_swap_control extension.
1052  */
1053 BOOL WINAPI wglSwapIntervalEXT( int interval )
1054 {
1055     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1056
1057     if (!funcs->ext.p_wglSwapIntervalEXT) return FALSE;
1058     return funcs->ext.p_wglSwapIntervalEXT( interval );
1059 }
1060
1061 /***********************************************************************
1062  *              wglGetSwapIntervalEXT
1063  *
1064  * Provided by the WGL_EXT_swap_control extension.
1065  */
1066 int WINAPI wglGetSwapIntervalEXT(void)
1067 {
1068     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1069
1070     if (!funcs->ext.p_wglGetSwapIntervalEXT) return FALSE;
1071     return funcs->ext.p_wglGetSwapIntervalEXT();
1072 }
1073
1074 /***********************************************************************
1075  *              wglSetPixelFormatWINE
1076  *
1077  * Provided by the WGL_WINE_pixel_format_passthrough extension.
1078  */
1079 BOOL WINAPI wglSetPixelFormatWINE( HDC hdc, int format )
1080 {
1081     const struct opengl_funcs *funcs = get_dc_funcs( hdc );
1082
1083     if (!funcs || !funcs->ext.p_wglSetPixelFormatWINE) return FALSE;
1084     return funcs->ext.p_wglSetPixelFormatWINE( hdc, format );
1085 }
1086
1087 /***********************************************************************
1088  *              wglUseFontBitmaps_common
1089  */
1090 static BOOL wglUseFontBitmaps_common( HDC hdc, DWORD first, DWORD count, DWORD listBase, BOOL unicode )
1091 {
1092     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1093      GLYPHMETRICS gm;
1094      unsigned int glyph, size = 0;
1095      void *bitmap = NULL, *gl_bitmap = NULL;
1096      int org_alignment;
1097      BOOL ret = TRUE;
1098
1099      funcs->gl.p_glGetIntegerv(GL_UNPACK_ALIGNMENT, &org_alignment);
1100      funcs->gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
1101
1102      for (glyph = first; glyph < first + count; glyph++) {
1103          static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
1104          unsigned int needed_size, height, width, width_int;
1105
1106          if (unicode)
1107              needed_size = GetGlyphOutlineW(hdc, glyph, GGO_BITMAP, &gm, 0, NULL, &identity);
1108          else
1109              needed_size = GetGlyphOutlineA(hdc, glyph, GGO_BITMAP, &gm, 0, NULL, &identity);
1110
1111          TRACE("Glyph: %3d / List: %d size %d\n", glyph, listBase, needed_size);
1112          if (needed_size == GDI_ERROR) {
1113              ret = FALSE;
1114              break;
1115          }
1116
1117          if (needed_size > size) {
1118              size = needed_size;
1119              HeapFree(GetProcessHeap(), 0, bitmap);
1120              HeapFree(GetProcessHeap(), 0, gl_bitmap);
1121              bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
1122              gl_bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
1123          }
1124          if (unicode)
1125              ret = (GetGlyphOutlineW(hdc, glyph, GGO_BITMAP, &gm, size, bitmap, &identity) != GDI_ERROR);
1126          else
1127              ret = (GetGlyphOutlineA(hdc, glyph, GGO_BITMAP, &gm, size, bitmap, &identity) != GDI_ERROR);
1128          if (!ret) break;
1129
1130          if (TRACE_ON(wgl)) {
1131              unsigned int bitmask;
1132              unsigned char *bitmap_ = bitmap;
1133
1134              TRACE("  - bbox: %d x %d\n", gm.gmBlackBoxX, gm.gmBlackBoxY);
1135              TRACE("  - origin: (%d, %d)\n", gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
1136              TRACE("  - increment: %d - %d\n", gm.gmCellIncX, gm.gmCellIncY);
1137              if (needed_size != 0) {
1138                  TRACE("  - bitmap:\n");
1139                  for (height = 0; height < gm.gmBlackBoxY; height++) {
1140                      TRACE("      ");
1141                      for (width = 0, bitmask = 0x80; width < gm.gmBlackBoxX; width++, bitmask >>= 1) {
1142                          if (bitmask == 0) {
1143                              bitmap_ += 1;
1144                              bitmask = 0x80;
1145                          }
1146                          if (*bitmap_ & bitmask)
1147                              TRACE("*");
1148                          else
1149                              TRACE(" ");
1150                      }
1151                      bitmap_ += (4 - ((UINT_PTR)bitmap_ & 0x03));
1152                      TRACE("\n");
1153                  }
1154              }
1155          }
1156
1157          /* In OpenGL, the bitmap is drawn from the bottom to the top... So we need to invert the
1158          * glyph for it to be drawn properly.
1159          */
1160          if (needed_size != 0) {
1161              width_int = (gm.gmBlackBoxX + 31) / 32;
1162              for (height = 0; height < gm.gmBlackBoxY; height++) {
1163                  for (width = 0; width < width_int; width++) {
1164                      ((int *) gl_bitmap)[(gm.gmBlackBoxY - height - 1) * width_int + width] =
1165                      ((int *) bitmap)[height * width_int + width];
1166                  }
1167              }
1168          }
1169
1170          funcs->gl.p_glNewList(listBase++, GL_COMPILE);
1171          if (needed_size != 0) {
1172              funcs->gl.p_glBitmap(gm.gmBlackBoxX, gm.gmBlackBoxY,
1173                      0 - gm.gmptGlyphOrigin.x, (int) gm.gmBlackBoxY - gm.gmptGlyphOrigin.y,
1174                      gm.gmCellIncX, gm.gmCellIncY,
1175                      gl_bitmap);
1176          } else {
1177              /* This is the case of 'empty' glyphs like the space character */
1178              funcs->gl.p_glBitmap(0, 0, 0, 0, gm.gmCellIncX, gm.gmCellIncY, NULL);
1179          }
1180          funcs->gl.p_glEndList();
1181      }
1182
1183      funcs->gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
1184      HeapFree(GetProcessHeap(), 0, bitmap);
1185      HeapFree(GetProcessHeap(), 0, gl_bitmap);
1186      return ret;
1187 }
1188
1189 /***********************************************************************
1190  *              wglUseFontBitmapsA (OPENGL32.@)
1191  */
1192 BOOL WINAPI wglUseFontBitmapsA(HDC hdc, DWORD first, DWORD count, DWORD listBase)
1193 {
1194     return wglUseFontBitmaps_common( hdc, first, count, listBase, FALSE );
1195 }
1196
1197 /***********************************************************************
1198  *              wglUseFontBitmapsW (OPENGL32.@)
1199  */
1200 BOOL WINAPI wglUseFontBitmapsW(HDC hdc, DWORD first, DWORD count, DWORD listBase)
1201 {
1202     return wglUseFontBitmaps_common( hdc, first, count, listBase, TRUE );
1203 }
1204
1205 /* FIXME: should probably have a glu.h header */
1206
1207 typedef struct GLUtesselator GLUtesselator;
1208 typedef void (WINAPI *_GLUfuncptr)(void);
1209
1210 #define GLU_TESS_BEGIN  100100
1211 #define GLU_TESS_VERTEX 100101
1212 #define GLU_TESS_END    100102
1213
1214 static GLUtesselator * (WINAPI *pgluNewTess)(void);
1215 static void (WINAPI *pgluDeleteTess)(GLUtesselator *tess);
1216 static void (WINAPI *pgluTessNormal)(GLUtesselator *tess, GLdouble x, GLdouble y, GLdouble z);
1217 static void (WINAPI *pgluTessBeginPolygon)(GLUtesselator *tess, void *polygon_data);
1218 static void (WINAPI *pgluTessEndPolygon)(GLUtesselator *tess);
1219 static void (WINAPI *pgluTessCallback)(GLUtesselator *tess, GLenum which, _GLUfuncptr fn);
1220 static void (WINAPI *pgluTessBeginContour)(GLUtesselator *tess);
1221 static void (WINAPI *pgluTessEndContour)(GLUtesselator *tess);
1222 static void (WINAPI *pgluTessVertex)(GLUtesselator *tess, GLdouble *location, GLvoid* data);
1223
1224 static HMODULE load_libglu(void)
1225 {
1226     static const WCHAR glu32W[] = {'g','l','u','3','2','.','d','l','l',0};
1227     static int already_loaded;
1228     static HMODULE module;
1229
1230     if (already_loaded) return module;
1231     already_loaded = 1;
1232
1233     TRACE("Trying to load GLU library\n");
1234     module = LoadLibraryW( glu32W );
1235     if (!module)
1236     {
1237         WARN("Failed to load glu32\n");
1238         return NULL;
1239     }
1240 #define LOAD_FUNCPTR(f) p##f = (void *)GetProcAddress( module, #f )
1241     LOAD_FUNCPTR(gluNewTess);
1242     LOAD_FUNCPTR(gluDeleteTess);
1243     LOAD_FUNCPTR(gluTessBeginContour);
1244     LOAD_FUNCPTR(gluTessNormal);
1245     LOAD_FUNCPTR(gluTessBeginPolygon);
1246     LOAD_FUNCPTR(gluTessCallback);
1247     LOAD_FUNCPTR(gluTessEndContour);
1248     LOAD_FUNCPTR(gluTessEndPolygon);
1249     LOAD_FUNCPTR(gluTessVertex);
1250 #undef LOAD_FUNCPTR
1251     return module;
1252 }
1253
1254 static void fixed_to_double(POINTFX fixed, UINT em_size, GLdouble vertex[3])
1255 {
1256     vertex[0] = (fixed.x.value + (GLdouble)fixed.x.fract / (1 << 16)) / em_size;  
1257     vertex[1] = (fixed.y.value + (GLdouble)fixed.y.fract / (1 << 16)) / em_size;  
1258     vertex[2] = 0.0;
1259 }
1260
1261 static void WINAPI tess_callback_vertex(GLvoid *vertex)
1262 {
1263     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1264     GLdouble *dbl = vertex;
1265     TRACE("%f, %f, %f\n", dbl[0], dbl[1], dbl[2]);
1266     funcs->gl.p_glVertex3dv(vertex);
1267 }
1268
1269 static void WINAPI tess_callback_begin(GLenum which)
1270 {
1271     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1272     TRACE("%d\n", which);
1273     funcs->gl.p_glBegin(which);
1274 }
1275
1276 static void WINAPI tess_callback_end(void)
1277 {
1278     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1279     TRACE("\n");
1280     funcs->gl.p_glEnd();
1281 }
1282
1283 typedef struct _bezier_vector {
1284     GLdouble x;
1285     GLdouble y;
1286 } bezier_vector;
1287
1288 static double bezier_deviation_squared(const bezier_vector *p)
1289 {
1290     bezier_vector deviation;
1291     bezier_vector vertex;
1292     bezier_vector base;
1293     double base_length;
1294     double dot;
1295
1296     vertex.x = (p[0].x + p[1].x*2 + p[2].x)/4 - p[0].x;
1297     vertex.y = (p[0].y + p[1].y*2 + p[2].y)/4 - p[0].y;
1298
1299     base.x = p[2].x - p[0].x;
1300     base.y = p[2].y - p[0].y;
1301
1302     base_length = sqrt(base.x*base.x + base.y*base.y);
1303     base.x /= base_length;
1304     base.y /= base_length;
1305
1306     dot = base.x*vertex.x + base.y*vertex.y;
1307     dot = min(max(dot, 0.0), base_length);
1308     base.x *= dot;
1309     base.y *= dot;
1310
1311     deviation.x = vertex.x-base.x;
1312     deviation.y = vertex.y-base.y;
1313
1314     return deviation.x*deviation.x + deviation.y*deviation.y;
1315 }
1316
1317 static int bezier_approximate(const bezier_vector *p, bezier_vector *points, FLOAT deviation)
1318 {
1319     bezier_vector first_curve[3];
1320     bezier_vector second_curve[3];
1321     bezier_vector vertex;
1322     int total_vertices;
1323
1324     if(bezier_deviation_squared(p) <= deviation*deviation)
1325     {
1326         if(points)
1327             *points = p[2];
1328         return 1;
1329     }
1330
1331     vertex.x = (p[0].x + p[1].x*2 + p[2].x)/4;
1332     vertex.y = (p[0].y + p[1].y*2 + p[2].y)/4;
1333
1334     first_curve[0] = p[0];
1335     first_curve[1].x = (p[0].x + p[1].x)/2;
1336     first_curve[1].y = (p[0].y + p[1].y)/2;
1337     first_curve[2] = vertex;
1338
1339     second_curve[0] = vertex;
1340     second_curve[1].x = (p[2].x + p[1].x)/2;
1341     second_curve[1].y = (p[2].y + p[1].y)/2;
1342     second_curve[2] = p[2];
1343
1344     total_vertices = bezier_approximate(first_curve, points, deviation);
1345     if(points)
1346         points += total_vertices;
1347     total_vertices += bezier_approximate(second_curve, points, deviation);
1348     return total_vertices;
1349 }
1350
1351 /***********************************************************************
1352  *              wglUseFontOutlines_common
1353  */
1354 static BOOL wglUseFontOutlines_common(HDC hdc,
1355                                       DWORD first,
1356                                       DWORD count,
1357                                       DWORD listBase,
1358                                       FLOAT deviation,
1359                                       FLOAT extrusion,
1360                                       int format,
1361                                       LPGLYPHMETRICSFLOAT lpgmf,
1362                                       BOOL unicode)
1363 {
1364     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1365     UINT glyph;
1366     const MAT2 identity = {{0,1},{0,0},{0,0},{0,1}};
1367     GLUtesselator *tess = NULL;
1368     LOGFONTW lf;
1369     HFONT old_font, unscaled_font;
1370     UINT em_size = 1024;
1371     RECT rc;
1372
1373     TRACE("(%p, %d, %d, %d, %f, %f, %d, %p, %s)\n", hdc, first, count,
1374           listBase, deviation, extrusion, format, lpgmf, unicode ? "W" : "A");
1375
1376     if(deviation <= 0.0)
1377         deviation = 1.0/em_size;
1378
1379     if(format == WGL_FONT_POLYGONS)
1380     {
1381         if (!load_libglu())
1382         {
1383             ERR("glu32 is required for this function but isn't available\n");
1384             return FALSE;
1385         }
1386
1387         tess = pgluNewTess();
1388         if(!tess) return FALSE;
1389         pgluTessCallback(tess, GLU_TESS_VERTEX, (_GLUfuncptr)tess_callback_vertex);
1390         pgluTessCallback(tess, GLU_TESS_BEGIN, (_GLUfuncptr)tess_callback_begin);
1391         pgluTessCallback(tess, GLU_TESS_END, tess_callback_end);
1392     }
1393
1394     GetObjectW(GetCurrentObject(hdc, OBJ_FONT), sizeof(lf), &lf);
1395     rc.left = rc.right = rc.bottom = 0;
1396     rc.top = em_size;
1397     DPtoLP(hdc, (POINT*)&rc, 2);
1398     lf.lfHeight = -abs(rc.top - rc.bottom);
1399     lf.lfOrientation = lf.lfEscapement = 0;
1400     unscaled_font = CreateFontIndirectW(&lf);
1401     old_font = SelectObject(hdc, unscaled_font);
1402
1403     for (glyph = first; glyph < first + count; glyph++)
1404     {
1405         DWORD needed;
1406         GLYPHMETRICS gm;
1407         BYTE *buf;
1408         TTPOLYGONHEADER *pph;
1409         TTPOLYCURVE *ppc;
1410         GLdouble *vertices = NULL;
1411         int vertex_total = -1;
1412
1413         if(unicode)
1414             needed = GetGlyphOutlineW(hdc, glyph, GGO_NATIVE, &gm, 0, NULL, &identity);
1415         else
1416             needed = GetGlyphOutlineA(hdc, glyph, GGO_NATIVE, &gm, 0, NULL, &identity);
1417
1418         if(needed == GDI_ERROR)
1419             goto error;
1420
1421         buf = HeapAlloc(GetProcessHeap(), 0, needed);
1422
1423         if(unicode)
1424             GetGlyphOutlineW(hdc, glyph, GGO_NATIVE, &gm, needed, buf, &identity);
1425         else
1426             GetGlyphOutlineA(hdc, glyph, GGO_NATIVE, &gm, needed, buf, &identity);
1427
1428         TRACE("glyph %d\n", glyph);
1429
1430         if(lpgmf)
1431         {
1432             lpgmf->gmfBlackBoxX = (float)gm.gmBlackBoxX / em_size;
1433             lpgmf->gmfBlackBoxY = (float)gm.gmBlackBoxY / em_size;
1434             lpgmf->gmfptGlyphOrigin.x = (float)gm.gmptGlyphOrigin.x / em_size;
1435             lpgmf->gmfptGlyphOrigin.y = (float)gm.gmptGlyphOrigin.y / em_size;
1436             lpgmf->gmfCellIncX = (float)gm.gmCellIncX / em_size;
1437             lpgmf->gmfCellIncY = (float)gm.gmCellIncY / em_size;
1438
1439             TRACE("%fx%f at %f,%f inc %f,%f\n", lpgmf->gmfBlackBoxX, lpgmf->gmfBlackBoxY,
1440                   lpgmf->gmfptGlyphOrigin.x, lpgmf->gmfptGlyphOrigin.y, lpgmf->gmfCellIncX, lpgmf->gmfCellIncY); 
1441             lpgmf++;
1442         }
1443
1444         funcs->gl.p_glNewList(listBase++, GL_COMPILE);
1445         funcs->gl.p_glFrontFace(GL_CCW);
1446         if(format == WGL_FONT_POLYGONS)
1447         {
1448             funcs->gl.p_glNormal3d(0.0, 0.0, 1.0);
1449             pgluTessNormal(tess, 0, 0, 1);
1450             pgluTessBeginPolygon(tess, NULL);
1451         }
1452
1453         while(!vertices)
1454         {
1455             if(vertex_total != -1)
1456                 vertices = HeapAlloc(GetProcessHeap(), 0, vertex_total * 3 * sizeof(GLdouble));
1457             vertex_total = 0;
1458
1459             pph = (TTPOLYGONHEADER*)buf;
1460             while((BYTE*)pph < buf + needed)
1461             {
1462                 GLdouble previous[3];
1463                 fixed_to_double(pph->pfxStart, em_size, previous);
1464
1465                 if(vertices)
1466                     TRACE("\tstart %d, %d\n", pph->pfxStart.x.value, pph->pfxStart.y.value);
1467
1468                 if(format == WGL_FONT_POLYGONS)
1469                     pgluTessBeginContour(tess);
1470                 else
1471                     funcs->gl.p_glBegin(GL_LINE_LOOP);
1472
1473                 if(vertices)
1474                 {
1475                     fixed_to_double(pph->pfxStart, em_size, vertices);
1476                     if(format == WGL_FONT_POLYGONS)
1477                         pgluTessVertex(tess, vertices, vertices);
1478                     else
1479                         funcs->gl.p_glVertex3d(vertices[0], vertices[1], vertices[2]);
1480                     vertices += 3;
1481                 }
1482                 vertex_total++;
1483
1484                 ppc = (TTPOLYCURVE*)((char*)pph + sizeof(*pph));
1485                 while((char*)ppc < (char*)pph + pph->cb)
1486                 {
1487                     int i, j;
1488                     int num;
1489
1490                     switch(ppc->wType) {
1491                     case TT_PRIM_LINE:
1492                         for(i = 0; i < ppc->cpfx; i++)
1493                         {
1494                             if(vertices)
1495                             {
1496                                 TRACE("\t\tline to %d, %d\n",
1497                                       ppc->apfx[i].x.value, ppc->apfx[i].y.value);
1498                                 fixed_to_double(ppc->apfx[i], em_size, vertices);
1499                                 if(format == WGL_FONT_POLYGONS)
1500                                     pgluTessVertex(tess, vertices, vertices);
1501                                 else
1502                                     funcs->gl.p_glVertex3d(vertices[0], vertices[1], vertices[2]);
1503                                 vertices += 3;
1504                             }
1505                             fixed_to_double(ppc->apfx[i], em_size, previous);
1506                             vertex_total++;
1507                         }
1508                         break;
1509
1510                     case TT_PRIM_QSPLINE:
1511                         for(i = 0; i < ppc->cpfx-1; i++)
1512                         {
1513                             bezier_vector curve[3];
1514                             bezier_vector *points;
1515                             GLdouble curve_vertex[3];
1516
1517                             if(vertices)
1518                                 TRACE("\t\tcurve  %d,%d %d,%d\n",
1519                                       ppc->apfx[i].x.value,     ppc->apfx[i].y.value,
1520                                       ppc->apfx[i + 1].x.value, ppc->apfx[i + 1].y.value);
1521
1522                             curve[0].x = previous[0];
1523                             curve[0].y = previous[1];
1524                             fixed_to_double(ppc->apfx[i], em_size, curve_vertex);
1525                             curve[1].x = curve_vertex[0];
1526                             curve[1].y = curve_vertex[1];
1527                             fixed_to_double(ppc->apfx[i + 1], em_size, curve_vertex);
1528                             curve[2].x = curve_vertex[0];
1529                             curve[2].y = curve_vertex[1];
1530                             if(i < ppc->cpfx-2)
1531                             {
1532                                 curve[2].x = (curve[1].x + curve[2].x)/2;
1533                                 curve[2].y = (curve[1].y + curve[2].y)/2;
1534                             }
1535                             num = bezier_approximate(curve, NULL, deviation);
1536                             points = HeapAlloc(GetProcessHeap(), 0, num*sizeof(bezier_vector));
1537                             num = bezier_approximate(curve, points, deviation);
1538                             vertex_total += num;
1539                             if(vertices)
1540                             {
1541                                 for(j=0; j<num; j++)
1542                                 {
1543                                     TRACE("\t\t\tvertex at %f,%f\n", points[j].x, points[j].y);
1544                                     vertices[0] = points[j].x;
1545                                     vertices[1] = points[j].y;
1546                                     vertices[2] = 0.0;
1547                                     if(format == WGL_FONT_POLYGONS)
1548                                         pgluTessVertex(tess, vertices, vertices);
1549                                     else
1550                                         funcs->gl.p_glVertex3d(vertices[0], vertices[1], vertices[2]);
1551                                     vertices += 3;
1552                                 }
1553                             }
1554                             HeapFree(GetProcessHeap(), 0, points);
1555                             previous[0] = curve[2].x;
1556                             previous[1] = curve[2].y;
1557                         }
1558                         break;
1559                     default:
1560                         ERR("\t\tcurve type = %d\n", ppc->wType);
1561                         if(format == WGL_FONT_POLYGONS)
1562                             pgluTessEndContour(tess);
1563                         else
1564                             funcs->gl.p_glEnd();
1565                         goto error_in_list;
1566                     }
1567
1568                     ppc = (TTPOLYCURVE*)((char*)ppc + sizeof(*ppc) +
1569                                          (ppc->cpfx - 1) * sizeof(POINTFX));
1570                 }
1571                 if(format == WGL_FONT_POLYGONS)
1572                     pgluTessEndContour(tess);
1573                 else
1574                     funcs->gl.p_glEnd();
1575                 pph = (TTPOLYGONHEADER*)((char*)pph + pph->cb);
1576             }
1577         }
1578
1579 error_in_list:
1580         if(format == WGL_FONT_POLYGONS)
1581             pgluTessEndPolygon(tess);
1582         funcs->gl.p_glTranslated((GLdouble)gm.gmCellIncX / em_size, (GLdouble)gm.gmCellIncY / em_size, 0.0);
1583         funcs->gl.p_glEndList();
1584         HeapFree(GetProcessHeap(), 0, buf);
1585         HeapFree(GetProcessHeap(), 0, vertices);
1586     }
1587
1588  error:
1589     DeleteObject(SelectObject(hdc, old_font));
1590     if(format == WGL_FONT_POLYGONS)
1591         pgluDeleteTess(tess);
1592     return TRUE;
1593
1594 }
1595
1596 /***********************************************************************
1597  *              wglUseFontOutlinesA (OPENGL32.@)
1598  */
1599 BOOL WINAPI wglUseFontOutlinesA(HDC hdc,
1600                                 DWORD first,
1601                                 DWORD count,
1602                                 DWORD listBase,
1603                                 FLOAT deviation,
1604                                 FLOAT extrusion,
1605                                 int format,
1606                                 LPGLYPHMETRICSFLOAT lpgmf)
1607 {
1608     return wglUseFontOutlines_common(hdc, first, count, listBase, deviation, extrusion, format, lpgmf, FALSE);
1609 }
1610
1611 /***********************************************************************
1612  *              wglUseFontOutlinesW (OPENGL32.@)
1613  */
1614 BOOL WINAPI wglUseFontOutlinesW(HDC hdc,
1615                                 DWORD first,
1616                                 DWORD count,
1617                                 DWORD listBase,
1618                                 FLOAT deviation,
1619                                 FLOAT extrusion,
1620                                 int format,
1621                                 LPGLYPHMETRICSFLOAT lpgmf)
1622 {
1623     return wglUseFontOutlines_common(hdc, first, count, listBase, deviation, extrusion, format, lpgmf, TRUE);
1624 }
1625
1626 /***********************************************************************
1627  *              glDebugEntry (OPENGL32.@)
1628  */
1629 GLint WINAPI glDebugEntry( GLint unknown1, GLint unknown2 )
1630 {
1631     return 0;
1632 }
1633
1634 /* build the extension string by filtering out the disabled extensions */
1635 static GLubyte *filter_extensions( const char *extensions )
1636 {
1637     static const char *disabled;
1638     char *p, *str;
1639     const char *end;
1640
1641     TRACE( "GL_EXTENSIONS:\n" );
1642
1643     if (!extensions) extensions = "";
1644
1645     if (!disabled)
1646     {
1647         HKEY hkey;
1648         DWORD size;
1649
1650         str = NULL;
1651         /* @@ Wine registry key: HKCU\Software\Wine\OpenGL */
1652         if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\OpenGL", &hkey ))
1653         {
1654             if (!RegQueryValueExA( hkey, "DisabledExtensions", 0, NULL, NULL, &size ))
1655             {
1656                 str = HeapAlloc( GetProcessHeap(), 0, size );
1657                 if (RegQueryValueExA( hkey, "DisabledExtensions", 0, NULL, (BYTE *)str, &size )) *str = 0;
1658             }
1659             RegCloseKey( hkey );
1660         }
1661         if (str)
1662         {
1663             if (InterlockedCompareExchangePointer( (void **)&disabled, str, NULL ))
1664                 HeapFree( GetProcessHeap(), 0, str );
1665         }
1666         else disabled = "";
1667     }
1668
1669     if (!disabled[0]) return NULL;
1670     if ((str = HeapAlloc( GetProcessHeap(), 0, strlen(extensions) + 2 )))
1671     {
1672         p = str;
1673         for (;;)
1674         {
1675             while (*extensions == ' ') extensions++;
1676             if (!*extensions) break;
1677             if (!(end = strchr( extensions, ' ' ))) end = extensions + strlen( extensions );
1678             memcpy( p, extensions, end - extensions );
1679             p[end - extensions] = 0;
1680             if (!has_extension( disabled, p ))
1681             {
1682                 TRACE("++ %s\n", p );
1683                 p += end - extensions;
1684                 *p++ = ' ';
1685             }
1686             else TRACE("-- %s (disabled by config)\n", p );
1687             extensions = end;
1688         }
1689         *p = 0;
1690     }
1691     return (GLubyte *)str;
1692 }
1693
1694 /***********************************************************************
1695  *              glGetString (OPENGL32.@)
1696  */
1697 const GLubyte * WINAPI glGetString( GLenum name )
1698 {
1699     const struct opengl_funcs *funcs = NtCurrentTeb()->glTable;
1700     const GLubyte *ret = funcs->gl.p_glGetString( name );
1701
1702     if (name == GL_EXTENSIONS && ret)
1703     {
1704         struct wgl_handle *ptr = get_current_context_ptr();
1705         if (ptr->u.context->extensions ||
1706             ((ptr->u.context->extensions = filter_extensions( (const char *)ret ))))
1707             ret = ptr->u.context->extensions;
1708     }
1709     return ret;
1710 }
1711
1712 /***********************************************************************
1713  *           OpenGL initialisation routine
1714  */
1715 BOOL WINAPI DllMain( HINSTANCE hinst, DWORD reason, LPVOID reserved )
1716 {
1717     switch(reason)
1718     {
1719     case DLL_PROCESS_ATTACH:
1720         DisableThreadLibraryCalls(hinst);
1721         NtCurrentTeb()->glTable = &null_opengl_funcs;
1722         break;
1723     case DLL_THREAD_ATTACH:
1724         NtCurrentTeb()->glTable = &null_opengl_funcs;
1725         break;
1726     }
1727     return TRUE;
1728 }