wined3d: Get rid of the WineD3D_PixelFormat typedef.
[wine] / dlls / wined3d / directx.c
1 /*
2  * IWineD3D implementation
3  *
4  * Copyright 2002-2004 Jason Edmeades
5  * Copyright 2003-2004 Raphael Junqueira
6  * Copyright 2004 Christian Costa
7  * Copyright 2005 Oliver Stieber
8  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
9  * Copyright 2009-2010 Henri Verbeet for CodeWeavers
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include <stdio.h>
28 #include "wined3d_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
31 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
32
33 #define WINE_DEFAULT_VIDMEM (64 * 1024 * 1024)
34
35 /* The d3d device ID */
36 static const GUID IID_D3DDEVICE_D3DUID = { 0xaeb2cdd4, 0x6e41, 0x43ea, { 0x94,0x1c,0x83,0x61,0xcc,0x76,0x07,0x81 } };
37
38 /* Extension detection */
39 static const struct {
40     const char *extension_string;
41     GL_SupportedExt extension;
42     DWORD version;
43 } EXTENSION_MAP[] = {
44     /* APPLE */
45     {"GL_APPLE_client_storage",             APPLE_CLIENT_STORAGE,           0                           },
46     {"GL_APPLE_fence",                      APPLE_FENCE,                    0                           },
47     {"GL_APPLE_float_pixels",               APPLE_FLOAT_PIXELS,             0                           },
48     {"GL_APPLE_flush_buffer_range",         APPLE_FLUSH_BUFFER_RANGE,       0                           },
49     {"GL_APPLE_flush_render",               APPLE_FLUSH_RENDER,             0                           },
50     {"GL_APPLE_ycbcr_422",                  APPLE_YCBCR_422,                0                           },
51
52     /* ARB */
53     {"GL_ARB_color_buffer_float",           ARB_COLOR_BUFFER_FLOAT,         0                           },
54     {"GL_ARB_depth_buffer_float",           ARB_DEPTH_BUFFER_FLOAT,         0                           },
55     {"GL_ARB_depth_clamp",                  ARB_DEPTH_CLAMP,                0                           },
56     {"GL_ARB_depth_texture",                ARB_DEPTH_TEXTURE,              0                           },
57     {"GL_ARB_draw_buffers",                 ARB_DRAW_BUFFERS,               0                           },
58     {"GL_ARB_fragment_program",             ARB_FRAGMENT_PROGRAM,           0                           },
59     {"GL_ARB_fragment_shader",              ARB_FRAGMENT_SHADER,            0                           },
60     {"GL_ARB_framebuffer_object",           ARB_FRAMEBUFFER_OBJECT,         0                           },
61     {"GL_ARB_geometry_shader4",             ARB_GEOMETRY_SHADER4,           0                           },
62     {"GL_ARB_half_float_pixel",             ARB_HALF_FLOAT_PIXEL,           0                           },
63     {"GL_ARB_half_float_vertex",            ARB_HALF_FLOAT_VERTEX,          0                           },
64     {"GL_ARB_map_buffer_range",             ARB_MAP_BUFFER_RANGE,           0                           },
65     {"GL_ARB_multisample",                  ARB_MULTISAMPLE,                0                           }, /* needs GLX_ARB_MULTISAMPLE as well */
66     {"GL_ARB_multitexture",                 ARB_MULTITEXTURE,               0                           },
67     {"GL_ARB_occlusion_query",              ARB_OCCLUSION_QUERY,            0                           },
68     {"GL_ARB_pixel_buffer_object",          ARB_PIXEL_BUFFER_OBJECT,        0                           },
69     {"GL_ARB_point_parameters",             ARB_POINT_PARAMETERS,           0                           },
70     {"GL_ARB_point_sprite",                 ARB_POINT_SPRITE,               0                           },
71     {"GL_ARB_provoking_vertex",             ARB_PROVOKING_VERTEX,           0                           },
72     {"GL_ARB_shader_objects",               ARB_SHADER_OBJECTS,             0                           },
73     {"GL_ARB_shader_texture_lod",           ARB_SHADER_TEXTURE_LOD,         0                           },
74     {"GL_ARB_shading_language_100",         ARB_SHADING_LANGUAGE_100,       0                           },
75     {"GL_ARB_shadow",                       ARB_SHADOW,                     0                           },
76     {"GL_ARB_sync",                         ARB_SYNC,                       0                           },
77     {"GL_ARB_texture_border_clamp",         ARB_TEXTURE_BORDER_CLAMP,       0                           },
78     {"GL_ARB_texture_compression",          ARB_TEXTURE_COMPRESSION,        0                           },
79     {"GL_ARB_texture_compression_rgtc",     ARB_TEXTURE_COMPRESSION_RGTC,   0                           },
80     {"GL_ARB_texture_cube_map",             ARB_TEXTURE_CUBE_MAP,           0                           },
81     {"GL_ARB_texture_env_add",              ARB_TEXTURE_ENV_ADD,            0                           },
82     {"GL_ARB_texture_env_combine",          ARB_TEXTURE_ENV_COMBINE,        0                           },
83     {"GL_ARB_texture_env_dot3",             ARB_TEXTURE_ENV_DOT3,           0                           },
84     {"GL_ARB_texture_float",                ARB_TEXTURE_FLOAT,              0                           },
85     {"GL_ARB_texture_mirrored_repeat",      ARB_TEXTURE_MIRRORED_REPEAT,    0                           },
86     {"GL_ARB_texture_non_power_of_two",     ARB_TEXTURE_NON_POWER_OF_TWO,   MAKEDWORD_VERSION(2, 0)     },
87     {"GL_ARB_texture_rectangle",            ARB_TEXTURE_RECTANGLE,          0                           },
88     {"GL_ARB_texture_rg",                   ARB_TEXTURE_RG,                 0                           },
89     {"GL_ARB_vertex_array_bgra",            ARB_VERTEX_ARRAY_BGRA,          0                           },
90     {"GL_ARB_vertex_blend",                 ARB_VERTEX_BLEND,               0                           },
91     {"GL_ARB_vertex_buffer_object",         ARB_VERTEX_BUFFER_OBJECT,       0                           },
92     {"GL_ARB_vertex_program",               ARB_VERTEX_PROGRAM,             0                           },
93     {"GL_ARB_vertex_shader",                ARB_VERTEX_SHADER,              0                           },
94
95     /* ATI */
96     {"GL_ATI_fragment_shader",              ATI_FRAGMENT_SHADER,            0                           },
97     {"GL_ATI_separate_stencil",             ATI_SEPARATE_STENCIL,           0                           },
98     {"GL_ATI_texture_compression_3dc",      ATI_TEXTURE_COMPRESSION_3DC,    0                           },
99     {"GL_ATI_texture_env_combine3",         ATI_TEXTURE_ENV_COMBINE3,       0                           },
100     {"GL_ATI_texture_mirror_once",          ATI_TEXTURE_MIRROR_ONCE,        0                           },
101
102     /* EXT */
103     {"GL_EXT_blend_color",                  EXT_BLEND_COLOR,                0                           },
104     {"GL_EXT_blend_equation_separate",      EXT_BLEND_EQUATION_SEPARATE,    0                           },
105     {"GL_EXT_blend_func_separate",          EXT_BLEND_FUNC_SEPARATE,        0                           },
106     {"GL_EXT_blend_minmax",                 EXT_BLEND_MINMAX,               0                           },
107     {"GL_EXT_blend_subtract",               EXT_BLEND_SUBTRACT,             0                           },
108     {"GL_EXT_depth_bounds_test",            EXT_DEPTH_BOUNDS_TEST,          0                           },
109     {"GL_EXT_draw_buffers2",                EXT_DRAW_BUFFERS2,              0                           },
110     {"GL_EXT_fog_coord",                    EXT_FOG_COORD,                  0                           },
111     {"GL_EXT_framebuffer_blit",             EXT_FRAMEBUFFER_BLIT,           0                           },
112     {"GL_EXT_framebuffer_multisample",      EXT_FRAMEBUFFER_MULTISAMPLE,    0                           },
113     {"GL_EXT_framebuffer_object",           EXT_FRAMEBUFFER_OBJECT,         0                           },
114     {"GL_EXT_gpu_program_parameters",       EXT_GPU_PROGRAM_PARAMETERS,     0                           },
115     {"GL_EXT_gpu_shader4",                  EXT_GPU_SHADER4,                0                           },
116     {"GL_EXT_packed_depth_stencil",         EXT_PACKED_DEPTH_STENCIL,       0                           },
117     {"GL_EXT_paletted_texture",             EXT_PALETTED_TEXTURE,           0                           },
118     {"GL_EXT_point_parameters",             EXT_POINT_PARAMETERS,           0                           },
119     {"GL_EXT_provoking_vertex",             EXT_PROVOKING_VERTEX,           0                           },
120     {"GL_EXT_secondary_color",              EXT_SECONDARY_COLOR,            0                           },
121     {"GL_EXT_stencil_two_side",             EXT_STENCIL_TWO_SIDE,           0                           },
122     {"GL_EXT_stencil_wrap",                 EXT_STENCIL_WRAP,               0                           },
123     {"GL_EXT_texture3D",                    EXT_TEXTURE3D,                  MAKEDWORD_VERSION(1, 2)     },
124     {"GL_EXT_texture_compression_rgtc",     EXT_TEXTURE_COMPRESSION_RGTC,   0                           },
125     {"GL_EXT_texture_compression_s3tc",     EXT_TEXTURE_COMPRESSION_S3TC,   0                           },
126     {"GL_EXT_texture_env_add",              EXT_TEXTURE_ENV_ADD,            0                           },
127     {"GL_EXT_texture_env_combine",          EXT_TEXTURE_ENV_COMBINE,        0                           },
128     {"GL_EXT_texture_env_dot3",             EXT_TEXTURE_ENV_DOT3,           0                           },
129     {"GL_EXT_texture_filter_anisotropic",   EXT_TEXTURE_FILTER_ANISOTROPIC, 0                           },
130     {"GL_EXT_texture_lod_bias",             EXT_TEXTURE_LOD_BIAS,           0                           },
131     {"GL_EXT_texture_sRGB",                 EXT_TEXTURE_SRGB,               0                           },
132     {"GL_EXT_texture_sRGB_decode",          EXT_TEXTURE_SRGB_DECODE,        0                           },
133     {"GL_EXT_vertex_array_bgra",            EXT_VERTEX_ARRAY_BGRA,          0                           },
134
135     /* NV */
136     {"GL_NV_depth_clamp",                   NV_DEPTH_CLAMP,                 0                           },
137     {"GL_NV_fence",                         NV_FENCE,                       0                           },
138     {"GL_NV_fog_distance",                  NV_FOG_DISTANCE,                0                           },
139     {"GL_NV_fragment_program",              NV_FRAGMENT_PROGRAM,            0                           },
140     {"GL_NV_fragment_program2",             NV_FRAGMENT_PROGRAM2,           0                           },
141     {"GL_NV_fragment_program_option",       NV_FRAGMENT_PROGRAM_OPTION,     0                           },
142     {"GL_NV_half_float",                    NV_HALF_FLOAT,                  0                           },
143     {"GL_NV_light_max_exponent",            NV_LIGHT_MAX_EXPONENT,          0                           },
144     {"GL_NV_point_sprite",                  NV_POINT_SPRITE,                0                           },
145     {"GL_NV_register_combiners",            NV_REGISTER_COMBINERS,          0                           },
146     {"GL_NV_register_combiners2",           NV_REGISTER_COMBINERS2,         0                           },
147     {"GL_NV_texgen_reflection",             NV_TEXGEN_REFLECTION,           0                           },
148     {"GL_NV_texture_env_combine4",          NV_TEXTURE_ENV_COMBINE4,        0                           },
149     {"GL_NV_texture_shader",                NV_TEXTURE_SHADER,              0                           },
150     {"GL_NV_texture_shader2",               NV_TEXTURE_SHADER2,             0                           },
151     {"GL_NV_vertex_program",                NV_VERTEX_PROGRAM,              0                           },
152     {"GL_NV_vertex_program1_1",             NV_VERTEX_PROGRAM1_1,           0                           },
153     {"GL_NV_vertex_program2",               NV_VERTEX_PROGRAM2,             0                           },
154     {"GL_NV_vertex_program2_option",        NV_VERTEX_PROGRAM2_OPTION,      0                           },
155     {"GL_NV_vertex_program3",               NV_VERTEX_PROGRAM3,             0                           },
156
157     /* SGI */
158     {"GL_SGIS_generate_mipmap",             SGIS_GENERATE_MIPMAP,           0                           },
159 };
160
161 /**********************************************************
162  * Utility functions follow
163  **********************************************************/
164
165 const struct min_lookup minMipLookup[] =
166 {
167     /* NONE         POINT                       LINEAR */
168     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
169     {{GL_NEAREST,   GL_NEAREST_MIPMAP_NEAREST,  GL_NEAREST_MIPMAP_LINEAR}}, /* POINT*/
170     {{GL_LINEAR,    GL_LINEAR_MIPMAP_NEAREST,   GL_LINEAR_MIPMAP_LINEAR}},  /* LINEAR */
171 };
172
173 const struct min_lookup minMipLookup_noFilter[] =
174 {
175     /* NONE         POINT                       LINEAR */
176     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
177     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* POINT */
178     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* LINEAR */
179 };
180
181 const struct min_lookup minMipLookup_noMip[] =
182 {
183     /* NONE         POINT                       LINEAR */
184     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
185     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* POINT */
186     {{GL_LINEAR,    GL_LINEAR,                  GL_LINEAR }},               /* LINEAR */
187 };
188
189 const GLenum magLookup[] =
190 {
191     /* NONE     POINT       LINEAR */
192     GL_NEAREST, GL_NEAREST, GL_LINEAR,
193 };
194
195 const GLenum magLookup_noFilter[] =
196 {
197     /* NONE     POINT       LINEAR */
198     GL_NEAREST, GL_NEAREST, GL_NEAREST,
199 };
200
201 /* drawStridedSlow attributes */
202 glAttribFunc position_funcs[WINED3D_FFP_EMIT_COUNT];
203 glAttribFunc diffuse_funcs[WINED3D_FFP_EMIT_COUNT];
204 glAttribFunc specular_func_3ubv;
205 glAttribFunc specular_funcs[WINED3D_FFP_EMIT_COUNT];
206 glAttribFunc normal_funcs[WINED3D_FFP_EMIT_COUNT];
207 glMultiTexCoordFunc multi_texcoord_funcs[WINED3D_FFP_EMIT_COUNT];
208
209 /**
210  * Note: GL seems to trap if GetDeviceCaps is called before any HWND's created,
211  * i.e., there is no GL Context - Get a default rendering context to enable the
212  * function query some info from GL.
213  */
214
215 struct wined3d_fake_gl_ctx
216 {
217     HDC dc;
218     HWND wnd;
219     HGLRC gl_ctx;
220     HDC restore_dc;
221     HGLRC restore_gl_ctx;
222 };
223
224 static void WineD3D_ReleaseFakeGLContext(struct wined3d_fake_gl_ctx *ctx)
225 {
226     TRACE_(d3d_caps)("Destroying fake GL context.\n");
227
228     if (!pwglMakeCurrent(NULL, NULL))
229     {
230         ERR_(d3d_caps)("Failed to disable fake GL context.\n");
231     }
232
233     if (!pwglDeleteContext(ctx->gl_ctx))
234     {
235         DWORD err = GetLastError();
236         ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx->gl_ctx, err);
237     }
238
239     ReleaseDC(ctx->wnd, ctx->dc);
240     DestroyWindow(ctx->wnd);
241
242     if (ctx->restore_gl_ctx && !pwglMakeCurrent(ctx->restore_dc, ctx->restore_gl_ctx))
243     {
244         ERR_(d3d_caps)("Failed to restore previous GL context.\n");
245     }
246 }
247
248 /* Do not call while under the GL lock. */
249 static BOOL WineD3D_CreateFakeGLContext(struct wined3d_fake_gl_ctx *ctx)
250 {
251     PIXELFORMATDESCRIPTOR pfd;
252     int iPixelFormat;
253
254     TRACE("getting context...\n");
255
256     ctx->restore_dc = pwglGetCurrentDC();
257     ctx->restore_gl_ctx = pwglGetCurrentContext();
258
259     /* We need a fake window as a hdc retrieved using GetDC(0) can't be used for much GL purposes. */
260     ctx->wnd = CreateWindowA(WINED3D_OPENGL_WINDOW_CLASS_NAME, "WineD3D fake window",
261             WS_OVERLAPPEDWINDOW, 10, 10, 10, 10, NULL, NULL, NULL, NULL);
262     if (!ctx->wnd)
263     {
264         ERR_(d3d_caps)("Failed to create a window.\n");
265         goto fail;
266     }
267
268     ctx->dc = GetDC(ctx->wnd);
269     if (!ctx->dc)
270     {
271         ERR_(d3d_caps)("Failed to get a DC.\n");
272         goto fail;
273     }
274
275     /* PixelFormat selection */
276     ZeroMemory(&pfd, sizeof(pfd));
277     pfd.nSize = sizeof(pfd);
278     pfd.nVersion = 1;
279     pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW; /* PFD_GENERIC_ACCELERATED */
280     pfd.iPixelType = PFD_TYPE_RGBA;
281     pfd.cColorBits = 32;
282     pfd.iLayerType = PFD_MAIN_PLANE;
283
284     iPixelFormat = ChoosePixelFormat(ctx->dc, &pfd);
285     if (!iPixelFormat)
286     {
287         /* If this happens something is very wrong as ChoosePixelFormat barely fails. */
288         ERR_(d3d_caps)("Can't find a suitable iPixelFormat.\n");
289         goto fail;
290     }
291     DescribePixelFormat(ctx->dc, iPixelFormat, sizeof(pfd), &pfd);
292     SetPixelFormat(ctx->dc, iPixelFormat, &pfd);
293
294     /* Create a GL context. */
295     ctx->gl_ctx = pwglCreateContext(ctx->dc);
296     if (!ctx->gl_ctx)
297     {
298         WARN_(d3d_caps)("Error creating default context for capabilities initialization.\n");
299         goto fail;
300     }
301
302     /* Make it the current GL context. */
303     if (!context_set_current(NULL))
304     {
305         ERR_(d3d_caps)("Failed to clear current D3D context.\n");
306     }
307
308     if (!pwglMakeCurrent(ctx->dc, ctx->gl_ctx))
309     {
310         ERR_(d3d_caps)("Failed to make fake GL context current.\n");
311         goto fail;
312     }
313
314     return TRUE;
315
316 fail:
317     if (ctx->gl_ctx) pwglDeleteContext(ctx->gl_ctx);
318     ctx->gl_ctx = NULL;
319     if (ctx->dc) ReleaseDC(ctx->wnd, ctx->dc);
320     ctx->dc = NULL;
321     if (ctx->wnd) DestroyWindow(ctx->wnd);
322     ctx->wnd = NULL;
323     if (ctx->restore_gl_ctx && !pwglMakeCurrent(ctx->restore_dc, ctx->restore_gl_ctx))
324     {
325         ERR_(d3d_caps)("Failed to restore previous GL context.\n");
326     }
327
328     return FALSE;
329 }
330
331 /* Adjust the amount of used texture memory */
332 unsigned int WineD3DAdapterChangeGLRam(IWineD3DDeviceImpl *device, unsigned int glram)
333 {
334     struct wined3d_adapter *adapter = device->adapter;
335
336     adapter->UsedTextureRam += glram;
337     TRACE("Adjusted gl ram by %d to %d\n", glram, adapter->UsedTextureRam);
338     return adapter->UsedTextureRam;
339 }
340
341 static void wined3d_adapter_cleanup(struct wined3d_adapter *adapter)
342 {
343     HeapFree(GetProcessHeap(), 0, adapter->gl_info.formats);
344     HeapFree(GetProcessHeap(), 0, adapter->cfgs);
345 }
346
347 ULONG CDECL wined3d_incref(struct wined3d *wined3d)
348 {
349     ULONG refcount = InterlockedIncrement(&wined3d->ref);
350
351     TRACE("%p increasing refcount to %u.\n", wined3d, refcount);
352
353     return refcount;
354 }
355
356 ULONG CDECL wined3d_decref(struct wined3d *wined3d)
357 {
358     ULONG refcount = InterlockedDecrement(&wined3d->ref);
359
360     TRACE("%p decreasing refcount to %u.\n", wined3d, refcount);
361
362     if (!refcount)
363     {
364         unsigned int i;
365
366         for (i = 0; i < wined3d->adapter_count; ++i)
367         {
368             wined3d_adapter_cleanup(&wined3d->adapters[i]);
369         }
370         HeapFree(GetProcessHeap(), 0, wined3d);
371     }
372
373     return refcount;
374 }
375
376 /**********************************************************
377  * IWineD3D parts follows
378  **********************************************************/
379
380 /* GL locking is done by the caller */
381 static inline BOOL test_arb_vs_offset_limit(const struct wined3d_gl_info *gl_info)
382 {
383     GLuint prog;
384     BOOL ret = FALSE;
385     const char *testcode =
386         "!!ARBvp1.0\n"
387         "PARAM C[66] = { program.env[0..65] };\n"
388         "ADDRESS A0;"
389         "PARAM zero = {0.0, 0.0, 0.0, 0.0};\n"
390         "ARL A0.x, zero.x;\n"
391         "MOV result.position, C[A0.x + 65];\n"
392         "END\n";
393
394     while(glGetError());
395     GL_EXTCALL(glGenProgramsARB(1, &prog));
396     if(!prog) {
397         ERR("Failed to create an ARB offset limit test program\n");
398     }
399     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, prog));
400     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
401                                   strlen(testcode), testcode));
402     if (glGetError())
403     {
404         TRACE("OpenGL implementation does not allow indirect addressing offsets > 63\n");
405         TRACE("error: %s\n", debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
406         ret = TRUE;
407     } else TRACE("OpenGL implementation allows offsets > 63\n");
408
409     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, 0));
410     GL_EXTCALL(glDeleteProgramsARB(1, &prog));
411     checkGLcall("ARB vp offset limit test cleanup");
412
413     return ret;
414 }
415
416 static DWORD ver_for_ext(GL_SupportedExt ext)
417 {
418     unsigned int i;
419     for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i) {
420         if(EXTENSION_MAP[i].extension == ext) {
421             return EXTENSION_MAP[i].version;
422         }
423     }
424     return 0;
425 }
426
427 static BOOL match_amd_r300_to_500(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
428         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
429 {
430     if (card_vendor != HW_VENDOR_AMD) return FALSE;
431     if (device == CARD_AMD_RADEON_9500) return TRUE;
432     if (device == CARD_AMD_RADEON_X700) return TRUE;
433     if (device == CARD_AMD_RADEON_X1600) return TRUE;
434     return FALSE;
435 }
436
437 static BOOL match_geforce5(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
438         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
439 {
440     if (card_vendor == HW_VENDOR_NVIDIA)
441     {
442         if (device == CARD_NVIDIA_GEFORCEFX_5200 ||
443             device == CARD_NVIDIA_GEFORCEFX_5600 ||
444             device == CARD_NVIDIA_GEFORCEFX_5800)
445         {
446             return TRUE;
447         }
448     }
449     return FALSE;
450 }
451
452 static BOOL match_apple(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
453         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
454 {
455     /* MacOS has various specialities in the extensions it advertises. Some have to be loaded from
456      * the opengl 1.2+ core, while other extensions are advertised, but software emulated. So try to
457      * detect the Apple OpenGL implementation to apply some extension fixups afterwards.
458      *
459      * Detecting this isn't really easy. The vendor string doesn't mention Apple. Compile-time checks
460      * aren't sufficient either because a Linux binary may display on a macos X server via remote X11.
461      * So try to detect the GL implementation by looking at certain Apple extensions. Some extensions
462      * like client storage might be supported on other implementations too, but GL_APPLE_flush_render
463      * is specific to the Mac OS X window management, and GL_APPLE_ycbcr_422 is QuickTime specific. So
464      * the chance that other implementations support them is rather small since Win32 QuickTime uses
465      * DirectDraw, not OpenGL.
466      *
467      * This test has been moved into wined3d_guess_gl_vendor()
468      */
469     if (gl_vendor == GL_VENDOR_APPLE)
470     {
471         return TRUE;
472     }
473     return FALSE;
474 }
475
476 /* Context activation is done by the caller. */
477 static void test_pbo_functionality(struct wined3d_gl_info *gl_info)
478 {
479     /* Some OpenGL implementations, namely Apple's Geforce 8 driver, advertises PBOs,
480      * but glTexSubImage from a PBO fails miserably, with the first line repeated over
481      * all the texture. This function detects this bug by its symptom and disables PBOs
482      * if the test fails.
483      *
484      * The test uploads a 4x4 texture via the PBO in the "native" format GL_BGRA,
485      * GL_UNSIGNED_INT_8_8_8_8_REV. This format triggers the bug, and it is what we use
486      * for D3DFMT_A8R8G8B8. Then the texture is read back without any PBO and the data
487      * read back is compared to the original. If they are equal PBOs are assumed to work,
488      * otherwise the PBO extension is disabled. */
489     GLuint texture, pbo;
490     static const unsigned int pattern[] =
491     {
492         0x00000000, 0x000000ff, 0x0000ff00, 0x40ff0000,
493         0x80ffffff, 0x40ffff00, 0x00ff00ff, 0x0000ffff,
494         0x00ffff00, 0x00ff00ff, 0x0000ffff, 0x000000ff,
495         0x80ff00ff, 0x0000ffff, 0x00ff00ff, 0x40ff00ff
496     };
497     unsigned int check[sizeof(pattern) / sizeof(pattern[0])];
498
499     /* No PBO -> No point in testing them. */
500     if (!gl_info->supported[ARB_PIXEL_BUFFER_OBJECT]) return;
501
502     ENTER_GL();
503
504     while (glGetError());
505     glGenTextures(1, &texture);
506     glBindTexture(GL_TEXTURE_2D, texture);
507
508     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
509     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 4, 4, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 0);
510     checkGLcall("Specifying the PBO test texture");
511
512     GL_EXTCALL(glGenBuffersARB(1, &pbo));
513     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo));
514     GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, sizeof(pattern), pattern, GL_STREAM_DRAW_ARB));
515     checkGLcall("Specifying the PBO test pbo");
516
517     glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 4, 4, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
518     checkGLcall("Loading the PBO test texture");
519
520     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
521     LEAVE_GL();
522
523     wglFinish(); /* just to be sure */
524
525     memset(check, 0, sizeof(check));
526     ENTER_GL();
527     glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, check);
528     checkGLcall("Reading back the PBO test texture");
529
530     glDeleteTextures(1, &texture);
531     GL_EXTCALL(glDeleteBuffersARB(1, &pbo));
532     checkGLcall("PBO test cleanup");
533
534     LEAVE_GL();
535
536     if (memcmp(check, pattern, sizeof(check)))
537     {
538         WARN_(d3d_caps)("PBO test failed, read back data doesn't match original.\n");
539         WARN_(d3d_caps)("Disabling PBOs. This may result in slower performance.\n");
540         gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] = FALSE;
541     }
542     else
543     {
544         TRACE_(d3d_caps)("PBO test successful.\n");
545     }
546 }
547
548 static BOOL match_apple_intel(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
549         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
550 {
551     return (card_vendor == HW_VENDOR_INTEL) && (gl_vendor == GL_VENDOR_APPLE);
552 }
553
554 static BOOL match_apple_nonr500ati(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
555         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
556 {
557     if (gl_vendor != GL_VENDOR_APPLE) return FALSE;
558     if (card_vendor != HW_VENDOR_AMD) return FALSE;
559     if (device == CARD_AMD_RADEON_X1600) return FALSE;
560     return TRUE;
561 }
562
563 static BOOL match_fglrx(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
564         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
565 {
566     return gl_vendor == GL_VENDOR_FGLRX;
567
568 }
569
570 static BOOL match_dx10_capable(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
571         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
572 {
573     /* DX9 cards support 40 single float varyings in hardware, most drivers report 32. ATI misreports
574      * 44 varyings. So assume that if we have more than 44 varyings we have a dx10 card.
575      * This detection is for the gl_ClipPos varying quirk. If a d3d9 card really supports more than 44
576      * varyings and we subtract one in dx9 shaders its not going to hurt us because the dx9 limit is
577      * hardcoded
578      *
579      * dx10 cards usually have 64 varyings */
580     return gl_info->limits.glsl_varyings > 44;
581 }
582
583 /* A GL context is provided by the caller */
584 static BOOL match_allows_spec_alpha(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
585         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
586 {
587     GLenum error;
588     DWORD data[16];
589
590     if (!gl_info->supported[EXT_SECONDARY_COLOR]) return FALSE;
591
592     ENTER_GL();
593     while(glGetError());
594     GL_EXTCALL(glSecondaryColorPointerEXT)(4, GL_UNSIGNED_BYTE, 4, data);
595     error = glGetError();
596     LEAVE_GL();
597
598     if(error == GL_NO_ERROR)
599     {
600         TRACE("GL Implementation accepts 4 component specular color pointers\n");
601         return TRUE;
602     }
603     else
604     {
605         TRACE("GL implementation does not accept 4 component specular colors, error %s\n",
606               debug_glerror(error));
607         return FALSE;
608     }
609 }
610
611 static BOOL match_apple_nvts(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
612         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
613 {
614     if (!match_apple(gl_info, gl_renderer, gl_vendor, card_vendor, device)) return FALSE;
615     return gl_info->supported[NV_TEXTURE_SHADER];
616 }
617
618 /* A GL context is provided by the caller */
619 static BOOL match_broken_nv_clip(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
620         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
621 {
622     GLuint prog;
623     BOOL ret = FALSE;
624     GLint pos;
625     const char *testcode =
626         "!!ARBvp1.0\n"
627         "OPTION NV_vertex_program2;\n"
628         "MOV result.clip[0], 0.0;\n"
629         "MOV result.position, 0.0;\n"
630         "END\n";
631
632     if (!gl_info->supported[NV_VERTEX_PROGRAM2_OPTION]) return FALSE;
633
634     ENTER_GL();
635     while(glGetError());
636
637     GL_EXTCALL(glGenProgramsARB(1, &prog));
638     if(!prog)
639     {
640         ERR("Failed to create the NVvp clip test program\n");
641         LEAVE_GL();
642         return FALSE;
643     }
644     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, prog));
645     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
646                                   strlen(testcode), testcode));
647     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
648     if(pos != -1)
649     {
650         WARN("GL_NV_vertex_program2_option result.clip[] test failed\n");
651         TRACE("error: %s\n", debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
652         ret = TRUE;
653         while(glGetError());
654     }
655     else TRACE("GL_NV_vertex_program2_option result.clip[] test passed\n");
656
657     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, 0));
658     GL_EXTCALL(glDeleteProgramsARB(1, &prog));
659     checkGLcall("GL_NV_vertex_program2_option result.clip[] test cleanup");
660
661     LEAVE_GL();
662     return ret;
663 }
664
665 /* Context activation is done by the caller. */
666 static BOOL match_fbo_tex_update(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
667         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
668 {
669     char data[4 * 4 * 4];
670     GLuint tex, fbo;
671     GLenum status;
672
673     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return FALSE;
674
675     memset(data, 0xcc, sizeof(data));
676
677     ENTER_GL();
678
679     glGenTextures(1, &tex);
680     glBindTexture(GL_TEXTURE_2D, tex);
681     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
682     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
683     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 4, 4, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
684     checkGLcall("glTexImage2D");
685
686     gl_info->fbo_ops.glGenFramebuffers(1, &fbo);
687     gl_info->fbo_ops.glBindFramebuffer(GL_FRAMEBUFFER, fbo);
688     gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
689     checkGLcall("glFramebufferTexture2D");
690
691     status = gl_info->fbo_ops.glCheckFramebufferStatus(GL_FRAMEBUFFER);
692     if (status != GL_FRAMEBUFFER_COMPLETE) ERR("FBO status %#x\n", status);
693     checkGLcall("glCheckFramebufferStatus");
694
695     memset(data, 0x11, sizeof(data));
696     glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 4, 4, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, data);
697     checkGLcall("glTexSubImage2D");
698
699     glClearColor(0.996f, 0.729f, 0.745f, 0.792f);
700     glClear(GL_COLOR_BUFFER_BIT);
701     checkGLcall("glClear");
702
703     glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, data);
704     checkGLcall("glGetTexImage");
705
706     gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
707     gl_info->fbo_ops.glBindFramebuffer(GL_FRAMEBUFFER, 0);
708     glBindTexture(GL_TEXTURE_2D, 0);
709     checkGLcall("glBindTexture");
710
711     gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
712     glDeleteTextures(1, &tex);
713     checkGLcall("glDeleteTextures");
714
715     LEAVE_GL();
716
717     return *(DWORD *)data == 0x11111111;
718 }
719
720 static void quirk_arb_constants(struct wined3d_gl_info *gl_info)
721 {
722     TRACE_(d3d_caps)("Using ARB vs constant limit(=%u) for GLSL.\n", gl_info->limits.arb_vs_native_constants);
723     gl_info->limits.glsl_vs_float_constants = gl_info->limits.arb_vs_native_constants;
724     TRACE_(d3d_caps)("Using ARB ps constant limit(=%u) for GLSL.\n", gl_info->limits.arb_ps_native_constants);
725     gl_info->limits.glsl_ps_float_constants = gl_info->limits.arb_ps_native_constants;
726 }
727
728 static void quirk_apple_glsl_constants(struct wined3d_gl_info *gl_info)
729 {
730     quirk_arb_constants(gl_info);
731     /* MacOS needs uniforms for relative addressing offsets. This can accumulate to quite a few uniforms.
732      * Beyond that the general uniform isn't optimal, so reserve a number of uniforms. 12 vec4's should
733      * allow 48 different offsets or other helper immediate values. */
734     TRACE_(d3d_caps)("Reserving 12 GLSL constants for compiler private use.\n");
735     gl_info->reserved_glsl_constants = max(gl_info->reserved_glsl_constants, 12);
736 }
737
738 /* fglrx crashes with a very bad kernel panic if GL_POINT_SPRITE_ARB is set to GL_COORD_REPLACE_ARB
739  * on more than one texture unit. This means that the d3d9 visual point size test will cause a
740  * kernel panic on any machine running fglrx 9.3(latest that supports r300 to r500 cards). This
741  * quirk only enables point sprites on the first texture unit. This keeps point sprites working in
742  * most games, but avoids the crash
743  *
744  * A more sophisticated way would be to find all units that need texture coordinates and enable
745  * point sprites for one if only one is found, and software emulate point sprites in drawStridedSlow
746  * if more than one unit needs texture coordinates(This requires software ffp and vertex shaders though)
747  *
748  * Note that disabling the extension entirely does not gain predictability because there is no point
749  * sprite capability flag in d3d, so the potential rendering bugs are the same if we disable the extension. */
750 static void quirk_one_point_sprite(struct wined3d_gl_info *gl_info)
751 {
752     if (gl_info->supported[ARB_POINT_SPRITE])
753     {
754         TRACE("Limiting point sprites to one texture unit.\n");
755         gl_info->limits.point_sprite_units = 1;
756     }
757 }
758
759 static void quirk_amd_dx9(struct wined3d_gl_info *gl_info)
760 {
761     quirk_arb_constants(gl_info);
762
763     /* MacOS advertises GL_ARB_texture_non_power_of_two on ATI r500 and earlier cards, although
764      * these cards only support GL_ARB_texture_rectangle(D3DPTEXTURECAPS_NONPOW2CONDITIONAL).
765      * If real NP2 textures are used, the driver falls back to software. We could just remove the
766      * extension and use GL_ARB_texture_rectangle instead, but texture_rectangle is inconventient
767      * due to the non-normalized texture coordinates. Thus set an internal extension flag,
768      * GL_WINE_normalized_texrect, which signals the code that it can use non power of two textures
769      * as per GL_ARB_texture_non_power_of_two, but has to stick to the texture_rectangle limits.
770      *
771      * fglrx doesn't advertise GL_ARB_texture_non_power_of_two, but it advertises opengl 2.0 which
772      * has this extension promoted to core. The extension loading code sets this extension supported
773      * due to that, so this code works on fglrx as well. */
774     if(gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
775     {
776         TRACE("GL_ARB_texture_non_power_of_two advertised on R500 or earlier card, removing.\n");
777         gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
778         gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT] = TRUE;
779     }
780
781     /* fglrx has the same structural issues as the one described in quirk_apple_glsl_constants, although
782      * it is generally more efficient. Reserve just 8 constants. */
783     TRACE_(d3d_caps)("Reserving 8 GLSL constants for compiler private use.\n");
784     gl_info->reserved_glsl_constants = max(gl_info->reserved_glsl_constants, 8);
785 }
786
787 static void quirk_no_np2(struct wined3d_gl_info *gl_info)
788 {
789     /*  The nVidia GeForceFX series reports OpenGL 2.0 capabilities with the latest drivers versions, but
790      *  doesn't explicitly advertise the ARB_tex_npot extension in the GL extension string.
791      *  This usually means that ARB_tex_npot is supported in hardware as long as the application is staying
792      *  within the limits enforced by the ARB_texture_rectangle extension. This however is not true for the
793      *  FX series, which instantly falls back to a slower software path as soon as ARB_tex_npot is used.
794      *  We therefore completely remove ARB_tex_npot from the list of supported extensions.
795      *
796      *  Note that wine_normalized_texrect can't be used in this case because internally it uses ARB_tex_npot,
797      *  triggering the software fallback. There is not much we can do here apart from disabling the
798      *  software-emulated extension and reenable ARB_tex_rect (which was previously disabled
799      *  in IWineD3DImpl_FillGLCaps).
800      *  This fixup removes performance problems on both the FX 5900 and FX 5700 (e.g. for framebuffer
801      *  post-processing effects in the game "Max Payne 2").
802      *  The behaviour can be verified through a simple test app attached in bugreport #14724. */
803     TRACE("GL_ARB_texture_non_power_of_two advertised through OpenGL 2.0 on NV FX card, removing.\n");
804     gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
805     gl_info->supported[ARB_TEXTURE_RECTANGLE] = TRUE;
806 }
807
808 static void quirk_texcoord_w(struct wined3d_gl_info *gl_info)
809 {
810     /* The Intel GPUs on MacOS set the .w register of texcoords to 0.0 by default, which causes problems
811      * with fixed function fragment processing. Ideally this flag should be detected with a test shader
812      * and OpenGL feedback mode, but some GL implementations (MacOS ATI at least, probably all MacOS ones)
813      * do not like vertex shaders in feedback mode and return an error, even though it should be valid
814      * according to the spec.
815      *
816      * We don't want to enable this on all cards, as it adds an extra instruction per texcoord used. This
817      * makes the shader slower and eats instruction slots which should be available to the d3d app.
818      *
819      * ATI Radeon HD 2xxx cards on MacOS have the issue. Instead of checking for the buggy cards, blacklist
820      * all radeon cards on Macs and whitelist the good ones. That way we're prepared for the future. If
821      * this workaround is activated on cards that do not need it, it won't break things, just affect
822      * performance negatively. */
823     TRACE("Enabling vertex texture coord fixes in vertex shaders.\n");
824     gl_info->quirks |= WINED3D_QUIRK_SET_TEXCOORD_W;
825 }
826
827 static void quirk_clip_varying(struct wined3d_gl_info *gl_info)
828 {
829     gl_info->quirks |= WINED3D_QUIRK_GLSL_CLIP_VARYING;
830 }
831
832 static void quirk_allows_specular_alpha(struct wined3d_gl_info *gl_info)
833 {
834     gl_info->quirks |= WINED3D_QUIRK_ALLOWS_SPECULAR_ALPHA;
835 }
836
837 static void quirk_apple_nvts(struct wined3d_gl_info *gl_info)
838 {
839     gl_info->supported[NV_TEXTURE_SHADER] = FALSE;
840     gl_info->supported[NV_TEXTURE_SHADER2] = FALSE;
841 }
842
843 static void quirk_disable_nvvp_clip(struct wined3d_gl_info *gl_info)
844 {
845     gl_info->quirks |= WINED3D_QUIRK_NV_CLIP_BROKEN;
846 }
847
848 static void quirk_fbo_tex_update(struct wined3d_gl_info *gl_info)
849 {
850     gl_info->quirks |= WINED3D_QUIRK_FBO_TEX_UPDATE;
851 }
852
853 struct driver_quirk
854 {
855     BOOL (*match)(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
856             enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device);
857     void (*apply)(struct wined3d_gl_info *gl_info);
858     const char *description;
859 };
860
861 static const struct driver_quirk quirk_table[] =
862 {
863     {
864         match_amd_r300_to_500,
865         quirk_amd_dx9,
866         "AMD GLSL constant and normalized texrect quirk"
867     },
868     /* MacOS advertises more GLSL vertex shader uniforms than supported by the hardware, and if more are
869      * used it falls back to software. While the compiler can detect if the shader uses all declared
870      * uniforms, the optimization fails if the shader uses relative addressing. So any GLSL shader
871      * using relative addressing falls back to software.
872      *
873      * ARB vp gives the correct amount of uniforms, so use it instead of GLSL. */
874     {
875         match_apple,
876         quirk_apple_glsl_constants,
877         "Apple GLSL uniform override"
878     },
879     {
880         match_geforce5,
881         quirk_no_np2,
882         "Geforce 5 NP2 disable"
883     },
884     {
885         match_apple_intel,
886         quirk_texcoord_w,
887         "Init texcoord .w for Apple Intel GPU driver"
888     },
889     {
890         match_apple_nonr500ati,
891         quirk_texcoord_w,
892         "Init texcoord .w for Apple ATI >= r600 GPU driver"
893     },
894     {
895         match_fglrx,
896         quirk_one_point_sprite,
897         "Fglrx point sprite crash workaround"
898     },
899     {
900         match_dx10_capable,
901         quirk_clip_varying,
902         "Reserved varying for gl_ClipPos"
903     },
904     {
905         /* GL_EXT_secondary_color does not allow 4 component secondary colors, but most
906          * GL implementations accept it. The Mac GL is the only implementation known to
907          * reject it.
908          *
909          * If we can pass 4 component specular colors, do it, because (a) we don't have
910          * to screw around with the data, and (b) the D3D fixed function vertex pipeline
911          * passes specular alpha to the pixel shader if any is used. Otherwise the
912          * specular alpha is used to pass the fog coordinate, which we pass to opengl
913          * via GL_EXT_fog_coord.
914          */
915         match_allows_spec_alpha,
916         quirk_allows_specular_alpha,
917         "Allow specular alpha quirk"
918     },
919     {
920         /* The pixel formats provided by GL_NV_texture_shader are broken on OSX
921          * (rdar://5682521).
922          */
923         match_apple_nvts,
924         quirk_apple_nvts,
925         "Apple NV_texture_shader disable"
926     },
927     {
928         match_broken_nv_clip,
929         quirk_disable_nvvp_clip,
930         "Apple NV_vertex_program clip bug quirk"
931     },
932     {
933         match_fbo_tex_update,
934         quirk_fbo_tex_update,
935         "FBO rebind for attachment updates"
936     },
937 };
938
939 /* Certain applications (Steam) complain if we report an outdated driver version. In general,
940  * reporting a driver version is moot because we are not the Windows driver, and we have different
941  * bugs, features, etc.
942  *
943  * The driver version has the form "x.y.z.w".
944  *
945  * "x" is the Windows version the driver is meant for:
946  * 4 -> 95/98/NT4
947  * 5 -> 2000
948  * 6 -> 2000/XP
949  * 7 -> Vista
950  * 8 -> Win 7
951  *
952  * "y" is the maximum Direct3D version the driver supports.
953  * y  -> d3d version mapping:
954  * 11 -> d3d6
955  * 12 -> d3d7
956  * 13 -> d3d8
957  * 14 -> d3d9
958  * 15 -> d3d10
959  * 16 -> d3d10.1
960  * 17 -> d3d11
961  *
962  * "z" is the subversion number.
963  *
964  * "w" is the vendor specific driver build number.
965  */
966
967 struct driver_version_information
968 {
969     enum wined3d_display_driver driver;
970     enum wined3d_driver_model driver_model;
971     const char *driver_name;            /* name of Windows driver */
972     WORD version;                       /* version word ('y'), contained in low word of DriverVersion.HighPart */
973     WORD subversion;                    /* subversion word ('z'), contained in high word of DriverVersion.LowPart */
974     WORD build;                         /* build number ('w'), contained in low word of DriverVersion.LowPart */
975 };
976
977 /* The driver version table contains driver information for different devices on several OS versions. */
978 static const struct driver_version_information driver_version_table[] =
979 {
980     /* AMD
981      * - Radeon HD2x00 (R600) and up supported by current drivers.
982      * - Radeon 9500 (R300) - X1*00 (R5xx) supported up to Catalyst 9.3 (Linux) and 10.2 (XP/Vista/Win7)
983      * - Radeon 7xxx (R100) - 9250 (RV250) supported up to Catalyst 6.11 (XP)
984      * - Rage 128 supported up to XP, latest official build 6.13.3279 dated October 2001 */
985     {DRIVER_AMD_RAGE_128PRO,    DRIVER_MODEL_NT5X,  "ati2dvaa.dll", 13, 3279,  0},
986     {DRIVER_AMD_R100,           DRIVER_MODEL_NT5X,  "ati2dvag.dll", 14, 10, 6614},
987     {DRIVER_AMD_R300,           DRIVER_MODEL_NT5X,  "ati2dvag.dll", 14, 10, 6764},
988     {DRIVER_AMD_R600,           DRIVER_MODEL_NT5X,  "ati2dvag.dll", 14, 10, 8681},
989     {DRIVER_AMD_R300,           DRIVER_MODEL_NT6X,  "atiumdag.dll", 14, 10, 741 },
990     {DRIVER_AMD_R600,           DRIVER_MODEL_NT6X,  "atiumdag.dll", 14, 10, 741 },
991
992     /* Intel
993      * The drivers are unified but not all versions support all GPUs. At some point the 2k/xp
994      * drivers used ialmrnt5.dll for GMA800/GMA900 but at some point the file was renamed to
995      * igxprd32.dll but the GMA800 driver was never updated. */
996     {DRIVER_INTEL_GMA800,       DRIVER_MODEL_NT5X,  "ialmrnt5.dll", 14, 10, 3889},
997     {DRIVER_INTEL_GMA900,       DRIVER_MODEL_NT5X,  "igxprd32.dll", 14, 10, 4764},
998     {DRIVER_INTEL_GMA950,       DRIVER_MODEL_NT5X,  "igxprd32.dll", 14, 10, 4926},
999     {DRIVER_INTEL_GMA3000,      DRIVER_MODEL_NT5X,  "igxprd32.dll", 14, 10, 5218},
1000     {DRIVER_INTEL_GMA950,       DRIVER_MODEL_NT6X,  "igdumd32.dll", 14, 10, 1504},
1001     {DRIVER_INTEL_GMA3000,      DRIVER_MODEL_NT6X,  "igdumd32.dll", 15, 10, 1666},
1002
1003     /* Nvidia
1004      * - Geforce6 and newer cards are supported by the current driver (197.x) on XP-Win7
1005      * - GeforceFX support is up to 173.x on <= XP
1006      * - Geforce2MX/3/4 up to 96.x on <= XP
1007      * - TNT/Geforce1/2 up to 71.x on <= XP
1008      * All version numbers used below are from the Linux nvidia drivers. */
1009     {DRIVER_NVIDIA_TNT,         DRIVER_MODEL_NT5X,  "nv4_disp.dll", 14, 10, 7186},
1010     {DRIVER_NVIDIA_GEFORCE2MX,  DRIVER_MODEL_NT5X,  "nv4_disp.dll", 14, 10, 9371},
1011     {DRIVER_NVIDIA_GEFORCEFX,   DRIVER_MODEL_NT5X,  "nv4_disp.dll", 14, 11, 7516},
1012     {DRIVER_NVIDIA_GEFORCE6,    DRIVER_MODEL_NT5X,  "nv4_disp.dll", 15, 12, 6658},
1013     {DRIVER_NVIDIA_GEFORCE6,    DRIVER_MODEL_NT6X,  "nvd3dum.dll",  15, 12, 6658},
1014 };
1015
1016 struct gpu_description
1017 {
1018     WORD vendor;                    /* reported PCI card vendor ID  */
1019     WORD card;                      /* reported PCI card device ID  */
1020     const char *description;        /* Description of the card e.g. NVIDIA RIVA TNT */
1021     enum wined3d_display_driver driver;
1022     unsigned int vidmem;
1023 };
1024
1025 /* The amount of video memory stored in the gpu description table is the minimum amount of video memory
1026  * found on a board containing a specific GPU. */
1027 static const struct gpu_description gpu_description_table[] =
1028 {
1029     /* Nvidia cards */
1030     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_RIVA_TNT,           "NVIDIA RIVA TNT",                  DRIVER_NVIDIA_TNT,       16  },
1031     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_RIVA_TNT2,          "NVIDIA RIVA TNT2/TNT2 Pro",        DRIVER_NVIDIA_TNT,       32  },
1032     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE,            "NVIDIA GeForce 256",               DRIVER_NVIDIA_TNT,       32  },
1033     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE2,           "NVIDIA GeForce2 GTS/GeForce2 Pro", DRIVER_NVIDIA_TNT,       32  },
1034     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE2_MX,        "NVIDIA GeForce2 MX/MX 400",        DRIVER_NVIDIA_GEFORCE2MX,32  },
1035     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE3,           "NVIDIA GeForce3",                  DRIVER_NVIDIA_GEFORCE2MX,64  },
1036     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE4_MX,        "NVIDIA GeForce4 MX 460",           DRIVER_NVIDIA_GEFORCE2MX,64  },
1037     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE4_TI4200,    "NVIDIA GeForce4 Ti 4200",          DRIVER_NVIDIA_GEFORCE2MX,64, },
1038     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5200,     "NVIDIA GeForce FX 5200",           DRIVER_NVIDIA_GEFORCEFX, 64  },
1039     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5600,     "NVIDIA GeForce FX 5600",           DRIVER_NVIDIA_GEFORCEFX, 128 },
1040     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5800,     "NVIDIA GeForce FX 5800",           DRIVER_NVIDIA_GEFORCEFX, 256 },
1041     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6200,       "NVIDIA GeForce 6200",              DRIVER_NVIDIA_GEFORCE6,  64  },
1042     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6600GT,     "NVIDIA GeForce 6600 GT",           DRIVER_NVIDIA_GEFORCE6,  128 },
1043     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6800,       "NVIDIA GeForce 6800",              DRIVER_NVIDIA_GEFORCE6,  128 },
1044     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7300,       "NVIDIA GeForce Go 7300",           DRIVER_NVIDIA_GEFORCE6,  256 },
1045     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7400,       "NVIDIA GeForce Go 7400",           DRIVER_NVIDIA_GEFORCE6,  256 },
1046     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7600,       "NVIDIA GeForce 7600 GT",           DRIVER_NVIDIA_GEFORCE6,  256 },
1047     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7800GT,     "NVIDIA GeForce 7800 GT",           DRIVER_NVIDIA_GEFORCE6,  256 },
1048     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8300GS,     "NVIDIA GeForce 8300 GS",           DRIVER_NVIDIA_GEFORCE6,  128 },
1049     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8400GS,     "NVIDIA GeForce 8400 GS",           DRIVER_NVIDIA_GEFORCE6,  128 },
1050     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8600GT,     "NVIDIA GeForce 8600 GT",           DRIVER_NVIDIA_GEFORCE6,  256 },
1051     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8600MGT,    "NVIDIA GeForce 8600M GT",          DRIVER_NVIDIA_GEFORCE6,  512 },
1052     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8800GTS,    "NVIDIA GeForce 8800 GTS",          DRIVER_NVIDIA_GEFORCE6,  320 },
1053     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8800GTX,    "NVIDIA GeForce 8800 GTX",          DRIVER_NVIDIA_GEFORCE6,  768 },
1054     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9200,       "NVIDIA GeForce 9200",              DRIVER_NVIDIA_GEFORCE6,  256 },
1055     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9400GT,     "NVIDIA GeForce 9400 GT",           DRIVER_NVIDIA_GEFORCE6,  256 },
1056     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9500GT,     "NVIDIA GeForce 9500 GT",           DRIVER_NVIDIA_GEFORCE6,  256 },
1057     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9600GT,     "NVIDIA GeForce 9600 GT",           DRIVER_NVIDIA_GEFORCE6,  384 },
1058     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9800GT,     "NVIDIA GeForce 9800 GT",           DRIVER_NVIDIA_GEFORCE6,  512 },
1059     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_210,        "NVIDIA GeForce 210",               DRIVER_NVIDIA_GEFORCE6,  512 },
1060     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT220,      "NVIDIA GeForce GT 220",            DRIVER_NVIDIA_GEFORCE6,  512 },
1061     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT240,      "NVIDIA GeForce GT 240",            DRIVER_NVIDIA_GEFORCE6,  512 },
1062     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX260,     "NVIDIA GeForce GTX 260",           DRIVER_NVIDIA_GEFORCE6,  1024},
1063     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX275,     "NVIDIA GeForce GTX 275",           DRIVER_NVIDIA_GEFORCE6,  896 },
1064     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX280,     "NVIDIA GeForce GTX 280",           DRIVER_NVIDIA_GEFORCE6,  1024},
1065     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT320M,     "NVIDIA GeForce GT 320M",           DRIVER_NVIDIA_GEFORCE6,  1024},
1066     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT325M,     "NVIDIA GeForce GT 325M",           DRIVER_NVIDIA_GEFORCE6,  1024},
1067     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT330,      "NVIDIA GeForce GT 330",            DRIVER_NVIDIA_GEFORCE6,  1024},
1068     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTS350M,    "NVIDIA GeForce GTS 350M",          DRIVER_NVIDIA_GEFORCE6,  1024},
1069     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT420,      "NVIDIA GeForce GT 420",            DRIVER_NVIDIA_GEFORCE6,  2048},
1070     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT430,      "NVIDIA GeForce GT 430",            DRIVER_NVIDIA_GEFORCE6,  1024},
1071     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT440,      "NVIDIA GeForce GT 440",            DRIVER_NVIDIA_GEFORCE6,  1024},
1072     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTS450,     "NVIDIA GeForce GTS 450",           DRIVER_NVIDIA_GEFORCE6,  1024},
1073     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX460,     "NVIDIA GeForce GTX 460",           DRIVER_NVIDIA_GEFORCE6,  768 },
1074     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX465,     "NVIDIA GeForce GTX 465",           DRIVER_NVIDIA_GEFORCE6,  1024},
1075     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX470,     "NVIDIA GeForce GTX 470",           DRIVER_NVIDIA_GEFORCE6,  1280},
1076     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX480,     "NVIDIA GeForce GTX 480",           DRIVER_NVIDIA_GEFORCE6,  1536},
1077     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX560,     "NVIDIA GeForce GTX 560 TI",        DRIVER_NVIDIA_GEFORCE6,  1024},
1078     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX570,     "NVIDIA GeForce GTX 570",           DRIVER_NVIDIA_GEFORCE6,  1280},
1079     {HW_VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX580,     "NVIDIA GeForce GTX 580",           DRIVER_NVIDIA_GEFORCE6,  1536},
1080
1081     /* AMD cards */
1082     {HW_VENDOR_AMD,        CARD_AMD_RAGE_128PRO,           "ATI Rage Fury",                    DRIVER_AMD_RAGE_128PRO,  16  },
1083     {HW_VENDOR_AMD,        CARD_AMD_RADEON_7200,           "ATI RADEON 7200 SERIES",           DRIVER_AMD_R100,         32  },
1084     {HW_VENDOR_AMD,        CARD_AMD_RADEON_8500,           "ATI RADEON 8500 SERIES",           DRIVER_AMD_R100,         64  },
1085     {HW_VENDOR_AMD,        CARD_AMD_RADEON_9500,           "ATI Radeon 9500",                  DRIVER_AMD_R300,         64  },
1086     {HW_VENDOR_AMD,        CARD_AMD_RADEON_XPRESS_200M,    "ATI RADEON XPRESS 200M Series",    DRIVER_AMD_R300,         64  },
1087     {HW_VENDOR_AMD,        CARD_AMD_RADEON_X700,           "ATI Radeon X700 SE",               DRIVER_AMD_R300,         128 },
1088     {HW_VENDOR_AMD,        CARD_AMD_RADEON_X1600,          "ATI Radeon X1600 Series",          DRIVER_AMD_R300,         128 },
1089     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD2350,         "ATI Mobility Radeon HD 2350",      DRIVER_AMD_R600,         256 },
1090     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD2600,         "ATI Mobility Radeon HD 2600",      DRIVER_AMD_R600,         256 },
1091     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD2900,         "ATI Radeon HD 2900 XT",            DRIVER_AMD_R600,         512 },
1092     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD3200,         "ATI Radeon HD 3200 Graphics",      DRIVER_AMD_R600,         128 },
1093     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD4350,         "ATI Radeon HD 4350",               DRIVER_AMD_R600,         256 },
1094     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD4600,         "ATI Radeon HD 4600 Series",        DRIVER_AMD_R600,         512 },
1095     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD4700,         "ATI Radeon HD 4700 Series",        DRIVER_AMD_R600,         512 },
1096     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD4800,         "ATI Radeon HD 4800 Series",        DRIVER_AMD_R600,         512 },
1097     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD5400,         "ATI Radeon HD 5400 Series",        DRIVER_AMD_R600,         512 },
1098     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD5600,         "ATI Radeon HD 5600 Series",        DRIVER_AMD_R600,         512 },
1099     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD5700,         "ATI Radeon HD 5700 Series",        DRIVER_AMD_R600,         512 },
1100     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD5800,         "ATI Radeon HD 5800 Series",        DRIVER_AMD_R600,         1024},
1101     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD5900,         "ATI Radeon HD 5900 Series",        DRIVER_AMD_R600,         1024},
1102     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD6310,         "AMD Radeon HD 6310 Graphics",      DRIVER_AMD_R600,         1024},
1103     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD6800,         "AMD Radeon HD 6800 Series",        DRIVER_AMD_R600,         1024},
1104     {HW_VENDOR_AMD,        CARD_AMD_RADEON_HD6900,         "AMD Radeon HD 6900 Series",        DRIVER_AMD_R600,         2048},
1105     /* Intel cards */
1106     {HW_VENDOR_INTEL,      CARD_INTEL_I830G,               "Intel(R) 82830M Graphics Controller",                       DRIVER_INTEL_GMA800,  32 },
1107     {HW_VENDOR_INTEL,      CARD_INTEL_I855G,               "Intel(R) 82852/82855 GM/GME Graphics Controller",           DRIVER_INTEL_GMA800,  32 },
1108     {HW_VENDOR_INTEL,      CARD_INTEL_I865G,               "Intel(R) 82865G Graphics Controller",                       DRIVER_INTEL_GMA800,  32 },
1109     {HW_VENDOR_INTEL,      CARD_INTEL_I915G,               "Intel(R) 82915G/GV/910GL Express Chipset Family",           DRIVER_INTEL_GMA900,  64 },
1110     {HW_VENDOR_INTEL,      CARD_INTEL_I915GM,              "Mobile Intel(R) 915GM/GMS,910GML Express Chipset Family",   DRIVER_INTEL_GMA900,  64 },
1111     {HW_VENDOR_INTEL,      CARD_INTEL_I945GM,              "Mobile Intel(R) 945GM Express Chipset Family",              DRIVER_INTEL_GMA950,  64 },
1112     {HW_VENDOR_INTEL,      CARD_INTEL_X3100,               "Mobile Intel(R) 965 Express Chipset Family",                DRIVER_INTEL_GMA3000, 128},
1113     {HW_VENDOR_INTEL,      CARD_INTEL_GM45,                "Mobile Intel(R) GM45 Express Chipset Family",               DRIVER_INTEL_GMA3000, 512}
1114 };
1115
1116 static const struct driver_version_information *get_driver_version_info(enum wined3d_display_driver driver,
1117         enum wined3d_driver_model driver_model)
1118 {
1119     unsigned int i;
1120
1121     TRACE("Looking up version info for driver=%d driver_model=%d\n", driver, driver_model);
1122     for (i = 0; i < (sizeof(driver_version_table) / sizeof(driver_version_table[0])); i++)
1123     {
1124         const struct driver_version_information *entry = &driver_version_table[i];
1125
1126         if (entry->driver == driver && entry->driver_model == driver_model)
1127         {
1128             TRACE_(d3d_caps)("Found driver '%s' version=%d subversion=%d build=%d\n",
1129                 entry->driver_name, entry->version, entry->subversion, entry->build);
1130
1131             return entry;
1132         }
1133     }
1134     return NULL;
1135 }
1136
1137 static void init_driver_info(struct wined3d_driver_info *driver_info,
1138         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
1139 {
1140     OSVERSIONINFOW os_version;
1141     WORD driver_os_version;
1142     unsigned int i;
1143     enum wined3d_display_driver driver = DRIVER_UNKNOWN;
1144     enum wined3d_driver_model driver_model;
1145     const struct driver_version_information *version_info;
1146
1147     if (wined3d_settings.pci_vendor_id != PCI_VENDOR_NONE)
1148     {
1149         TRACE_(d3d_caps)("Overriding PCI vendor ID with: %04x\n", wined3d_settings.pci_vendor_id);
1150         vendor = wined3d_settings.pci_vendor_id;
1151     }
1152     driver_info->vendor = vendor;
1153
1154     if (wined3d_settings.pci_device_id != PCI_DEVICE_NONE)
1155     {
1156         TRACE_(d3d_caps)("Overriding PCI device ID with: %04x\n", wined3d_settings.pci_device_id);
1157         device = wined3d_settings.pci_device_id;
1158     }
1159     driver_info->device = device;
1160
1161     /* Set a default amount of video memory (64MB). In general this code isn't used unless the user
1162      * overrides the pci ids to a card which is not in our database. */
1163     driver_info->vidmem = WINE_DEFAULT_VIDMEM;
1164
1165     memset(&os_version, 0, sizeof(os_version));
1166     os_version.dwOSVersionInfoSize = sizeof(os_version);
1167     if (!GetVersionExW(&os_version))
1168     {
1169         ERR("Failed to get OS version, reporting 2000/XP.\n");
1170         driver_os_version = 6;
1171         driver_model = DRIVER_MODEL_NT5X;
1172     }
1173     else
1174     {
1175         TRACE("OS version %u.%u.\n", os_version.dwMajorVersion, os_version.dwMinorVersion);
1176         switch (os_version.dwMajorVersion)
1177         {
1178             case 4:
1179                 /* If needed we could distinguish between 9x and NT4, but this code won't make
1180                  * sense for NT4 since it had no way to obtain this info through DirectDraw 3.0.
1181                  */
1182                 driver_os_version = 4;
1183                 driver_model = DRIVER_MODEL_WIN9X;
1184                 break;
1185
1186             case 5:
1187                 driver_os_version = 6;
1188                 driver_model = DRIVER_MODEL_NT5X;
1189                 break;
1190
1191             case 6:
1192                 if (os_version.dwMinorVersion == 0)
1193                 {
1194                     driver_os_version = 7;
1195                     driver_model = DRIVER_MODEL_NT6X;
1196                 }
1197                 else
1198                 {
1199                     if (os_version.dwMinorVersion > 1)
1200                     {
1201                         FIXME("Unhandled OS version %u.%u, reporting Win 7.\n",
1202                                 os_version.dwMajorVersion, os_version.dwMinorVersion);
1203                     }
1204                     driver_os_version = 8;
1205                     driver_model = DRIVER_MODEL_NT6X;
1206                 }
1207                 break;
1208
1209             default:
1210                 FIXME("Unhandled OS version %u.%u, reporting 2000/XP.\n",
1211                         os_version.dwMajorVersion, os_version.dwMinorVersion);
1212                 driver_os_version = 6;
1213                 driver_model = DRIVER_MODEL_NT5X;
1214                 break;
1215         }
1216     }
1217
1218     /* When we reach this stage we always have a vendor or device id (it can be a default one).
1219      * This means that unless the ids are overriden, we will always find a GPU description. */
1220     for (i = 0; i < (sizeof(gpu_description_table) / sizeof(gpu_description_table[0])); i++)
1221     {
1222         if (vendor == gpu_description_table[i].vendor && device == gpu_description_table[i].card)
1223         {
1224             TRACE_(d3d_caps)("Found card %04x:%04x in driver DB.\n", vendor, device);
1225
1226             driver_info->description = gpu_description_table[i].description;
1227             driver_info->vidmem = gpu_description_table[i].vidmem * 1024*1024;
1228             driver = gpu_description_table[i].driver;
1229             break;
1230         }
1231     }
1232
1233     if (wined3d_settings.emulated_textureram)
1234     {
1235         TRACE_(d3d_caps)("Overriding amount of video memory with: %d byte\n", wined3d_settings.emulated_textureram);
1236         driver_info->vidmem = wined3d_settings.emulated_textureram;
1237     }
1238
1239     /* Try to obtain driver version information for the current Windows version. This fails in
1240      * some cases:
1241      * - the gpu is not available on the currently selected OS version:
1242      *   - Geforce GTX480 on Win98. When running applications in compatibility mode on Windows,
1243      *     version information for the current Windows version is returned instead of faked info.
1244      *     We do the same and assume the default Windows version to emulate is WinXP.
1245      *
1246      *   - Videocard is a Riva TNT but winver is set to win7 (there are no drivers for this beast)
1247      *     For now return the XP driver info. Perhaps later on we should return VESA.
1248      *
1249      * - the gpu is not in our database (can happen when the user overrides the vendor_id / device_id)
1250      *   This could be an indication that our database is not up to date, so this should be fixed.
1251      */
1252     version_info = get_driver_version_info(driver, driver_model);
1253     if (version_info)
1254     {
1255         driver_info->name = version_info->driver_name;
1256         driver_info->version_high = MAKEDWORD_VERSION(driver_os_version, version_info->version);
1257         driver_info->version_low = MAKEDWORD_VERSION(version_info->subversion, version_info->build);
1258     }
1259     else
1260     {
1261         version_info = get_driver_version_info(driver, DRIVER_MODEL_NT5X);
1262         if (version_info)
1263         {
1264             driver_info->name = version_info->driver_name;
1265             driver_info->version_high = MAKEDWORD_VERSION(driver_os_version, version_info->version);
1266             driver_info->version_low = MAKEDWORD_VERSION(version_info->subversion, version_info->build);
1267         }
1268         else
1269         {
1270             driver_info->description = "Direct3D HAL";
1271             driver_info->name = "Display";
1272             driver_info->version_high = MAKEDWORD_VERSION(driver_os_version, 15);
1273             driver_info->version_low = MAKEDWORD_VERSION(8, 6); /* Nvidia RIVA TNT, arbitrary */
1274
1275             FIXME("Unable to find a driver/device info for vendor_id=%#x device_id=%#x for driver_model=%d\n",
1276                     vendor, device, driver_model);
1277         }
1278     }
1279
1280     TRACE_(d3d_caps)("Reporting (fake) driver version 0x%08x-0x%08x.\n",
1281             driver_info->version_high, driver_info->version_low);
1282 }
1283
1284 /* Context activation is done by the caller. */
1285 static void fixup_extensions(struct wined3d_gl_info *gl_info, const char *gl_renderer,
1286         enum wined3d_gl_vendor gl_vendor, enum wined3d_pci_vendor card_vendor, enum wined3d_pci_device device)
1287 {
1288     unsigned int i;
1289
1290     for (i = 0; i < (sizeof(quirk_table) / sizeof(*quirk_table)); ++i)
1291     {
1292         if (!quirk_table[i].match(gl_info, gl_renderer, gl_vendor, card_vendor, device)) continue;
1293         TRACE_(d3d_caps)("Applying driver quirk \"%s\".\n", quirk_table[i].description);
1294         quirk_table[i].apply(gl_info);
1295     }
1296
1297     /* Find out if PBOs work as they are supposed to. */
1298     test_pbo_functionality(gl_info);
1299 }
1300
1301 static DWORD wined3d_parse_gl_version(const char *gl_version)
1302 {
1303     const char *ptr = gl_version;
1304     int major, minor;
1305
1306     major = atoi(ptr);
1307     if (major <= 0) ERR_(d3d_caps)("Invalid opengl major version: %d.\n", major);
1308
1309     while (isdigit(*ptr)) ++ptr;
1310     if (*ptr++ != '.') ERR_(d3d_caps)("Invalid opengl version string: %s.\n", debugstr_a(gl_version));
1311
1312     minor = atoi(ptr);
1313
1314     TRACE_(d3d_caps)("Found OpenGL version: %d.%d.\n", major, minor);
1315
1316     return MAKEDWORD_VERSION(major, minor);
1317 }
1318
1319 static enum wined3d_gl_vendor wined3d_guess_gl_vendor(struct wined3d_gl_info *gl_info, const char *gl_vendor_string, const char *gl_renderer)
1320 {
1321
1322     /* MacOS has various specialities in the extensions it advertises. Some have to be loaded from
1323      * the opengl 1.2+ core, while other extensions are advertised, but software emulated. So try to
1324      * detect the Apple OpenGL implementation to apply some extension fixups afterwards.
1325      *
1326      * Detecting this isn't really easy. The vendor string doesn't mention Apple. Compile-time checks
1327      * aren't sufficient either because a Linux binary may display on a macos X server via remote X11.
1328      * So try to detect the GL implementation by looking at certain Apple extensions. Some extensions
1329      * like client storage might be supported on other implementations too, but GL_APPLE_flush_render
1330      * is specific to the Mac OS X window management, and GL_APPLE_ycbcr_422 is QuickTime specific. So
1331      * the chance that other implementations support them is rather small since Win32 QuickTime uses
1332      * DirectDraw, not OpenGL. */
1333     if (gl_info->supported[APPLE_FENCE]
1334             && gl_info->supported[APPLE_CLIENT_STORAGE]
1335             && gl_info->supported[APPLE_FLUSH_RENDER]
1336             && gl_info->supported[APPLE_YCBCR_422])
1337         return GL_VENDOR_APPLE;
1338
1339     if (strstr(gl_vendor_string, "NVIDIA"))
1340         return GL_VENDOR_NVIDIA;
1341
1342     if (strstr(gl_vendor_string, "ATI"))
1343         return GL_VENDOR_FGLRX;
1344
1345     if (strstr(gl_vendor_string, "Intel(R)")
1346             /* Intel switched from Intel(R) to Intel® recently, so just match Intel. */
1347             || strstr(gl_renderer, "Intel")
1348             || strstr(gl_vendor_string, "Intel Inc."))
1349         return GL_VENDOR_INTEL;
1350
1351     if (strstr(gl_vendor_string, "Mesa")
1352             || strstr(gl_vendor_string, "Advanced Micro Devices, Inc.")
1353             || strstr(gl_vendor_string, "DRI R300 Project")
1354             || strstr(gl_vendor_string, "X.Org R300 Project")
1355             || strstr(gl_vendor_string, "Tungsten Graphics, Inc")
1356             || strstr(gl_vendor_string, "VMware, Inc.")
1357             || strstr(gl_renderer, "Mesa")
1358             || strstr(gl_renderer, "Gallium"))
1359         return GL_VENDOR_MESA;
1360
1361     FIXME_(d3d_caps)("Received unrecognized GL_VENDOR %s. Returning GL_VENDOR_UNKNOWN.\n",
1362             debugstr_a(gl_vendor_string));
1363
1364     return GL_VENDOR_UNKNOWN;
1365 }
1366
1367 static enum wined3d_pci_vendor wined3d_guess_card_vendor(const char *gl_vendor_string, const char *gl_renderer)
1368 {
1369     if (strstr(gl_vendor_string, "NVIDIA")
1370             || strstr(gl_vendor_string, "nouveau"))
1371         return HW_VENDOR_NVIDIA;
1372
1373     if (strstr(gl_vendor_string, "ATI")
1374             || strstr(gl_vendor_string, "Advanced Micro Devices, Inc.")
1375             || strstr(gl_vendor_string, "X.Org R300 Project")
1376             || strstr(gl_renderer, "AMD")
1377             || strstr(gl_renderer, "R100")
1378             || strstr(gl_renderer, "R200")
1379             || strstr(gl_renderer, "R300")
1380             || strstr(gl_renderer, "R600")
1381             || strstr(gl_renderer, "R700"))
1382         return HW_VENDOR_AMD;
1383
1384     if (strstr(gl_vendor_string, "Intel(R)")
1385             /* Intel switched from Intel(R) to Intel® recently, so just match Intel. */
1386             || strstr(gl_renderer, "Intel")
1387             || strstr(gl_vendor_string, "Intel Inc."))
1388         return HW_VENDOR_INTEL;
1389
1390     if (strstr(gl_vendor_string, "Mesa")
1391             || strstr(gl_vendor_string, "Tungsten Graphics, Inc")
1392             || strstr(gl_vendor_string, "VMware, Inc."))
1393         return HW_VENDOR_SOFTWARE;
1394
1395     FIXME_(d3d_caps)("Received unrecognized GL_VENDOR %s. Returning HW_VENDOR_NVIDIA.\n", debugstr_a(gl_vendor_string));
1396
1397     return HW_VENDOR_NVIDIA;
1398 }
1399
1400
1401
1402 static enum wined3d_pci_device select_card_nvidia_binary(const struct wined3d_gl_info *gl_info,
1403         const char *gl_renderer)
1404 {
1405     unsigned int i;
1406
1407     if (WINE_D3D10_CAPABLE(gl_info))
1408     {
1409         static const struct
1410         {
1411             const char *renderer;
1412             enum wined3d_pci_device id;
1413         }
1414         cards[] =
1415         {
1416             {"GTX 580",     CARD_NVIDIA_GEFORCE_GTX580},    /* Geforce 500 - highend */
1417             {"GTX 570",     CARD_NVIDIA_GEFORCE_GTX570},    /* Geforce 500 - midend high */
1418             {"GTX 560 TI",  CARD_NVIDIA_GEFORCE_GTX560},    /* Geforce 500 - midend */
1419             {"GTX 480",     CARD_NVIDIA_GEFORCE_GTX480},    /* Geforce 400 - highend */
1420             {"GTX 470",     CARD_NVIDIA_GEFORCE_GTX470},    /* Geforce 400 - midend high */
1421             {"GTX 465",     CARD_NVIDIA_GEFORCE_GTX465},    /* Geforce 400 - midend */
1422             {"GTX 460",     CARD_NVIDIA_GEFORCE_GTX460},    /* Geforce 400 - midend */
1423             {"GTS 450",     CARD_NVIDIA_GEFORCE_GTS450},    /* Geforce 400 - midend low */
1424             {"GT 440",      CARD_NVIDIA_GEFORCE_GT440},     /* Geforce 400 - lowend */
1425             {"GT 430",      CARD_NVIDIA_GEFORCE_GT430},     /* Geforce 400 - lowend */
1426             {"GT 420",      CARD_NVIDIA_GEFORCE_GT420},     /* Geforce 400 - lowend */
1427             {"GT 330",      CARD_NVIDIA_GEFORCE_GT330},     /* Geforce 300 - highend */
1428             {"GTS 360M",    CARD_NVIDIA_GEFORCE_GTS350M},   /* Geforce 300 - highend mobile */
1429             {"GTS 350M",    CARD_NVIDIA_GEFORCE_GTS350M},   /* Geforce 300 - highend mobile */
1430             {"GT 330M",     CARD_NVIDIA_GEFORCE_GT325M},    /* Geforce 300 - midend mobile */
1431             {"GT 325M",     CARD_NVIDIA_GEFORCE_GT325M},    /* Geforce 300 - midend mobile */
1432             {"GT 320M",     CARD_NVIDIA_GEFORCE_GT320M},    /* Geforce 300 - midend mobile */
1433             {"GTX 295",     CARD_NVIDIA_GEFORCE_GTX280},    /* Geforce 200 - highend */
1434             {"GTX 285",     CARD_NVIDIA_GEFORCE_GTX280},    /* Geforce 200 - highend */
1435             {"GTX 280",     CARD_NVIDIA_GEFORCE_GTX280},    /* Geforce 200 - highend */
1436             {"GTX 275",     CARD_NVIDIA_GEFORCE_GTX275},    /* Geforce 200 - midend high */
1437             {"GTX 260",     CARD_NVIDIA_GEFORCE_GTX260},    /* Geforce 200 - midend */
1438             {"GT 240",      CARD_NVIDIA_GEFORCE_GT240},     /* Geforce 200 - midend */
1439             {"GT 220",      CARD_NVIDIA_GEFORCE_GT220},     /* Geforce 200 - lowend */
1440             {"Geforce 310", CARD_NVIDIA_GEFORCE_210},       /* Geforce 200 - lowend */
1441             {"Geforce 305", CARD_NVIDIA_GEFORCE_210},       /* Geforce 200 - lowend */
1442             {"Geforce 210", CARD_NVIDIA_GEFORCE_210},       /* Geforce 200 - lowend */
1443             {"G 210",       CARD_NVIDIA_GEFORCE_210},       /* Geforce 200 - lowend */
1444             {"GTS 250",     CARD_NVIDIA_GEFORCE_9800GT},    /* Geforce 9 - highend / Geforce 200 - midend */
1445             {"GTS 150",     CARD_NVIDIA_GEFORCE_9800GT},    /* Geforce 9 - highend / Geforce 200 - midend */
1446             {"9800",        CARD_NVIDIA_GEFORCE_9800GT},    /* Geforce 9 - highend / Geforce 200 - midend */
1447             {"GT 140",      CARD_NVIDIA_GEFORCE_9600GT},    /* Geforce 9 - midend */
1448             {"9600",        CARD_NVIDIA_GEFORCE_9600GT},    /* Geforce 9 - midend */
1449             {"GT 130",      CARD_NVIDIA_GEFORCE_9500GT},    /* Geforce 9 - midend low / Geforce 200 - low */
1450             {"GT 120",      CARD_NVIDIA_GEFORCE_9500GT},    /* Geforce 9 - midend low / Geforce 200 - low */
1451             {"9500",        CARD_NVIDIA_GEFORCE_9500GT},    /* Geforce 9 - midend low / Geforce 200 - low */
1452             {"9400",        CARD_NVIDIA_GEFORCE_9400GT},    /* Geforce 9 - lowend */
1453             {"9300",        CARD_NVIDIA_GEFORCE_9200},      /* Geforce 9 - lowend low */
1454             {"9200",        CARD_NVIDIA_GEFORCE_9200},      /* Geforce 9 - lowend low */
1455             {"9100",        CARD_NVIDIA_GEFORCE_9200},      /* Geforce 9 - lowend low */
1456             {"G 100",       CARD_NVIDIA_GEFORCE_9200},      /* Geforce 9 - lowend low */
1457             {"8800 GTX",    CARD_NVIDIA_GEFORCE_8800GTX},   /* Geforce 8 - highend high */
1458             {"8800",        CARD_NVIDIA_GEFORCE_8800GTS},   /* Geforce 8 - highend */
1459             {"8600 M",      CARD_NVIDIA_GEFORCE_8600MGT},   /* Geforce 8 - midend mobile */
1460             {"8700",        CARD_NVIDIA_GEFORCE_8600GT},    /* Geforce 8 - midend */
1461             {"8600",        CARD_NVIDIA_GEFORCE_8600GT},    /* Geforce 8 - midend */
1462             {"8500",        CARD_NVIDIA_GEFORCE_8400GS},    /* Geforce 8 - mid-lowend */
1463             {"8400",        CARD_NVIDIA_GEFORCE_8400GS},    /* Geforce 8 - mid-lowend */
1464             {"8300",        CARD_NVIDIA_GEFORCE_8300GS},    /* Geforce 8 - lowend */
1465             {"8200",        CARD_NVIDIA_GEFORCE_8300GS},    /* Geforce 8 - lowend */
1466             {"8100",        CARD_NVIDIA_GEFORCE_8300GS},    /* Geforce 8 - lowend */
1467         };
1468
1469         for (i = 0; i < sizeof(cards) / sizeof(*cards); ++i)
1470         {
1471             if (strstr(gl_renderer, cards[i].renderer))
1472                 return cards[i].id;
1473         }
1474
1475         /* Geforce8-compatible fall back if the GPU is not in the list yet */
1476         return CARD_NVIDIA_GEFORCE_8300GS;
1477     }
1478
1479     /* Both the GeforceFX, 6xxx and 7xxx series support D3D9. The last two types have more
1480      * shader capabilities, so we use the shader capabilities to distinguish between FX and 6xxx/7xxx.
1481      */
1482     if (WINE_D3D9_CAPABLE(gl_info) && gl_info->supported[NV_VERTEX_PROGRAM3])
1483     {
1484         static const struct
1485         {
1486             const char *renderer;
1487             enum wined3d_pci_device id;
1488         }
1489         cards[] =
1490         {
1491             {"Quadro FX 5", CARD_NVIDIA_GEFORCE_7800GT},    /* Geforce 7 - highend */
1492             {"Quadro FX 4", CARD_NVIDIA_GEFORCE_7800GT},    /* Geforce 7 - highend */
1493             {"7950",        CARD_NVIDIA_GEFORCE_7800GT},    /* Geforce 7 - highend */
1494             {"7900",        CARD_NVIDIA_GEFORCE_7800GT},    /* Geforce 7 - highend */
1495             {"7800",        CARD_NVIDIA_GEFORCE_7800GT},    /* Geforce 7 - highend */
1496             {"7700",        CARD_NVIDIA_GEFORCE_7600},      /* Geforce 7 - midend */
1497             {"7600",        CARD_NVIDIA_GEFORCE_7600},      /* Geforce 7 - midend */
1498             {"7400",        CARD_NVIDIA_GEFORCE_7400},      /* Geforce 7 - lower medium */
1499             {"7300",        CARD_NVIDIA_GEFORCE_7300},      /* Geforce 7 - lowend */
1500             {"6800",        CARD_NVIDIA_GEFORCE_6800},      /* Geforce 6 - highend */
1501             {"6700",        CARD_NVIDIA_GEFORCE_6600GT},    /* Geforce 6 - midend */
1502             {"6610",        CARD_NVIDIA_GEFORCE_6600GT},    /* Geforce 6 - midend */
1503             {"6600",        CARD_NVIDIA_GEFORCE_6600GT},    /* Geforce 6 - midend */
1504         };
1505
1506         for (i = 0; i < sizeof(cards) / sizeof(*cards); ++i)
1507         {
1508             if (strstr(gl_renderer, cards[i].renderer))
1509                 return cards[i].id;
1510         }
1511
1512         /* Geforce 6/7 - lowend */
1513         return CARD_NVIDIA_GEFORCE_6200; /* Geforce 6100/6150/6200/7300/7400/7500 */
1514     }
1515
1516     if (WINE_D3D9_CAPABLE(gl_info))
1517     {
1518         /* GeforceFX - highend */
1519         if (strstr(gl_renderer, "5800")
1520                 || strstr(gl_renderer, "5900")
1521                 || strstr(gl_renderer, "5950")
1522                 || strstr(gl_renderer, "Quadro FX"))
1523         {
1524             return CARD_NVIDIA_GEFORCEFX_5800;
1525         }
1526
1527         /* GeforceFX - midend */
1528         if (strstr(gl_renderer, "5600")
1529                 || strstr(gl_renderer, "5650")
1530                 || strstr(gl_renderer, "5700")
1531                 || strstr(gl_renderer, "5750"))
1532         {
1533             return CARD_NVIDIA_GEFORCEFX_5600;
1534         }
1535
1536         /* GeforceFX - lowend */
1537         return CARD_NVIDIA_GEFORCEFX_5200; /* GeforceFX 5100/5200/5250/5300/5500 */
1538     }
1539
1540     if (WINE_D3D8_CAPABLE(gl_info))
1541     {
1542         if (strstr(gl_renderer, "GeForce4 Ti") || strstr(gl_renderer, "Quadro4"))
1543         {
1544             return CARD_NVIDIA_GEFORCE4_TI4200; /* Geforce4 Ti4200/Ti4400/Ti4600/Ti4800, Quadro4 */
1545         }
1546
1547         return CARD_NVIDIA_GEFORCE3; /* Geforce3 standard/Ti200/Ti500, Quadro DCC */
1548     }
1549
1550     if (WINE_D3D7_CAPABLE(gl_info))
1551     {
1552         if (strstr(gl_renderer, "GeForce4 MX"))
1553         {
1554             return CARD_NVIDIA_GEFORCE4_MX; /* MX420/MX440/MX460/MX4000 */
1555         }
1556
1557         if (strstr(gl_renderer, "GeForce2 MX") || strstr(gl_renderer, "Quadro2 MXR"))
1558         {
1559             return CARD_NVIDIA_GEFORCE2_MX; /* Geforce2 standard/MX100/MX200/MX400, Quadro2 MXR */
1560         }
1561
1562         if (strstr(gl_renderer, "GeForce2") || strstr(gl_renderer, "Quadro2"))
1563         {
1564             return CARD_NVIDIA_GEFORCE2; /* Geforce2 GTS/Pro/Ti/Ultra, Quadro2 */
1565         }
1566
1567         return CARD_NVIDIA_GEFORCE; /* Geforce 256/DDR, Quadro */
1568     }
1569
1570     if (strstr(gl_renderer, "TNT2"))
1571     {
1572         return CARD_NVIDIA_RIVA_TNT2; /* Riva TNT2 standard/M64/Pro/Ultra */
1573     }
1574
1575     return CARD_NVIDIA_RIVA_TNT; /* Riva TNT, Vanta */
1576 }
1577
1578 static enum wined3d_pci_device select_card_amd_binary(const struct wined3d_gl_info *gl_info,
1579         const char *gl_renderer)
1580 {
1581     /* See http://developer.amd.com/drivers/pc_vendor_id/Pages/default.aspx
1582      *
1583      * Beware: renderer string do not match exact card model,
1584      * eg HD 4800 is returned for multiple cards, even for RV790 based ones. */
1585     if (WINE_D3D10_CAPABLE(gl_info))
1586     {
1587         unsigned int i;
1588
1589         static const struct
1590         {
1591             const char *renderer;
1592             enum wined3d_pci_device id;
1593         }
1594         cards[] =
1595         {
1596             /* Evergreen */
1597             {"HD 5870", CARD_AMD_RADEON_HD5800},    /* Radeon EG CYPRESS PRO */
1598             {"HD 5850", CARD_AMD_RADEON_HD5800},    /* Radeon EG CYPRESS XT */
1599             {"HD 5800", CARD_AMD_RADEON_HD5800},    /* Radeon EG CYPRESS HD58xx generic renderer string */
1600             {"HD 5770", CARD_AMD_RADEON_HD5700},    /* Radeon EG JUNIPER XT */
1601             {"HD 5750", CARD_AMD_RADEON_HD5700},    /* Radeon EG JUNIPER LE */
1602             {"HD 5700", CARD_AMD_RADEON_HD5700},    /* Radeon EG JUNIPER HD57xx generic renderer string */
1603             {"HD 5670", CARD_AMD_RADEON_HD5600},    /* Radeon EG REDWOOD XT */
1604             {"HD 5570", CARD_AMD_RADEON_HD5600},    /* Radeon EG REDWOOD PRO mapped to HD5600 series */
1605             {"HD 5550", CARD_AMD_RADEON_HD5600},    /* Radeon EG REDWOOD LE mapped to HD5600 series */
1606             {"HD 5450", CARD_AMD_RADEON_HD5400},    /* Radeon EG CEDAR PRO */
1607             /* R700 */
1608             {"HD 4890", CARD_AMD_RADEON_HD4800},    /* Radeon RV790 */
1609             {"HD 4870", CARD_AMD_RADEON_HD4800},    /* Radeon RV770 */
1610             {"HD 4850", CARD_AMD_RADEON_HD4800},    /* Radeon RV770 */
1611             {"HD 4830", CARD_AMD_RADEON_HD4800},    /* Radeon RV770 */
1612             {"HD 4800", CARD_AMD_RADEON_HD4800},    /* Radeon RV7xx HD48xx generic renderer string */
1613             {"HD 4770", CARD_AMD_RADEON_HD4700},    /* Radeon RV740 */
1614             {"HD 4700", CARD_AMD_RADEON_HD4700},    /* Radeon RV7xx HD47xx generic renderer string */
1615             {"HD 4670", CARD_AMD_RADEON_HD4600},    /* Radeon RV730 */
1616             {"HD 4650", CARD_AMD_RADEON_HD4600},    /* Radeon RV730 */
1617             {"HD 4600", CARD_AMD_RADEON_HD4600},    /* Radeon RV730 */
1618             {"HD 4550", CARD_AMD_RADEON_HD4350},    /* Radeon RV710 */
1619             {"HD 4350", CARD_AMD_RADEON_HD4350},    /* Radeon RV710 */
1620             /* R600/R700 integrated */
1621             {"HD 3300", CARD_AMD_RADEON_HD3200},
1622             {"HD 3200", CARD_AMD_RADEON_HD3200},
1623             {"HD 3100", CARD_AMD_RADEON_HD3200},
1624             /* R600 */
1625             {"HD 3870", CARD_AMD_RADEON_HD2900},    /* HD2900/HD3800 - highend */
1626             {"HD 3850", CARD_AMD_RADEON_HD2900},    /* HD2900/HD3800 - highend */
1627             {"HD 2900", CARD_AMD_RADEON_HD2900},    /* HD2900/HD3800 - highend */
1628             {"HD 3830", CARD_AMD_RADEON_HD2600},    /* China-only midend */
1629             {"HD 3690", CARD_AMD_RADEON_HD2600},    /* HD2600/HD3600 - midend */
1630             {"HD 3650", CARD_AMD_RADEON_HD2600},    /* HD2600/HD3600 - midend */
1631             {"HD 2600", CARD_AMD_RADEON_HD2600},    /* HD2600/HD3600 - midend */
1632             {"HD 3470", CARD_AMD_RADEON_HD2350},    /* HD2350/HD2400/HD3400 - lowend */
1633             {"HD 3450", CARD_AMD_RADEON_HD2350},    /* HD2350/HD2400/HD3400 - lowend */
1634             {"HD 3430", CARD_AMD_RADEON_HD2350},    /* HD2350/HD2400/HD3400 - lowend */
1635             {"HD 3400", CARD_AMD_RADEON_HD2350},    /* HD2350/HD2400/HD3400 - lowend */
1636             {"HD 2400", CARD_AMD_RADEON_HD2350},    /* HD2350/HD2400/HD3400 - lowend */
1637             {"HD 2350", CARD_AMD_RADEON_HD2350},    /* HD2350/HD2400/HD3400 - lowend */
1638         };
1639
1640         for (i = 0; i < sizeof(cards) / sizeof(*cards); ++i)
1641         {
1642             if (strstr(gl_renderer, cards[i].renderer))
1643                 return cards[i].id;
1644         }
1645
1646         /* Default for when no GPU has been found */
1647         return CARD_AMD_RADEON_HD3200;
1648     }
1649
1650     if (WINE_D3D8_CAPABLE(gl_info))
1651     {
1652         /* Radeon R5xx */
1653         if (strstr(gl_renderer, "X1600")
1654                 || strstr(gl_renderer, "X1650")
1655                 || strstr(gl_renderer, "X1800")
1656                 || strstr(gl_renderer, "X1900")
1657                 || strstr(gl_renderer, "X1950"))
1658         {
1659             return CARD_AMD_RADEON_X1600;
1660         }
1661
1662         /* Radeon R4xx + X1300/X1400/X1450/X1550/X2300/X2500/HD2300 (lowend R5xx)
1663          * Note X2300/X2500/HD2300 are R5xx GPUs with a 2xxx naming but they are still DX9-only */
1664         if (strstr(gl_renderer, "X700")
1665                 || strstr(gl_renderer, "X800")
1666                 || strstr(gl_renderer, "X850")
1667                 || strstr(gl_renderer, "X1300")
1668                 || strstr(gl_renderer, "X1400")
1669                 || strstr(gl_renderer, "X1450")
1670                 || strstr(gl_renderer, "X1550")
1671                 || strstr(gl_renderer, "X2300")
1672                 || strstr(gl_renderer, "X2500")
1673                 || strstr(gl_renderer, "HD 2300")
1674                 )
1675         {
1676             return CARD_AMD_RADEON_X700;
1677         }
1678
1679         /* Radeon Xpress Series - onboard, DX9b, Shader 2.0, 300-400MHz */
1680         if (strstr(gl_renderer, "Radeon Xpress"))
1681         {
1682             return CARD_AMD_RADEON_XPRESS_200M;
1683         }
1684
1685         /* Radeon R3xx */
1686         return CARD_AMD_RADEON_9500; /* Radeon 9500/9550/9600/9700/9800/X300/X550/X600 */
1687     }
1688
1689     if (WINE_D3D8_CAPABLE(gl_info))
1690     {
1691         return CARD_AMD_RADEON_8500; /* Radeon 8500/9000/9100/9200/9300 */
1692     }
1693
1694     if (WINE_D3D7_CAPABLE(gl_info))
1695     {
1696         return CARD_AMD_RADEON_7200; /* Radeon 7000/7100/7200/7500 */
1697     }
1698
1699     return CARD_AMD_RAGE_128PRO;
1700 }
1701
1702 static enum wined3d_pci_device select_card_intel(const struct wined3d_gl_info *gl_info,
1703         const char *gl_renderer)
1704 {
1705     if (strstr(gl_renderer, "GM45")) return CARD_INTEL_GM45;
1706     if (strstr(gl_renderer, "X3100") || strstr(gl_renderer, "965GM"))
1707     {
1708         /* MacOS calls the card GMA X3100, otherwise known as GM965/GL960 */
1709         return CARD_INTEL_X3100;
1710     }
1711
1712     if (strstr(gl_renderer, "GMA 950") || strstr(gl_renderer, "945GM"))
1713     {
1714         /* MacOS calls the card GMA 950, but everywhere else the PCI ID is named 945GM */
1715         return CARD_INTEL_I945GM;
1716     }
1717
1718     if (strstr(gl_renderer, "915GM")) return CARD_INTEL_I915GM;
1719     if (strstr(gl_renderer, "915G")) return CARD_INTEL_I915G;
1720     if (strstr(gl_renderer, "865G")) return CARD_INTEL_I865G;
1721     if (strstr(gl_renderer, "855G")) return CARD_INTEL_I855G;
1722     if (strstr(gl_renderer, "830G")) return CARD_INTEL_I830G;
1723     return CARD_INTEL_I915G;
1724
1725 }
1726
1727 static enum wined3d_pci_device select_card_amd_mesa(const struct wined3d_gl_info *gl_info,
1728         const char *gl_renderer)
1729 {
1730     unsigned int i;
1731
1732     /* See http://developer.amd.com/drivers/pc_vendor_id/Pages/default.aspx
1733      *
1734      * Beware: renderer string do not match exact card model,
1735      * eg HD 4800 is returned for multiple cards, even for RV790 based ones. */
1736     if (strstr(gl_renderer, "Gallium"))
1737     {
1738         /* 20101109 - These are never returned by current Gallium radeon
1739          * drivers: R700, RV790, R680, RV535, RV516, R410, RS485, RV360, RV351.
1740          *
1741          * These are returned but not handled: RC410, RV380. */
1742         static const struct
1743         {
1744             const char *renderer;
1745             enum wined3d_pci_device id;
1746         }
1747         cards[] =
1748         {
1749             /* Northern Islands */
1750             {"CAYMAN",  CARD_AMD_RADEON_HD6900},
1751             {"BARTS",   CARD_AMD_RADEON_HD6800},
1752             {"PALM",    CARD_AMD_RADEON_HD6310},
1753             /* Evergreen */
1754             {"HEMLOCK", CARD_AMD_RADEON_HD5900},
1755             {"CYPRESS", CARD_AMD_RADEON_HD5800},
1756             {"JUNIPER", CARD_AMD_RADEON_HD5700},
1757             {"REDWOOD", CARD_AMD_RADEON_HD5600},
1758             {"CEDAR",   CARD_AMD_RADEON_HD5400},
1759             /* R700 */
1760             {"R700",    CARD_AMD_RADEON_HD4800},    /* HD4800 - highend */
1761             {"RV790",   CARD_AMD_RADEON_HD4800},
1762             {"RV770",   CARD_AMD_RADEON_HD4800},
1763             {"RV740",   CARD_AMD_RADEON_HD4700},    /* HD4700 - midend */
1764             {"RV730",   CARD_AMD_RADEON_HD4600},    /* HD4600 - midend */
1765             {"RV710",   CARD_AMD_RADEON_HD4350},    /* HD4500/HD4350 - lowend */
1766             /* R600/R700 integrated */
1767             {"RS880",   CARD_AMD_RADEON_HD3200},
1768             {"RS780",   CARD_AMD_RADEON_HD3200},
1769             /* R600 */
1770             {"R680",    CARD_AMD_RADEON_HD2900},    /* HD2900/HD3800 - highend */
1771             {"R600",    CARD_AMD_RADEON_HD2900},
1772             {"RV670",   CARD_AMD_RADEON_HD2900},
1773             {"RV635",   CARD_AMD_RADEON_HD2600},    /* HD2600/HD3600 - midend; HD3830 is China-only midend */
1774             {"RV630",   CARD_AMD_RADEON_HD2600},
1775             {"RV620",   CARD_AMD_RADEON_HD2350},    /* HD2350/HD2400/HD3400 - lowend */
1776             {"RV610",   CARD_AMD_RADEON_HD2350},
1777             /* R500 */
1778             {"R580",    CARD_AMD_RADEON_X1600},
1779             {"R520",    CARD_AMD_RADEON_X1600},
1780             {"RV570",   CARD_AMD_RADEON_X1600},
1781             {"RV560",   CARD_AMD_RADEON_X1600},
1782             {"RV535",   CARD_AMD_RADEON_X1600},
1783             {"RV530",   CARD_AMD_RADEON_X1600},
1784             {"RV516",   CARD_AMD_RADEON_X700},      /* X700 is actually R400. */
1785             {"RV515",   CARD_AMD_RADEON_X700},
1786             /* R400 */
1787             {"R481",    CARD_AMD_RADEON_X700},
1788             {"R480",    CARD_AMD_RADEON_X700},
1789             {"R430",    CARD_AMD_RADEON_X700},
1790             {"R423",    CARD_AMD_RADEON_X700},
1791             {"R420",    CARD_AMD_RADEON_X700},
1792             {"R410",    CARD_AMD_RADEON_X700},
1793             {"RV410",   CARD_AMD_RADEON_X700},
1794             /* Radeon Xpress - onboard, DX9b, Shader 2.0, 300-400MHz */
1795             {"RS740",   CARD_AMD_RADEON_XPRESS_200M},
1796             {"RS690",   CARD_AMD_RADEON_XPRESS_200M},
1797             {"RS600",   CARD_AMD_RADEON_XPRESS_200M},
1798             {"RS485",   CARD_AMD_RADEON_XPRESS_200M},
1799             {"RS482",   CARD_AMD_RADEON_XPRESS_200M},
1800             {"RS480",   CARD_AMD_RADEON_XPRESS_200M},
1801             {"RS400",   CARD_AMD_RADEON_XPRESS_200M},
1802             /* R300 */
1803             {"R360",    CARD_AMD_RADEON_9500},
1804             {"R350",    CARD_AMD_RADEON_9500},
1805             {"R300",    CARD_AMD_RADEON_9500},
1806             {"RV370",   CARD_AMD_RADEON_9500},
1807             {"RV360",   CARD_AMD_RADEON_9500},
1808             {"RV351",   CARD_AMD_RADEON_9500},
1809             {"RV350",   CARD_AMD_RADEON_9500},
1810         };
1811
1812         for (i = 0; i < sizeof(cards) / sizeof(*cards); ++i)
1813         {
1814             if (strstr(gl_renderer, cards[i].renderer))
1815                 return cards[i].id;
1816         }
1817     }
1818
1819     if (WINE_D3D9_CAPABLE(gl_info))
1820     {
1821         static const struct
1822         {
1823             const char *renderer;
1824             enum wined3d_pci_device id;
1825         }
1826         cards[] =
1827         {
1828             /* R700 */
1829             {"(R700",   CARD_AMD_RADEON_HD4800},    /* HD4800 - highend */
1830             {"(RV790",  CARD_AMD_RADEON_HD4800},
1831             {"(RV770",  CARD_AMD_RADEON_HD4800},
1832             {"(RV740",  CARD_AMD_RADEON_HD4700},    /* HD4700 - midend */
1833             {"(RV730",  CARD_AMD_RADEON_HD4600},    /* HD4600 - midend */
1834             {"(RV710",  CARD_AMD_RADEON_HD4350},    /* HD4500/HD4350 - lowend */
1835             /* R600/R700 integrated */
1836             {"RS880",   CARD_AMD_RADEON_HD3200},
1837             {"RS780",   CARD_AMD_RADEON_HD3200},
1838             /* R600 */
1839             {"(R680",   CARD_AMD_RADEON_HD2900},    /* HD2900/HD3800 - highend */
1840             {"(R600",   CARD_AMD_RADEON_HD2900},
1841             {"(RV670",  CARD_AMD_RADEON_HD2900},
1842             {"(RV635",  CARD_AMD_RADEON_HD2600},    /* HD2600/HD3600 - midend; HD3830 is China-only midend */
1843             {"(RV630",  CARD_AMD_RADEON_HD2600},
1844             {"(RV620",  CARD_AMD_RADEON_HD2350},    /* HD2300/HD2400/HD3400 - lowend */
1845             {"(RV610",  CARD_AMD_RADEON_HD2350},
1846         };
1847
1848         for (i = 0; i < sizeof(cards) / sizeof(*cards); ++i)
1849         {
1850             if (strstr(gl_renderer, cards[i].renderer))
1851                 return cards[i].id;
1852         }
1853     }
1854
1855     if (WINE_D3D8_CAPABLE(gl_info))
1856     {
1857         return CARD_AMD_RADEON_8500; /* Radeon 8500/9000/9100/9200/9300 */
1858     }
1859
1860     if (WINE_D3D7_CAPABLE(gl_info))
1861     {
1862         return CARD_AMD_RADEON_7200; /* Radeon 7000/7100/7200/7500 */
1863     }
1864
1865     return CARD_AMD_RAGE_128PRO;
1866 }
1867
1868 static enum wined3d_pci_device select_card_nvidia_mesa(const struct wined3d_gl_info *gl_info,
1869         const char *gl_renderer)
1870 {
1871     if (strstr(gl_renderer, "Gallium"))
1872     {
1873         unsigned int i;
1874
1875         static const struct
1876         {
1877             const char *renderer;
1878             enum wined3d_pci_device id;
1879         }
1880         cards[] =
1881         {
1882             {"NVC8",    CARD_NVIDIA_GEFORCE_GTX570},
1883             {"NVC4",    CARD_NVIDIA_GEFORCE_GTX460},
1884             {"NVC3",    CARD_NVIDIA_GEFORCE_GT440},
1885             {"NVC0",    CARD_NVIDIA_GEFORCE_GTX480},
1886             {"NVAF",    CARD_NVIDIA_GEFORCE_GT320M},
1887             {"NVAC",    CARD_NVIDIA_GEFORCE_8200},
1888             {"NVAA",    CARD_NVIDIA_GEFORCE_8200},
1889             {"NVA8",    CARD_NVIDIA_GEFORCE_210},
1890             {"NVA5",    CARD_NVIDIA_GEFORCE_GT220},
1891             {"NVA3",    CARD_NVIDIA_GEFORCE_GT240},
1892             {"NVA0",    CARD_NVIDIA_GEFORCE_GTX280},
1893             {"NV98",    CARD_NVIDIA_GEFORCE_9200},
1894             {"NV96",    CARD_NVIDIA_GEFORCE_9400GT},
1895             {"NV94",    CARD_NVIDIA_GEFORCE_9600GT},
1896             {"NV92",    CARD_NVIDIA_GEFORCE_9800GT},
1897             {"NV86",    CARD_NVIDIA_GEFORCE_8500GT},
1898             {"NV84",    CARD_NVIDIA_GEFORCE_8600GT},
1899             {"NV68",    CARD_NVIDIA_GEFORCE_6200},      /* 7050 */
1900             {"NV67",    CARD_NVIDIA_GEFORCE_6200},      /* 7000M */
1901             {"NV63",    CARD_NVIDIA_GEFORCE_6200},      /* 7100 */
1902             {"NV50",    CARD_NVIDIA_GEFORCE_8800GTX},
1903             {"NV4E",    CARD_NVIDIA_GEFORCE_6200},      /* 6100 Go / 6150 Go */
1904             {"NV4C",    CARD_NVIDIA_GEFORCE_6200},      /* 6150SE */
1905             {"NV4B",    CARD_NVIDIA_GEFORCE_7600},
1906             {"NV4A",    CARD_NVIDIA_GEFORCE_6200},
1907             {"NV49",    CARD_NVIDIA_GEFORCE_7800GT},    /* 7900 */
1908             {"NV47",    CARD_NVIDIA_GEFORCE_7800GT},
1909             {"NV46",    CARD_NVIDIA_GEFORCE_7400},
1910             {"NV45",    CARD_NVIDIA_GEFORCE_6800},
1911             {"NV44",    CARD_NVIDIA_GEFORCE_6200},
1912             {"NV43",    CARD_NVIDIA_GEFORCE_6600GT},
1913             {"NV42",    CARD_NVIDIA_GEFORCE_6800},
1914             {"NV41",    CARD_NVIDIA_GEFORCE_6800},
1915             {"NV40",    CARD_NVIDIA_GEFORCE_6800},
1916             {"NV38",    CARD_NVIDIA_GEFORCEFX_5800},    /* FX 5950 Ultra */
1917             {"NV36",    CARD_NVIDIA_GEFORCEFX_5800},    /* FX 5700/5750 */
1918             {"NV35",    CARD_NVIDIA_GEFORCEFX_5800},    /* FX 5900 */
1919             {"NV34",    CARD_NVIDIA_GEFORCEFX_5200},
1920             {"NV31",    CARD_NVIDIA_GEFORCEFX_5600},
1921             {"NV30",    CARD_NVIDIA_GEFORCEFX_5800},
1922             {"NV28",    CARD_NVIDIA_GEFORCE4_TI4200},
1923             {"NV25",    CARD_NVIDIA_GEFORCE4_TI4200},
1924             {"NV20",    CARD_NVIDIA_GEFORCE3},
1925             {"NV1F",    CARD_NVIDIA_GEFORCE4_MX},       /* GF4 MX IGP */
1926             {"NV1A",    CARD_NVIDIA_GEFORCE2},          /* GF2 IGP */
1927             {"NV18",    CARD_NVIDIA_GEFORCE4_MX},
1928             {"NV17",    CARD_NVIDIA_GEFORCE4_MX},
1929             {"NV16",    CARD_NVIDIA_GEFORCE2},
1930             {"NV15",    CARD_NVIDIA_GEFORCE2},
1931             {"NV11",    CARD_NVIDIA_GEFORCE2_MX},
1932             {"NV10",    CARD_NVIDIA_GEFORCE},
1933             {"NV05",    CARD_NVIDIA_RIVA_TNT2},
1934             {"NV04",    CARD_NVIDIA_RIVA_TNT},
1935             {"NV03",    CARD_NVIDIA_RIVA_128},
1936         };
1937
1938         for (i = 0; i < sizeof(cards) / sizeof(*cards); ++i)
1939         {
1940             if (strstr(gl_renderer, cards[i].renderer))
1941                 return cards[i].id;
1942         }
1943     }
1944
1945     FIXME_(d3d_caps)("Unknown renderer %s.\n", debugstr_a(gl_renderer));
1946     if (WINE_D3D9_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCEFX_5600;
1947     if (WINE_D3D8_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCE3;
1948     if (WINE_D3D7_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCE;
1949     if (WINE_D3D6_CAPABLE(gl_info)) return CARD_NVIDIA_RIVA_TNT;
1950     return CARD_NVIDIA_RIVA_128;
1951 }
1952
1953
1954 struct vendor_card_selection
1955 {
1956     enum wined3d_gl_vendor gl_vendor;
1957     enum wined3d_pci_vendor card_vendor;
1958     const char *description;        /* Description of the card selector i.e. Apple OS/X Intel */
1959     enum wined3d_pci_device (*select_card)(const struct wined3d_gl_info *gl_info, const char *gl_renderer);
1960 };
1961
1962 static const struct vendor_card_selection vendor_card_select_table[] =
1963 {
1964     {GL_VENDOR_NVIDIA, HW_VENDOR_NVIDIA,  "Nvidia binary driver",     select_card_nvidia_binary},
1965     {GL_VENDOR_APPLE,  HW_VENDOR_NVIDIA,  "Apple OSX NVidia binary driver",   select_card_nvidia_binary},
1966     {GL_VENDOR_APPLE,  HW_VENDOR_AMD,     "Apple OSX AMD/ATI binary driver",  select_card_amd_binary},
1967     {GL_VENDOR_APPLE,  HW_VENDOR_INTEL,   "Apple OSX Intel binary driver",    select_card_intel},
1968     {GL_VENDOR_FGLRX,  HW_VENDOR_AMD,     "AMD/ATI binary driver",    select_card_amd_binary},
1969     {GL_VENDOR_MESA,   HW_VENDOR_AMD,     "Mesa AMD/ATI driver",      select_card_amd_mesa},
1970     {GL_VENDOR_MESA,   HW_VENDOR_NVIDIA,  "Mesa Nouveau driver",      select_card_nvidia_mesa},
1971     {GL_VENDOR_MESA,   HW_VENDOR_INTEL,   "Mesa Intel driver",        select_card_intel},
1972     {GL_VENDOR_INTEL,  HW_VENDOR_INTEL,   "Mesa Intel driver",        select_card_intel}
1973 };
1974
1975
1976 static enum wined3d_pci_device wined3d_guess_card(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
1977         enum wined3d_gl_vendor *gl_vendor, enum wined3d_pci_vendor *card_vendor)
1978 {
1979     /* Above is a list of Nvidia and ATI GPUs. Both vendors have dozens of
1980      * different GPUs with roughly the same features. In most cases GPUs from a
1981      * certain family differ in clockspeeds, the amount of video memory and the
1982      * number of shader pipelines.
1983      *
1984      * A Direct3D device object contains the PCI id (vendor + device) of the
1985      * videocard which is used for rendering. Various applications use this
1986      * information to get a rough estimation of the features of the card and
1987      * some might use it for enabling 3d effects only on certain types of
1988      * videocards. In some cases games might even use it to work around bugs
1989      * which happen on certain videocards/driver combinations. The problem is
1990      * that OpenGL only exposes a rendering string containing the name of the
1991      * videocard and not the PCI id.
1992      *
1993      * Various games depend on the PCI id, so somehow we need to provide one.
1994      * A simple option is to parse the renderer string and translate this to
1995      * the right PCI id. This is a lot of work because there are more than 200
1996      * GPUs just for Nvidia. Various cards share the same renderer string, so
1997      * the amount of code might be 'small' but there are quite a number of
1998      * exceptions which would make this a pain to maintain. Another way would
1999      * be to query the PCI id from the operating system (assuming this is the
2000      * videocard which is used for rendering which is not always the case).
2001      * This would work but it is not very portable. Second it would not work
2002      * well in, let's say, a remote X situation in which the amount of 3d
2003      * features which can be used is limited.
2004      *
2005      * As said most games only use the PCI id to get an indication of the
2006      * capabilities of the card. It doesn't really matter if the given id is
2007      * the correct one if we return the id of a card with similar 3d features.
2008      *
2009      * The code below checks the OpenGL capabilities of a videocard and matches
2010      * that to a certain level of Direct3D functionality. Once a card passes
2011      * the Direct3D9 check, we know that the card (in case of Nvidia) is at
2012      * least a GeforceFX. To give a better estimate we do a basic check on the
2013      * renderer string but if that won't pass we return a default card. This
2014      * way is better than maintaining a full card database as even without a
2015      * full database we can return a card with similar features. Second the
2016      * size of the database can be made quite small because when you know what
2017      * type of 3d functionality a card has, you know to which GPU family the
2018      * GPU must belong. Because of this you only have to check a small part of
2019      * the renderer string to distinguishes between different models from that
2020      * family.
2021      *
2022      * The code also selects a default amount of video memory which we will
2023      * use for an estimation of the amount of free texture memory. In case of
2024      * real D3D the amount of texture memory includes video memory and system
2025      * memory (to be specific AGP memory or in case of PCIE TurboCache /
2026      * HyperMemory). We don't know how much system memory can be addressed by
2027      * the system but we can make a reasonable estimation about the amount of
2028      * video memory. If the value is slightly wrong it doesn't matter as we
2029      * didn't include AGP-like memory which makes the amount of addressable
2030      * memory higher and second OpenGL isn't that critical it moves to system
2031      * memory behind our backs if really needed. Note that the amount of video
2032      * memory can be overruled using a registry setting. */
2033
2034     int i;
2035
2036     for (i = 0; i < (sizeof(vendor_card_select_table) / sizeof(*vendor_card_select_table)); ++i)
2037     {
2038         if ((vendor_card_select_table[i].gl_vendor != *gl_vendor)
2039             || (vendor_card_select_table[i].card_vendor != *card_vendor))
2040                 continue;
2041         TRACE_(d3d_caps)("Applying card_selector \"%s\".\n", vendor_card_select_table[i].description);
2042         return vendor_card_select_table[i].select_card(gl_info, gl_renderer);
2043     }
2044
2045     FIXME_(d3d_caps)("No card selector available for GL vendor %d and card vendor %04x.\n",
2046                      *gl_vendor, *card_vendor);
2047
2048     /* Default to generic Nvidia hardware based on the supported OpenGL extensions. The choice
2049      * for Nvidia was because the hardware and drivers they make are of good quality. This makes
2050      * them a good generic choice. */
2051     *card_vendor = HW_VENDOR_NVIDIA;
2052     if (WINE_D3D9_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCEFX_5600;
2053     if (WINE_D3D8_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCE3;
2054     if (WINE_D3D7_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCE;
2055     if (WINE_D3D6_CAPABLE(gl_info)) return CARD_NVIDIA_RIVA_TNT;
2056     return CARD_NVIDIA_RIVA_128;
2057 }
2058
2059 static const struct fragment_pipeline *select_fragment_implementation(struct wined3d_adapter *adapter)
2060 {
2061     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
2062     int vs_selected_mode, ps_selected_mode;
2063
2064     select_shader_mode(gl_info, &ps_selected_mode, &vs_selected_mode);
2065     if ((ps_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_GLSL)
2066             && gl_info->supported[ARB_FRAGMENT_PROGRAM]) return &arbfp_fragment_pipeline;
2067     else if (ps_selected_mode == SHADER_ATI) return &atifs_fragment_pipeline;
2068     else if (gl_info->supported[NV_REGISTER_COMBINERS]
2069             && gl_info->supported[NV_TEXTURE_SHADER2]) return &nvts_fragment_pipeline;
2070     else if (gl_info->supported[NV_REGISTER_COMBINERS]) return &nvrc_fragment_pipeline;
2071     else return &ffp_fragment_pipeline;
2072 }
2073
2074 static const struct wined3d_shader_backend_ops *select_shader_backend(struct wined3d_adapter *adapter)
2075 {
2076     int vs_selected_mode, ps_selected_mode;
2077
2078     select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
2079     if (vs_selected_mode == SHADER_GLSL || ps_selected_mode == SHADER_GLSL) return &glsl_shader_backend;
2080     if (vs_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_ARB) return &arb_program_shader_backend;
2081     return &none_shader_backend;
2082 }
2083
2084 static const struct blit_shader *select_blit_implementation(struct wined3d_adapter *adapter)
2085 {
2086     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
2087     int vs_selected_mode, ps_selected_mode;
2088
2089     select_shader_mode(gl_info, &ps_selected_mode, &vs_selected_mode);
2090     if ((ps_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_GLSL)
2091             && gl_info->supported[ARB_FRAGMENT_PROGRAM]) return &arbfp_blit;
2092     else return &ffp_blit;
2093 }
2094
2095 static void load_gl_funcs(struct wined3d_gl_info *gl_info, DWORD gl_version)
2096 {
2097     DWORD ver;
2098
2099 #define USE_GL_FUNC(type, pfn, ext, replace) \
2100     if (gl_info->supported[ext]) gl_info->pfn = (type)pwglGetProcAddress(#pfn); \
2101     else if ((ver = ver_for_ext(ext)) && ver <= gl_version) gl_info->pfn = (type)pwglGetProcAddress(#replace); \
2102     else gl_info->pfn = NULL;
2103
2104     GL_EXT_FUNCS_GEN;
2105 #undef USE_GL_FUNC
2106
2107 #define USE_GL_FUNC(type, pfn, ext, replace) gl_info->pfn = (type)pwglGetProcAddress(#pfn);
2108     WGL_EXT_FUNCS_GEN;
2109 #undef USE_GL_FUNC
2110 }
2111
2112 /* Context activation is done by the caller. */
2113 static BOOL IWineD3DImpl_FillGLCaps(struct wined3d_adapter *adapter)
2114 {
2115     struct wined3d_driver_info *driver_info = &adapter->driver_info;
2116     struct wined3d_gl_info *gl_info = &adapter->gl_info;
2117     const char *GL_Extensions    = NULL;
2118     const char *WGL_Extensions   = NULL;
2119     const char *gl_vendor_str, *gl_renderer_str, *gl_version_str;
2120     struct fragment_caps fragment_caps;
2121     enum wined3d_gl_vendor gl_vendor;
2122     enum wined3d_pci_vendor card_vendor;
2123     enum wined3d_pci_device device;
2124     GLint       gl_max;
2125     GLfloat     gl_floatv[2];
2126     unsigned    i;
2127     HDC         hdc;
2128     DWORD gl_version;
2129     size_t len;
2130
2131     TRACE_(d3d_caps)("(%p)\n", gl_info);
2132
2133     ENTER_GL();
2134
2135     gl_renderer_str = (const char *)glGetString(GL_RENDERER);
2136     TRACE_(d3d_caps)("GL_RENDERER: %s.\n", debugstr_a(gl_renderer_str));
2137     if (!gl_renderer_str)
2138     {
2139         LEAVE_GL();
2140         ERR_(d3d_caps)("Received a NULL GL_RENDERER.\n");
2141         return FALSE;
2142     }
2143
2144     gl_vendor_str = (const char *)glGetString(GL_VENDOR);
2145     TRACE_(d3d_caps)("GL_VENDOR: %s.\n", debugstr_a(gl_vendor_str));
2146     if (!gl_vendor_str)
2147     {
2148         LEAVE_GL();
2149         ERR_(d3d_caps)("Received a NULL GL_VENDOR.\n");
2150         return FALSE;
2151     }
2152
2153     /* Parse the GL_VERSION field into major and minor information */
2154     gl_version_str = (const char *)glGetString(GL_VERSION);
2155     TRACE_(d3d_caps)("GL_VERSION: %s.\n", debugstr_a(gl_version_str));
2156     if (!gl_version_str)
2157     {
2158         LEAVE_GL();
2159         ERR_(d3d_caps)("Received a NULL GL_VERSION.\n");
2160         return FALSE;
2161     }
2162     gl_version = wined3d_parse_gl_version(gl_version_str);
2163
2164     /*
2165      * Initialize openGL extension related variables
2166      *  with Default values
2167      */
2168     memset(gl_info->supported, 0, sizeof(gl_info->supported));
2169     gl_info->limits.blends = 1;
2170     gl_info->limits.buffers = 1;
2171     gl_info->limits.textures = 1;
2172     gl_info->limits.fragment_samplers = 1;
2173     gl_info->limits.vertex_samplers = 0;
2174     gl_info->limits.combined_samplers = gl_info->limits.fragment_samplers + gl_info->limits.vertex_samplers;
2175     gl_info->limits.sampler_stages = 1;
2176     gl_info->limits.glsl_vs_float_constants = 0;
2177     gl_info->limits.glsl_ps_float_constants = 0;
2178     gl_info->limits.arb_vs_float_constants = 0;
2179     gl_info->limits.arb_vs_native_constants = 0;
2180     gl_info->limits.arb_vs_instructions = 0;
2181     gl_info->limits.arb_vs_temps = 0;
2182     gl_info->limits.arb_ps_float_constants = 0;
2183     gl_info->limits.arb_ps_local_constants = 0;
2184     gl_info->limits.arb_ps_instructions = 0;
2185     gl_info->limits.arb_ps_temps = 0;
2186
2187     /* Retrieve opengl defaults */
2188     glGetIntegerv(GL_MAX_CLIP_PLANES, &gl_max);
2189     gl_info->limits.clipplanes = min(WINED3DMAXUSERCLIPPLANES, gl_max);
2190     TRACE_(d3d_caps)("ClipPlanes support - num Planes=%d\n", gl_max);
2191
2192     glGetIntegerv(GL_MAX_LIGHTS, &gl_max);
2193     gl_info->limits.lights = gl_max;
2194     TRACE_(d3d_caps)("Lights support - max lights=%d\n", gl_max);
2195
2196     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_max);
2197     gl_info->limits.texture_size = gl_max;
2198     TRACE_(d3d_caps)("Maximum texture size support - max texture size=%d\n", gl_max);
2199
2200     glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, gl_floatv);
2201     gl_info->limits.pointsize_min = gl_floatv[0];
2202     gl_info->limits.pointsize_max = gl_floatv[1];
2203     TRACE_(d3d_caps)("Maximum point size support - max point size=%f\n", gl_floatv[1]);
2204
2205     /* Parse the gl supported features, in theory enabling parts of our code appropriately. */
2206     GL_Extensions = (const char *)glGetString(GL_EXTENSIONS);
2207     if (!GL_Extensions)
2208     {
2209         LEAVE_GL();
2210         ERR_(d3d_caps)("Received a NULL GL_EXTENSIONS.\n");
2211         return FALSE;
2212     }
2213
2214     LEAVE_GL();
2215
2216     TRACE_(d3d_caps)("GL_Extensions reported:\n");
2217
2218     gl_info->supported[WINED3D_GL_EXT_NONE] = TRUE;
2219
2220     while (*GL_Extensions)
2221     {
2222         const char *start;
2223
2224         while (isspace(*GL_Extensions)) ++GL_Extensions;
2225         start = GL_Extensions;
2226         while (!isspace(*GL_Extensions) && *GL_Extensions) ++GL_Extensions;
2227
2228         len = GL_Extensions - start;
2229         if (!len) continue;
2230
2231         TRACE_(d3d_caps)("- %s\n", debugstr_an(start, len));
2232
2233         for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i)
2234         {
2235             if (len == strlen(EXTENSION_MAP[i].extension_string)
2236                     && !memcmp(start, EXTENSION_MAP[i].extension_string, len))
2237             {
2238                 TRACE_(d3d_caps)(" FOUND: %s support.\n", EXTENSION_MAP[i].extension_string);
2239                 gl_info->supported[EXTENSION_MAP[i].extension] = TRUE;
2240                 break;
2241             }
2242         }
2243     }
2244
2245     /* Now work out what GL support this card really has */
2246     load_gl_funcs( gl_info, gl_version );
2247
2248     ENTER_GL();
2249
2250     /* Now mark all the extensions supported which are included in the opengl core version. Do this *after*
2251      * loading the functions, otherwise the code above will load the extension entry points instead of the
2252      * core functions, which may not work. */
2253     for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i)
2254     {
2255         if (!gl_info->supported[EXTENSION_MAP[i].extension]
2256                 && EXTENSION_MAP[i].version <= gl_version && EXTENSION_MAP[i].version)
2257         {
2258             TRACE_(d3d_caps)(" GL CORE: %s support.\n", EXTENSION_MAP[i].extension_string);
2259             gl_info->supported[EXTENSION_MAP[i].extension] = TRUE;
2260         }
2261     }
2262
2263     if (gl_version >= MAKEDWORD_VERSION(2, 0)) gl_info->supported[WINED3D_GL_VERSION_2_0] = TRUE;
2264
2265     if (gl_info->supported[APPLE_FENCE])
2266     {
2267         /* GL_NV_fence and GL_APPLE_fence provide the same functionality basically.
2268          * The apple extension interacts with some other apple exts. Disable the NV
2269          * extension if the apple one is support to prevent confusion in other parts
2270          * of the code. */
2271         gl_info->supported[NV_FENCE] = FALSE;
2272     }
2273     if (gl_info->supported[APPLE_FLOAT_PIXELS])
2274     {
2275         /* GL_APPLE_float_pixels == GL_ARB_texture_float + GL_ARB_half_float_pixel
2276          *
2277          * The enums are the same:
2278          * GL_RGBA16F_ARB     = GL_RGBA_FLOAT16_APPLE = 0x881A
2279          * GL_RGB16F_ARB      = GL_RGB_FLOAT16_APPLE  = 0x881B
2280          * GL_RGBA32F_ARB     = GL_RGBA_FLOAT32_APPLE = 0x8814
2281          * GL_RGB32F_ARB      = GL_RGB_FLOAT32_APPLE  = 0x8815
2282          * GL_HALF_FLOAT_ARB  = GL_HALF_APPLE         = 0x140B
2283          */
2284         if (!gl_info->supported[ARB_TEXTURE_FLOAT])
2285         {
2286             TRACE_(d3d_caps)(" IMPLIED: GL_ARB_texture_float support(from GL_APPLE_float_pixels.\n");
2287             gl_info->supported[ARB_TEXTURE_FLOAT] = TRUE;
2288         }
2289         if (!gl_info->supported[ARB_HALF_FLOAT_PIXEL])
2290         {
2291             TRACE_(d3d_caps)(" IMPLIED: GL_ARB_half_float_pixel support(from GL_APPLE_float_pixels.\n");
2292             gl_info->supported[ARB_HALF_FLOAT_PIXEL] = TRUE;
2293         }
2294     }
2295     if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
2296     {
2297         /* GL_ARB_map_buffer_range and GL_APPLE_flush_buffer_range provide the same
2298          * functionality. Prefer the ARB extension */
2299         gl_info->supported[APPLE_FLUSH_BUFFER_RANGE] = FALSE;
2300     }
2301     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2302     {
2303         TRACE_(d3d_caps)(" IMPLIED: NVIDIA (NV) Texture Gen Reflection support.\n");
2304         gl_info->supported[NV_TEXGEN_REFLECTION] = TRUE;
2305     }
2306     if (!gl_info->supported[ARB_DEPTH_CLAMP] && gl_info->supported[NV_DEPTH_CLAMP])
2307     {
2308         TRACE_(d3d_caps)(" IMPLIED: ARB_depth_clamp support (by NV_depth_clamp).\n");
2309         gl_info->supported[ARB_DEPTH_CLAMP] = TRUE;
2310     }
2311     if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && gl_info->supported[EXT_VERTEX_ARRAY_BGRA])
2312     {
2313         TRACE_(d3d_caps)(" IMPLIED: ARB_vertex_array_bgra support (by EXT_vertex_array_bgra).\n");
2314         gl_info->supported[ARB_VERTEX_ARRAY_BGRA] = TRUE;
2315     }
2316     if (!gl_info->supported[ARB_TEXTURE_COMPRESSION_RGTC] && gl_info->supported[EXT_TEXTURE_COMPRESSION_RGTC])
2317     {
2318         TRACE_(d3d_caps)(" IMPLIED: ARB_texture_compression_rgtc support (by EXT_texture_compression_rgtc).\n");
2319         gl_info->supported[ARB_TEXTURE_COMPRESSION_RGTC] = TRUE;
2320     }
2321     if (gl_info->supported[NV_TEXTURE_SHADER2])
2322     {
2323         if (gl_info->supported[NV_REGISTER_COMBINERS])
2324         {
2325             /* Also disable ATI_FRAGMENT_SHADER if register combiners and texture_shader2
2326              * are supported. The nv extensions provide the same functionality as the
2327              * ATI one, and a bit more(signed pixelformats). */
2328             gl_info->supported[ATI_FRAGMENT_SHADER] = FALSE;
2329         }
2330     }
2331
2332     if (gl_info->supported[NV_REGISTER_COMBINERS])
2333     {
2334         glGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &gl_max);
2335         gl_info->limits.general_combiners = gl_max;
2336         TRACE_(d3d_caps)("Max general combiners: %d.\n", gl_max);
2337     }
2338     if (gl_info->supported[ARB_DRAW_BUFFERS])
2339     {
2340         glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &gl_max);
2341         gl_info->limits.buffers = gl_max;
2342         TRACE_(d3d_caps)("Max draw buffers: %u.\n", gl_max);
2343     }
2344     if (gl_info->supported[ARB_MULTITEXTURE])
2345     {
2346         glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &gl_max);
2347         gl_info->limits.textures = min(MAX_TEXTURES, gl_max);
2348         TRACE_(d3d_caps)("Max textures: %d.\n", gl_info->limits.textures);
2349
2350         if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
2351         {
2352             GLint tmp;
2353             glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &tmp);
2354             gl_info->limits.fragment_samplers = min(MAX_FRAGMENT_SAMPLERS, tmp);
2355         }
2356         else
2357         {
2358             gl_info->limits.fragment_samplers = max(gl_info->limits.fragment_samplers, gl_max);
2359         }
2360         TRACE_(d3d_caps)("Max fragment samplers: %d.\n", gl_info->limits.fragment_samplers);
2361
2362         if (gl_info->supported[ARB_VERTEX_SHADER])
2363         {
2364             GLint tmp;
2365             glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, &tmp);
2366             gl_info->limits.vertex_samplers = tmp;
2367             glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, &tmp);
2368             gl_info->limits.combined_samplers = tmp;
2369
2370             /* Loading GLSL sampler uniforms is much simpler if we can assume that the sampler setup
2371              * is known at shader link time. In a vertex shader + pixel shader combination this isn't
2372              * an issue because then the sampler setup only depends on the two shaders. If a pixel
2373              * shader is used with fixed function vertex processing we're fine too because fixed function
2374              * vertex processing doesn't use any samplers. If fixed function fragment processing is
2375              * used we have to make sure that all vertex sampler setups are valid together with all
2376              * possible fixed function fragment processing setups. This is true if vsamplers + MAX_TEXTURES
2377              * <= max_samplers. This is true on all d3d9 cards that support vtf(gf 6 and gf7 cards).
2378              * dx9 radeon cards do not support vertex texture fetch. DX10 cards have 128 samplers, and
2379              * dx9 is limited to 8 fixed function texture stages and 4 vertex samplers. DX10 does not have
2380              * a fixed function pipeline anymore.
2381              *
2382              * So this is just a check to check that our assumption holds true. If not, write a warning
2383              * and reduce the number of vertex samplers or probably disable vertex texture fetch. */
2384             if (gl_info->limits.vertex_samplers && gl_info->limits.combined_samplers < 12
2385                     && MAX_TEXTURES + gl_info->limits.vertex_samplers > gl_info->limits.combined_samplers)
2386             {
2387                 FIXME("OpenGL implementation supports %u vertex samplers and %u total samplers.\n",
2388                         gl_info->limits.vertex_samplers, gl_info->limits.combined_samplers);
2389                 FIXME("Expected vertex samplers + MAX_TEXTURES(=8) > combined_samplers.\n");
2390                 if (gl_info->limits.combined_samplers > MAX_TEXTURES)
2391                     gl_info->limits.vertex_samplers = gl_info->limits.combined_samplers - MAX_TEXTURES;
2392                 else
2393                     gl_info->limits.vertex_samplers = 0;
2394             }
2395         }
2396         else
2397         {
2398             gl_info->limits.combined_samplers = gl_info->limits.fragment_samplers;
2399         }
2400         TRACE_(d3d_caps)("Max vertex samplers: %u.\n", gl_info->limits.vertex_samplers);
2401         TRACE_(d3d_caps)("Max combined samplers: %u.\n", gl_info->limits.combined_samplers);
2402     }
2403     if (gl_info->supported[ARB_VERTEX_BLEND])
2404     {
2405         glGetIntegerv(GL_MAX_VERTEX_UNITS_ARB, &gl_max);
2406         gl_info->limits.blends = gl_max;
2407         TRACE_(d3d_caps)("Max blends: %u.\n", gl_info->limits.blends);
2408     }
2409     if (gl_info->supported[EXT_TEXTURE3D])
2410     {
2411         glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE_EXT, &gl_max);
2412         gl_info->limits.texture3d_size = gl_max;
2413         TRACE_(d3d_caps)("Max texture3D size: %d.\n", gl_info->limits.texture3d_size);
2414     }
2415     if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
2416     {
2417         glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max);
2418         gl_info->limits.anisotropy = gl_max;
2419         TRACE_(d3d_caps)("Max anisotropy: %d.\n", gl_info->limits.anisotropy);
2420     }
2421     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
2422     {
2423         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &gl_max));
2424         gl_info->limits.arb_ps_float_constants = gl_max;
2425         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM float constants: %d.\n", gl_info->limits.arb_ps_float_constants);
2426         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB, &gl_max));
2427         gl_info->limits.arb_ps_native_constants = gl_max;
2428         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native float constants: %d.\n",
2429                 gl_info->limits.arb_ps_native_constants);
2430         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, &gl_max));
2431         gl_info->limits.arb_ps_temps = gl_max;
2432         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native temporaries: %d.\n", gl_info->limits.arb_ps_temps);
2433         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, &gl_max));
2434         gl_info->limits.arb_ps_instructions = gl_max;
2435         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native instructions: %d.\n", gl_info->limits.arb_ps_instructions);
2436         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &gl_max));
2437         gl_info->limits.arb_ps_local_constants = gl_max;
2438         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM local parameters: %d.\n", gl_info->limits.arb_ps_instructions);
2439     }
2440     if (gl_info->supported[ARB_VERTEX_PROGRAM])
2441     {
2442         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &gl_max));
2443         gl_info->limits.arb_vs_float_constants = gl_max;
2444         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM float constants: %d.\n", gl_info->limits.arb_vs_float_constants);
2445         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB, &gl_max));
2446         gl_info->limits.arb_vs_native_constants = gl_max;
2447         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native float constants: %d.\n",
2448                 gl_info->limits.arb_vs_native_constants);
2449         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, &gl_max));
2450         gl_info->limits.arb_vs_temps = gl_max;
2451         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native temporaries: %d.\n", gl_info->limits.arb_vs_temps);
2452         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, &gl_max));
2453         gl_info->limits.arb_vs_instructions = gl_max;
2454         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native instructions: %d.\n", gl_info->limits.arb_vs_instructions);
2455
2456         if (test_arb_vs_offset_limit(gl_info)) gl_info->quirks |= WINED3D_QUIRK_ARB_VS_OFFSET_LIMIT;
2457     }
2458     if (gl_info->supported[ARB_VERTEX_SHADER])
2459     {
2460         glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, &gl_max);
2461         gl_info->limits.glsl_vs_float_constants = gl_max / 4;
2462         TRACE_(d3d_caps)("Max ARB_VERTEX_SHADER float constants: %u.\n", gl_info->limits.glsl_vs_float_constants);
2463     }
2464     if (gl_info->supported[ARB_FRAGMENT_SHADER])
2465     {
2466         glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, &gl_max);
2467         gl_info->limits.glsl_ps_float_constants = gl_max / 4;
2468         TRACE_(d3d_caps)("Max ARB_FRAGMENT_SHADER float constants: %u.\n", gl_info->limits.glsl_ps_float_constants);
2469         glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, &gl_max);
2470         gl_info->limits.glsl_varyings = gl_max;
2471         TRACE_(d3d_caps)("Max GLSL varyings: %u (%u 4 component varyings).\n", gl_max, gl_max / 4);
2472     }
2473     if (gl_info->supported[ARB_SHADING_LANGUAGE_100])
2474     {
2475         const char *str = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION_ARB);
2476         unsigned int major, minor;
2477
2478         TRACE_(d3d_caps)("GLSL version string: %s.\n", debugstr_a(str));
2479
2480         /* The format of the GLSL version string is "major.minor[.release] [vendor info]". */
2481         sscanf(str, "%u.%u", &major, &minor);
2482         gl_info->glsl_version = MAKEDWORD_VERSION(major, minor);
2483     }
2484     if (gl_info->supported[NV_LIGHT_MAX_EXPONENT])
2485     {
2486         glGetFloatv(GL_MAX_SHININESS_NV, &gl_info->limits.shininess);
2487     }
2488     else
2489     {
2490         gl_info->limits.shininess = 128.0f;
2491     }
2492     if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
2493     {
2494         /* If we have full NP2 texture support, disable
2495          * GL_ARB_texture_rectangle because we will never use it.
2496          * This saves a few redundant glDisable calls. */
2497         gl_info->supported[ARB_TEXTURE_RECTANGLE] = FALSE;
2498     }
2499     if (gl_info->supported[ATI_FRAGMENT_SHADER])
2500     {
2501         /* Disable NV_register_combiners and fragment shader if this is supported.
2502          * generally the NV extensions are preferred over the ATI ones, and this
2503          * extension is disabled if register_combiners and texture_shader2 are both
2504          * supported. So we reach this place only if we have incomplete NV dxlevel 8
2505          * fragment processing support. */
2506         gl_info->supported[NV_REGISTER_COMBINERS] = FALSE;
2507         gl_info->supported[NV_REGISTER_COMBINERS2] = FALSE;
2508         gl_info->supported[NV_TEXTURE_SHADER] = FALSE;
2509         gl_info->supported[NV_TEXTURE_SHADER2] = FALSE;
2510     }
2511     if (gl_info->supported[NV_HALF_FLOAT])
2512     {
2513         /* GL_ARB_half_float_vertex is a subset of GL_NV_half_float. */
2514         gl_info->supported[ARB_HALF_FLOAT_VERTEX] = TRUE;
2515     }
2516     if (gl_info->supported[ARB_POINT_SPRITE])
2517     {
2518         gl_info->limits.point_sprite_units = gl_info->limits.textures;
2519     }
2520     else
2521     {
2522         gl_info->limits.point_sprite_units = 0;
2523     }
2524     checkGLcall("extension detection");
2525
2526     LEAVE_GL();
2527
2528     adapter->fragment_pipe = select_fragment_implementation(adapter);
2529     adapter->shader_backend = select_shader_backend(adapter);
2530     adapter->blitter = select_blit_implementation(adapter);
2531
2532     adapter->fragment_pipe->get_caps(gl_info, &fragment_caps);
2533     gl_info->limits.texture_stages = fragment_caps.MaxTextureBlendStages;
2534     TRACE_(d3d_caps)("Max texture stages: %u.\n", gl_info->limits.texture_stages);
2535
2536     /* In some cases the number of texture stages can be larger than the number
2537      * of samplers. The GF4 for example can use only 2 samplers (no fragment
2538      * shaders), but 8 texture stages (register combiners). */
2539     gl_info->limits.sampler_stages = max(gl_info->limits.fragment_samplers, gl_info->limits.texture_stages);
2540
2541     if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT])
2542     {
2543         gl_info->fbo_ops.glIsRenderbuffer = gl_info->glIsRenderbuffer;
2544         gl_info->fbo_ops.glBindRenderbuffer = gl_info->glBindRenderbuffer;
2545         gl_info->fbo_ops.glDeleteRenderbuffers = gl_info->glDeleteRenderbuffers;
2546         gl_info->fbo_ops.glGenRenderbuffers = gl_info->glGenRenderbuffers;
2547         gl_info->fbo_ops.glRenderbufferStorage = gl_info->glRenderbufferStorage;
2548         gl_info->fbo_ops.glRenderbufferStorageMultisample = gl_info->glRenderbufferStorageMultisample;
2549         gl_info->fbo_ops.glGetRenderbufferParameteriv = gl_info->glGetRenderbufferParameteriv;
2550         gl_info->fbo_ops.glIsFramebuffer = gl_info->glIsFramebuffer;
2551         gl_info->fbo_ops.glBindFramebuffer = gl_info->glBindFramebuffer;
2552         gl_info->fbo_ops.glDeleteFramebuffers = gl_info->glDeleteFramebuffers;
2553         gl_info->fbo_ops.glGenFramebuffers = gl_info->glGenFramebuffers;
2554         gl_info->fbo_ops.glCheckFramebufferStatus = gl_info->glCheckFramebufferStatus;
2555         gl_info->fbo_ops.glFramebufferTexture1D = gl_info->glFramebufferTexture1D;
2556         gl_info->fbo_ops.glFramebufferTexture2D = gl_info->glFramebufferTexture2D;
2557         gl_info->fbo_ops.glFramebufferTexture3D = gl_info->glFramebufferTexture3D;
2558         gl_info->fbo_ops.glFramebufferRenderbuffer = gl_info->glFramebufferRenderbuffer;
2559         gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv = gl_info->glGetFramebufferAttachmentParameteriv;
2560         gl_info->fbo_ops.glBlitFramebuffer = gl_info->glBlitFramebuffer;
2561         gl_info->fbo_ops.glGenerateMipmap = gl_info->glGenerateMipmap;
2562     }
2563     else
2564     {
2565         if (gl_info->supported[EXT_FRAMEBUFFER_OBJECT])
2566         {
2567             gl_info->fbo_ops.glIsRenderbuffer = gl_info->glIsRenderbufferEXT;
2568             gl_info->fbo_ops.glBindRenderbuffer = gl_info->glBindRenderbufferEXT;
2569             gl_info->fbo_ops.glDeleteRenderbuffers = gl_info->glDeleteRenderbuffersEXT;
2570             gl_info->fbo_ops.glGenRenderbuffers = gl_info->glGenRenderbuffersEXT;
2571             gl_info->fbo_ops.glRenderbufferStorage = gl_info->glRenderbufferStorageEXT;
2572             gl_info->fbo_ops.glGetRenderbufferParameteriv = gl_info->glGetRenderbufferParameterivEXT;
2573             gl_info->fbo_ops.glIsFramebuffer = gl_info->glIsFramebufferEXT;
2574             gl_info->fbo_ops.glBindFramebuffer = gl_info->glBindFramebufferEXT;
2575             gl_info->fbo_ops.glDeleteFramebuffers = gl_info->glDeleteFramebuffersEXT;
2576             gl_info->fbo_ops.glGenFramebuffers = gl_info->glGenFramebuffersEXT;
2577             gl_info->fbo_ops.glCheckFramebufferStatus = gl_info->glCheckFramebufferStatusEXT;
2578             gl_info->fbo_ops.glFramebufferTexture1D = gl_info->glFramebufferTexture1DEXT;
2579             gl_info->fbo_ops.glFramebufferTexture2D = gl_info->glFramebufferTexture2DEXT;
2580             gl_info->fbo_ops.glFramebufferTexture3D = gl_info->glFramebufferTexture3DEXT;
2581             gl_info->fbo_ops.glFramebufferRenderbuffer = gl_info->glFramebufferRenderbufferEXT;
2582             gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv = gl_info->glGetFramebufferAttachmentParameterivEXT;
2583             gl_info->fbo_ops.glGenerateMipmap = gl_info->glGenerateMipmapEXT;
2584         }
2585         else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2586         {
2587             WARN_(d3d_caps)("Framebuffer objects not supported, falling back to backbuffer offscreen rendering mode.\n");
2588             wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
2589         }
2590         if (gl_info->supported[EXT_FRAMEBUFFER_BLIT])
2591         {
2592             gl_info->fbo_ops.glBlitFramebuffer = gl_info->glBlitFramebufferEXT;
2593         }
2594         if (gl_info->supported[EXT_FRAMEBUFFER_MULTISAMPLE])
2595         {
2596             gl_info->fbo_ops.glRenderbufferStorageMultisample = gl_info->glRenderbufferStorageMultisampleEXT;
2597         }
2598     }
2599
2600     /* MRTs are currently only supported when FBOs are used. */
2601     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2602     {
2603         gl_info->limits.buffers = 1;
2604     }
2605
2606     gl_vendor = wined3d_guess_gl_vendor(gl_info, gl_vendor_str, gl_renderer_str);
2607     card_vendor = wined3d_guess_card_vendor(gl_vendor_str, gl_renderer_str);
2608     TRACE_(d3d_caps)("found GL_VENDOR (%s)->(0x%04x/0x%04x)\n", debugstr_a(gl_vendor_str), gl_vendor, card_vendor);
2609
2610     device = wined3d_guess_card(gl_info, gl_renderer_str, &gl_vendor, &card_vendor);
2611     TRACE_(d3d_caps)("FOUND (fake) card: 0x%x (vendor id), 0x%x (device id)\n", card_vendor, device);
2612
2613     gl_info->wrap_lookup[WINED3DTADDRESS_WRAP - WINED3DTADDRESS_WRAP] = GL_REPEAT;
2614     gl_info->wrap_lookup[WINED3DTADDRESS_MIRROR - WINED3DTADDRESS_WRAP] =
2615             gl_info->supported[ARB_TEXTURE_MIRRORED_REPEAT] ? GL_MIRRORED_REPEAT_ARB : GL_REPEAT;
2616     gl_info->wrap_lookup[WINED3DTADDRESS_CLAMP - WINED3DTADDRESS_WRAP] = GL_CLAMP_TO_EDGE;
2617     gl_info->wrap_lookup[WINED3DTADDRESS_BORDER - WINED3DTADDRESS_WRAP] =
2618             gl_info->supported[ARB_TEXTURE_BORDER_CLAMP] ? GL_CLAMP_TO_BORDER_ARB : GL_REPEAT;
2619     gl_info->wrap_lookup[WINED3DTADDRESS_MIRRORONCE - WINED3DTADDRESS_WRAP] =
2620             gl_info->supported[ATI_TEXTURE_MIRROR_ONCE] ? GL_MIRROR_CLAMP_TO_EDGE_ATI : GL_REPEAT;
2621
2622     /* Make sure there's an active HDC else the WGL extensions will fail */
2623     hdc = pwglGetCurrentDC();
2624     if (hdc) {
2625         /* Not all GL drivers might offer WGL extensions e.g. VirtualBox */
2626         if(GL_EXTCALL(wglGetExtensionsStringARB))
2627             WGL_Extensions = GL_EXTCALL(wglGetExtensionsStringARB(hdc));
2628
2629         if (!WGL_Extensions)
2630         {
2631             ERR("   WGL_Extensions returns NULL\n");
2632         }
2633         else
2634         {
2635             TRACE_(d3d_caps)("WGL_Extensions reported:\n");
2636             while (*WGL_Extensions)
2637             {
2638                 const char *Start;
2639                 char ThisExtn[256];
2640
2641                 while (isspace(*WGL_Extensions)) WGL_Extensions++;
2642                 Start = WGL_Extensions;
2643                 while (!isspace(*WGL_Extensions) && *WGL_Extensions) ++WGL_Extensions;
2644
2645                 len = WGL_Extensions - Start;
2646                 if (!len || len >= sizeof(ThisExtn))
2647                     continue;
2648
2649                 memcpy(ThisExtn, Start, len);
2650                 ThisExtn[len] = '\0';
2651                 TRACE_(d3d_caps)("- %s\n", debugstr_a(ThisExtn));
2652
2653                 if (!strcmp(ThisExtn, "WGL_ARB_pixel_format")) {
2654                     gl_info->supported[WGL_ARB_PIXEL_FORMAT] = TRUE;
2655                     TRACE_(d3d_caps)("FOUND: WGL_ARB_pixel_format support\n");
2656                 }
2657                 if (!strcmp(ThisExtn, "WGL_EXT_swap_control")) {
2658                     gl_info->supported[WGL_EXT_SWAP_CONTROL] = TRUE;
2659                     TRACE_(d3d_caps)("FOUND: WGL_EXT_swap_control support\n");
2660                 }
2661                 if (!strcmp(ThisExtn, "WGL_WINE_pixel_format_passthrough")) {
2662                     gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH] = TRUE;
2663                     TRACE_(d3d_caps)("FOUND: WGL_WINE_pixel_format_passthrough support\n");
2664                 }
2665             }
2666         }
2667     }
2668
2669     fixup_extensions(gl_info, gl_renderer_str, gl_vendor, card_vendor, device);
2670     init_driver_info(driver_info, card_vendor, device);
2671     add_gl_compat_wrappers(gl_info);
2672
2673     return TRUE;
2674 }
2675
2676 UINT CDECL wined3d_get_adapter_count(const struct wined3d *wined3d)
2677 {
2678     TRACE_(d3d_caps)("wined3d %p, reporting %u adapters.\n",
2679             wined3d, wined3d->adapter_count);
2680
2681     return wined3d->adapter_count;
2682 }
2683
2684 HRESULT CDECL wined3d_register_software_device(struct wined3d *wined3d, void *init_function)
2685 {
2686     FIXME("wined3d %p, init_function %p stub!\n", wined3d, init_function);
2687
2688     return WINED3D_OK;
2689 }
2690
2691 HMONITOR CDECL wined3d_get_adapter_monitor(const struct wined3d *wined3d, UINT adapter_idx)
2692 {
2693     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u.\n", wined3d, adapter_idx);
2694
2695     if (adapter_idx >= wined3d->adapter_count)
2696         return NULL;
2697
2698     return MonitorFromPoint(wined3d->adapters[adapter_idx].monitorPoint, MONITOR_DEFAULTTOPRIMARY);
2699 }
2700
2701 /* FIXME: GetAdapterModeCount and EnumAdapterModes currently only returns modes
2702      of the same bpp but different resolutions                                  */
2703
2704 /* Note: dx9 supplies a format. Calls from d3d8 supply WINED3DFMT_UNKNOWN */
2705 UINT CDECL wined3d_get_adapter_mode_count(const struct wined3d *wined3d, UINT adapter_idx,
2706         enum wined3d_format_id format_id)
2707 {
2708     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u, format %s.\n", wined3d, adapter_idx, debug_d3dformat(format_id));
2709
2710     if (adapter_idx >= wined3d->adapter_count)
2711         return 0;
2712
2713     /* TODO: Store modes per adapter and read it from the adapter structure */
2714     if (!adapter_idx)
2715     {
2716         const struct wined3d_format *format = wined3d_get_format(&wined3d->adapters[adapter_idx].gl_info, format_id);
2717         UINT format_bits = format->byte_count * CHAR_BIT;
2718         unsigned int i = 0;
2719         unsigned int j = 0;
2720         DEVMODEW mode;
2721
2722         memset(&mode, 0, sizeof(mode));
2723         mode.dmSize = sizeof(mode);
2724
2725         while (EnumDisplaySettingsExW(NULL, j, &mode, 0))
2726         {
2727             ++j;
2728
2729             if (format_id == WINED3DFMT_UNKNOWN)
2730             {
2731                 /* This is for D3D8, do not enumerate P8 here */
2732                 if (mode.dmBitsPerPel == 32 || mode.dmBitsPerPel == 16) ++i;
2733             }
2734             else if (mode.dmBitsPerPel == format_bits)
2735             {
2736                 ++i;
2737             }
2738         }
2739
2740         TRACE_(d3d_caps)("Returning %u matching modes (out of %u total) for adapter %u.\n", i, j, adapter_idx);
2741
2742         return i;
2743     }
2744     else
2745     {
2746         FIXME_(d3d_caps)("Adapter not primary display.\n");
2747     }
2748
2749     return 0;
2750 }
2751
2752 /* Note: dx9 supplies a format. Calls from d3d8 supply WINED3DFMT_UNKNOWN */
2753 HRESULT CDECL wined3d_enum_adapter_modes(const struct wined3d *wined3d, UINT adapter_idx,
2754         enum wined3d_format_id format_id, UINT mode_idx, WINED3DDISPLAYMODE *mode)
2755 {
2756     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u, format %s, mode_idx %u, mode %p.\n",
2757             wined3d, adapter_idx, debug_d3dformat(format_id), mode_idx, mode);
2758
2759     /* Validate the parameters as much as possible */
2760     if (!mode || adapter_idx >= wined3d->adapter_count
2761             || mode_idx >= wined3d_get_adapter_mode_count(wined3d, adapter_idx, format_id))
2762     {
2763         return WINED3DERR_INVALIDCALL;
2764     }
2765
2766     /* TODO: Store modes per adapter and read it from the adapter structure */
2767     if (!adapter_idx)
2768     {
2769         const struct wined3d_format *format = wined3d_get_format(&wined3d->adapters[adapter_idx].gl_info, format_id);
2770         UINT format_bits = format->byte_count * CHAR_BIT;
2771         DEVMODEW DevModeW;
2772         int ModeIdx = 0;
2773         UINT i = 0;
2774         int j = 0;
2775
2776         ZeroMemory(&DevModeW, sizeof(DevModeW));
2777         DevModeW.dmSize = sizeof(DevModeW);
2778
2779         /* If we are filtering to a specific format (D3D9), then need to skip
2780            all unrelated modes, but if mode is irrelevant (D3D8), then we can
2781            just count through the ones with valid bit depths */
2782         while (i <= mode_idx && EnumDisplaySettingsExW(NULL, j++, &DevModeW, 0))
2783         {
2784             if (format_id == WINED3DFMT_UNKNOWN)
2785             {
2786                 /* This is for D3D8, do not enumerate P8 here */
2787                 if (DevModeW.dmBitsPerPel == 32 || DevModeW.dmBitsPerPel == 16) ++i;
2788             }
2789             else if (DevModeW.dmBitsPerPel == format_bits)
2790             {
2791                 ++i;
2792             }
2793         }
2794
2795         if (!i)
2796         {
2797             TRACE_(d3d_caps)("No modes found for format (%x - %s)\n", format_id, debug_d3dformat(format_id));
2798             return WINED3DERR_INVALIDCALL;
2799         }
2800         ModeIdx = j - 1;
2801
2802         /* Now get the display mode via the calculated index */
2803         if (EnumDisplaySettingsExW(NULL, ModeIdx, &DevModeW, 0))
2804         {
2805             mode->Width = DevModeW.dmPelsWidth;
2806             mode->Height = DevModeW.dmPelsHeight;
2807             mode->RefreshRate = DEFAULT_REFRESH_RATE;
2808             if (DevModeW.dmFields & DM_DISPLAYFREQUENCY)
2809                 mode->RefreshRate = DevModeW.dmDisplayFrequency;
2810
2811             if (format_id == WINED3DFMT_UNKNOWN)
2812                 mode->Format = pixelformat_for_depth(DevModeW.dmBitsPerPel);
2813             else
2814                 mode->Format = format_id;
2815         }
2816         else
2817         {
2818             TRACE_(d3d_caps)("Requested mode %u out of range.\n", mode_idx);
2819             return WINED3DERR_INVALIDCALL;
2820         }
2821
2822         TRACE_(d3d_caps)("W %d H %d rr %d fmt (%x - %s) bpp %u\n",
2823                 mode->Width, mode->Height, mode->RefreshRate, mode->Format,
2824                 debug_d3dformat(mode->Format), DevModeW.dmBitsPerPel);
2825     }
2826     else
2827     {
2828         FIXME_(d3d_caps)("Adapter not primary display\n");
2829     }
2830
2831     return WINED3D_OK;
2832 }
2833
2834 HRESULT CDECL wined3d_get_adapter_display_mode(const struct wined3d *wined3d, UINT adapter_idx,
2835         WINED3DDISPLAYMODE *mode)
2836 {
2837     TRACE("wined3d %p, adapter_idx %u, display_mode %p.\n", wined3d, adapter_idx, mode);
2838
2839     if (!mode || adapter_idx >= wined3d->adapter_count)
2840         return WINED3DERR_INVALIDCALL;
2841
2842     if (!adapter_idx)
2843     {
2844         DEVMODEW DevModeW;
2845         unsigned int bpp;
2846
2847         ZeroMemory(&DevModeW, sizeof(DevModeW));
2848         DevModeW.dmSize = sizeof(DevModeW);
2849
2850         EnumDisplaySettingsExW(NULL, ENUM_CURRENT_SETTINGS, &DevModeW, 0);
2851         mode->Width = DevModeW.dmPelsWidth;
2852         mode->Height = DevModeW.dmPelsHeight;
2853         bpp = DevModeW.dmBitsPerPel;
2854         mode->RefreshRate = DEFAULT_REFRESH_RATE;
2855         if (DevModeW.dmFields&DM_DISPLAYFREQUENCY)
2856             mode->RefreshRate = DevModeW.dmDisplayFrequency;
2857         mode->Format = pixelformat_for_depth(bpp);
2858     }
2859     else
2860     {
2861         FIXME_(d3d_caps)("Adapter not primary display\n");
2862     }
2863
2864     TRACE_(d3d_caps)("returning w:%d, h:%d, ref:%d, fmt:%s\n", mode->Width,
2865           mode->Height, mode->RefreshRate, debug_d3dformat(mode->Format));
2866     return WINED3D_OK;
2867 }
2868
2869 /* NOTE: due to structure differences between dx8 and dx9 D3DADAPTER_IDENTIFIER,
2870    and fields being inserted in the middle, a new structure is used in place    */
2871 HRESULT CDECL wined3d_get_adapter_identifier(const struct wined3d *wined3d,
2872         UINT adapter_idx, DWORD flags, WINED3DADAPTER_IDENTIFIER *identifier)
2873 {
2874     const struct wined3d_adapter *adapter;
2875     size_t len;
2876
2877     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u, flags %#x, indentifier %p.\n",
2878             wined3d, adapter_idx, flags, identifier);
2879
2880     if (adapter_idx >= wined3d->adapter_count)
2881         return WINED3DERR_INVALIDCALL;
2882
2883     adapter = &wined3d->adapters[adapter_idx];
2884
2885     /* Return the information requested */
2886     TRACE_(d3d_caps)("device/Vendor Name and Version detection using FillGLCaps\n");
2887
2888     if (identifier->driver_size)
2889     {
2890         const char *name = adapter->driver_info.name;
2891         len = min(strlen(name), identifier->driver_size - 1);
2892         memcpy(identifier->driver, name, len);
2893         identifier->driver[len] = '\0';
2894     }
2895
2896     if (identifier->description_size)
2897     {
2898         const char *description = adapter->driver_info.description;
2899         len = min(strlen(description), identifier->description_size - 1);
2900         memcpy(identifier->description, description, len);
2901         identifier->description[len] = '\0';
2902     }
2903
2904     /* Note that d3d8 doesn't supply a device name. */
2905     if (identifier->device_name_size)
2906     {
2907         static const char *device_name = "\\\\.\\DISPLAY1"; /* FIXME: May depend on desktop? */
2908
2909         len = strlen(device_name);
2910         if (len >= identifier->device_name_size)
2911         {
2912             ERR("Device name size too small.\n");
2913             return WINED3DERR_INVALIDCALL;
2914         }
2915
2916         memcpy(identifier->device_name, device_name, len);
2917         identifier->device_name[len] = '\0';
2918     }
2919
2920     identifier->driver_version.u.HighPart = adapter->driver_info.version_high;
2921     identifier->driver_version.u.LowPart = adapter->driver_info.version_low;
2922     identifier->vendor_id = adapter->driver_info.vendor;
2923     identifier->device_id = adapter->driver_info.device;
2924     identifier->subsystem_id = 0;
2925     identifier->revision = 0;
2926     memcpy(&identifier->device_identifier, &IID_D3DDEVICE_D3DUID, sizeof(identifier->device_identifier));
2927     identifier->whql_level = (flags & WINED3DENUM_NO_WHQL_LEVEL) ? 0 : 1;
2928     memcpy(&identifier->adapter_luid, &adapter->luid, sizeof(identifier->adapter_luid));
2929     identifier->video_memory = adapter->TextureRam;
2930
2931     return WINED3D_OK;
2932 }
2933
2934 static BOOL IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(const struct wined3d_gl_info *gl_info,
2935         const struct wined3d_pixel_format *cfg, const struct wined3d_format *format)
2936 {
2937     short redSize, greenSize, blueSize, alphaSize, colorBits;
2938
2939     if(!cfg)
2940         return FALSE;
2941
2942     /* Float formats need FBOs. If FBOs are used this function isn't called */
2943     if (format->flags & WINED3DFMT_FLAG_FLOAT) return FALSE;
2944
2945     if(cfg->iPixelType == WGL_TYPE_RGBA_ARB) { /* Integer RGBA formats */
2946         if (!getColorBits(format, &redSize, &greenSize, &blueSize, &alphaSize, &colorBits))
2947         {
2948             ERR("Unable to check compatibility for format %s.\n", debug_d3dformat(format->id));
2949             return FALSE;
2950         }
2951
2952         if(cfg->redSize < redSize)
2953             return FALSE;
2954
2955         if(cfg->greenSize < greenSize)
2956             return FALSE;
2957
2958         if(cfg->blueSize < blueSize)
2959             return FALSE;
2960
2961         if(cfg->alphaSize < alphaSize)
2962             return FALSE;
2963
2964         return TRUE;
2965     }
2966
2967     /* Probably a RGBA_float or color index mode */
2968     return FALSE;
2969 }
2970
2971 static BOOL IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(const struct wined3d_gl_info *gl_info,
2972         const struct wined3d_pixel_format *cfg, const struct wined3d_format *format)
2973 {
2974     short depthSize, stencilSize;
2975     BOOL lockable = FALSE;
2976
2977     if(!cfg)
2978         return FALSE;
2979
2980     if (!getDepthStencilBits(format, &depthSize, &stencilSize))
2981     {
2982         ERR("Unable to check compatibility for format %s.\n", debug_d3dformat(format->id));
2983         return FALSE;
2984     }
2985
2986     /* Float formats need FBOs. If FBOs are used this function isn't called */
2987     if (format->flags & WINED3DFMT_FLAG_FLOAT) return FALSE;
2988
2989     if ((format->id == WINED3DFMT_D16_LOCKABLE) || (format->id == WINED3DFMT_D32_FLOAT))
2990         lockable = TRUE;
2991
2992     /* On some modern cards like the Geforce8/9 GLX doesn't offer some dephthstencil formats which D3D9 reports.
2993      * We can safely report 'compatible' formats (e.g. D24 can be used for D16) as long as we aren't dealing with
2994      * a lockable format. This also helps D3D <= 7 as they expect D16 which isn't offered without this on Geforce8 cards. */
2995     if(!(cfg->depthSize == depthSize || (!lockable && cfg->depthSize > depthSize)))
2996         return FALSE;
2997
2998     /* Some cards like Intel i915 ones only offer D24S8 but lots of games also need a format without stencil, so
2999      * allow more stencil bits than requested. */
3000     if(cfg->stencilSize < stencilSize)
3001         return FALSE;
3002
3003     return TRUE;
3004 }
3005
3006 HRESULT CDECL wined3d_check_depth_stencil_match(const struct wined3d *wined3d,
3007         UINT adapter_idx, WINED3DDEVTYPE device_type, enum wined3d_format_id adapter_format_id,
3008         enum wined3d_format_id render_target_format_id, enum wined3d_format_id depth_stencil_format_id)
3009 {
3010     const struct wined3d_format *rt_format;
3011     const struct wined3d_format *ds_format;
3012     const struct wined3d_adapter *adapter;
3013
3014     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u, device_type %s,\n"
3015             "adapter_format %s, render_target_format %s, depth_stencil_format %s.\n",
3016             wined3d, adapter_idx, debug_d3ddevicetype(device_type), debug_d3dformat(adapter_format_id),
3017             debug_d3dformat(render_target_format_id), debug_d3dformat(depth_stencil_format_id));
3018
3019     if (adapter_idx >= wined3d->adapter_count)
3020         return WINED3DERR_INVALIDCALL;
3021
3022     adapter = &wined3d->adapters[adapter_idx];
3023     rt_format = wined3d_get_format(&adapter->gl_info, render_target_format_id);
3024     ds_format = wined3d_get_format(&adapter->gl_info, depth_stencil_format_id);
3025     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3026     {
3027         if ((rt_format->flags & WINED3DFMT_FLAG_RENDERTARGET)
3028                 && (ds_format->flags & (WINED3DFMT_FLAG_DEPTH | WINED3DFMT_FLAG_STENCIL)))
3029         {
3030             TRACE_(d3d_caps)("Formats match.\n");
3031             return WINED3D_OK;
3032         }
3033     }
3034     else
3035     {
3036         const struct wined3d_pixel_format *cfgs;
3037         unsigned int cfg_count;
3038         unsigned int i;
3039
3040         cfgs = adapter->cfgs;
3041         cfg_count = adapter->nCfgs;
3042         for (i = 0; i < cfg_count; ++i)
3043         {
3044             if (IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info, &cfgs[i], rt_format))
3045             {
3046                 if (IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, &cfgs[i], ds_format))
3047                 {
3048                     TRACE_(d3d_caps)("Formats match.\n");
3049                     return WINED3D_OK;
3050                 }
3051             }
3052         }
3053     }
3054
3055     TRACE_(d3d_caps)("Unsupported format pair: %s and %s.\n",
3056             debug_d3dformat(render_target_format_id),
3057             debug_d3dformat(depth_stencil_format_id));
3058
3059     return WINED3DERR_NOTAVAILABLE;
3060 }
3061
3062 HRESULT CDECL wined3d_check_device_multisample_type(const struct wined3d *wined3d, UINT adapter_idx,
3063         WINED3DDEVTYPE device_type, enum wined3d_format_id surface_format_id, BOOL windowed,
3064         WINED3DMULTISAMPLE_TYPE multisample_type, DWORD *quality_levels)
3065 {
3066     const struct wined3d_adapter *adapter;
3067     const struct wined3d_format *format;
3068
3069     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u, device_type %s, surface_format %s,\n"
3070             "windowed %#x, multisample_type %#x, quality_levels %p.\n",
3071             wined3d, adapter_idx, debug_d3ddevicetype(device_type), debug_d3dformat(surface_format_id),
3072             windowed, multisample_type, quality_levels);
3073
3074     if (adapter_idx >= wined3d->adapter_count)
3075         return WINED3DERR_INVALIDCALL;
3076
3077     /* TODO: Handle windowed, add more quality levels. */
3078
3079     if (WINED3DMULTISAMPLE_NONE == multisample_type)
3080     {
3081         if (quality_levels) *quality_levels = 1;
3082         return WINED3D_OK;
3083     }
3084
3085     /* By default multisampling is disabled right now as it causes issues
3086      * on some Nvidia driver versions and it doesn't work well in combination
3087      * with FBOs yet. */
3088     if (!wined3d_settings.allow_multisampling)
3089         return WINED3DERR_NOTAVAILABLE;
3090
3091     adapter = &wined3d->adapters[adapter_idx];
3092     format = wined3d_get_format(&adapter->gl_info, surface_format_id);
3093     if (!format) return WINED3DERR_INVALIDCALL;
3094
3095     if (format->flags & (WINED3DFMT_FLAG_DEPTH | WINED3DFMT_FLAG_STENCIL))
3096     {
3097         const struct wined3d_pixel_format *cfgs;
3098         unsigned int i, cfg_count;
3099
3100         cfgs = adapter->cfgs;
3101         cfg_count = adapter->nCfgs;
3102         for (i = 0; i < cfg_count; ++i)
3103         {
3104             if(cfgs[i].numSamples != multisample_type)
3105                 continue;
3106
3107             if (!IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, &cfgs[i], format))
3108                 continue;
3109
3110             TRACE("Found pixel format %u to support multisample_type %#x for format %s.\n",
3111                     cfgs[i].iPixelFormat, multisample_type, debug_d3dformat(surface_format_id));
3112
3113             if (quality_levels) *quality_levels = 1;
3114
3115             return WINED3D_OK;
3116         }
3117     }
3118     else if (format->flags & WINED3DFMT_FLAG_RENDERTARGET)
3119     {
3120         short redSize, greenSize, blueSize, alphaSize, colorBits;
3121         const struct wined3d_pixel_format *cfgs;
3122         unsigned int i, cfg_count;
3123
3124         if (!getColorBits(format, &redSize, &greenSize, &blueSize, &alphaSize, &colorBits))
3125         {
3126             ERR("Unable to get color bits for format %s, can't check multisampling capability.\n",
3127                     debug_d3dformat(surface_format_id));
3128             return WINED3DERR_NOTAVAILABLE;
3129         }
3130
3131         cfgs = adapter->cfgs;
3132         cfg_count = adapter->nCfgs;
3133         for (i = 0; i < cfg_count; ++i)
3134         {
3135             if(cfgs[i].numSamples != multisample_type)
3136                 continue;
3137             if(cfgs[i].redSize != redSize)
3138                 continue;
3139             if(cfgs[i].greenSize != greenSize)
3140                 continue;
3141             if(cfgs[i].blueSize != blueSize)
3142                 continue;
3143             /* Not all drivers report alpha-less formats since they use 32-bit
3144              * anyway, so accept alpha even if we didn't ask for it. */
3145             if(alphaSize && cfgs[i].alphaSize != alphaSize)
3146                 continue;
3147             if (cfgs[i].colorSize != (format->byte_count << 3))
3148                 continue;
3149
3150             TRACE("Found pixel format %u to support multisample_type %#x for format %s.\n",
3151                     cfgs[i].iPixelFormat, multisample_type, debug_d3dformat(surface_format_id));
3152
3153             if (quality_levels) *quality_levels = 1;
3154
3155             return WINED3D_OK;
3156         }
3157     }
3158     return WINED3DERR_NOTAVAILABLE;
3159 }
3160
3161 /* Check if we support bumpmapping for a format */
3162 static BOOL CheckBumpMapCapability(const struct wined3d_adapter *adapter, const struct wined3d_format *format)
3163 {
3164     /* Ask the fixed function pipeline implementation if it can deal
3165      * with the conversion. If we've got a GL extension giving native
3166      * support this will be an identity conversion. */
3167     return (format->flags & WINED3DFMT_FLAG_BUMPMAP)
3168             && adapter->fragment_pipe->color_fixup_supported(format->color_fixup);
3169 }
3170
3171 /* Check if the given DisplayFormat + DepthStencilFormat combination is valid for the Adapter */
3172 static BOOL CheckDepthStencilCapability(const struct wined3d_adapter *adapter,
3173         const struct wined3d_format *display_format, const struct wined3d_format *ds_format)
3174 {
3175     int it=0;
3176
3177     /* Only allow depth/stencil formats */
3178     if (!(ds_format->depth_size || ds_format->stencil_size)) return FALSE;
3179
3180     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3181     {
3182         /* With FBOs WGL limitations do not apply, but the format needs to be FBO attachable */
3183         if (ds_format->flags & (WINED3DFMT_FLAG_DEPTH | WINED3DFMT_FLAG_STENCIL)) return TRUE;
3184     }
3185     else
3186     {
3187         /* Walk through all WGL pixel formats to find a match */
3188         for (it = 0; it < adapter->nCfgs; ++it)
3189         {
3190             const struct wined3d_pixel_format *cfg = &adapter->cfgs[it];
3191             if (IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info, cfg, display_format))
3192             {
3193                 if (IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, cfg, ds_format))
3194                 {
3195                     return TRUE;
3196                 }
3197             }
3198         }
3199     }
3200
3201     return FALSE;
3202 }
3203
3204 static BOOL CheckFilterCapability(const struct wined3d_adapter *adapter, const struct wined3d_format *format)
3205 {
3206     /* The flags entry of a format contains the filtering capability */
3207     if (format->flags & WINED3DFMT_FLAG_FILTERING) return TRUE;
3208
3209     return FALSE;
3210 }
3211
3212 /* Check the render target capabilities of a format */
3213 static BOOL CheckRenderTargetCapability(const struct wined3d_adapter *adapter,
3214         const struct wined3d_format *adapter_format, const struct wined3d_format *check_format)
3215 {
3216     /* Filter out non-RT formats */
3217     if (!(check_format->flags & WINED3DFMT_FLAG_RENDERTARGET)) return FALSE;
3218     if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
3219     {
3220         short AdapterRed, AdapterGreen, AdapterBlue, AdapterAlpha, AdapterTotalSize;
3221         short CheckRed, CheckGreen, CheckBlue, CheckAlpha, CheckTotalSize;
3222         const struct wined3d_pixel_format *cfgs = adapter->cfgs;
3223         int it;
3224
3225         getColorBits(adapter_format, &AdapterRed, &AdapterGreen, &AdapterBlue, &AdapterAlpha, &AdapterTotalSize);
3226         getColorBits(check_format, &CheckRed, &CheckGreen, &CheckBlue, &CheckAlpha, &CheckTotalSize);
3227
3228         /* In backbuffer mode the front and backbuffer share the same WGL pixelformat.
3229          * The format must match in RGB, alpha is allowed to be different. (Only the backbuffer can have alpha) */
3230         if(!((AdapterRed == CheckRed) && (AdapterGreen == CheckGreen) && (AdapterBlue == CheckBlue))) {
3231             TRACE_(d3d_caps)("[FAILED]\n");
3232             return FALSE;
3233         }
3234
3235         /* Check if there is a WGL pixel format matching the requirements, the format should also be window
3236          * drawable (not offscreen; e.g. Nvidia offers R5G6B5 for pbuffers even when X is running at 24bit) */
3237         for (it = 0; it < adapter->nCfgs; ++it)
3238         {
3239             if (cfgs[it].windowDrawable && IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info,
3240                     &cfgs[it], check_format))
3241             {
3242                 TRACE_(d3d_caps)("Pixel format %d is compatible with format %s.\n",
3243                         cfgs[it].iPixelFormat, debug_d3dformat(check_format->id));
3244                 return TRUE;
3245             }
3246         }
3247     }
3248     else if(wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3249     {
3250         /* For now return TRUE for FBOs until we have some proper checks.
3251          * Note that this function will only be called when the format is around for texturing. */
3252         return TRUE;
3253     }
3254     return FALSE;
3255 }
3256
3257 static BOOL CheckSrgbReadCapability(const struct wined3d_adapter *adapter, const struct wined3d_format *format)
3258 {
3259     return format->flags & WINED3DFMT_FLAG_SRGB_READ;
3260 }
3261
3262 static BOOL CheckSrgbWriteCapability(const struct wined3d_adapter *adapter, const struct wined3d_format *format)
3263 {
3264     /* Only offer SRGB writing on X8R8G8B8/A8R8G8B8 when we use ARB or GLSL shaders as we are
3265      * doing the color fixup in shaders.
3266      * Note Windows drivers (at least on the Geforce 8800) also offer this on R5G6B5. */
3267     if (format->flags & WINED3DFMT_FLAG_SRGB_WRITE)
3268     {
3269         int vs_selected_mode;
3270         int ps_selected_mode;
3271         select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
3272
3273         if((ps_selected_mode == SHADER_ARB) || (ps_selected_mode == SHADER_GLSL)) {
3274             TRACE_(d3d_caps)("[OK]\n");
3275             return TRUE;
3276         }
3277     }
3278
3279     TRACE_(d3d_caps)("[FAILED] - sRGB writes not supported by format %s.\n", debug_d3dformat(format->id));
3280     return FALSE;
3281 }
3282
3283 /* Check if a format support blending in combination with pixel shaders */
3284 static BOOL CheckPostPixelShaderBlendingCapability(const struct wined3d_adapter *adapter,
3285         const struct wined3d_format *format)
3286 {
3287     /* The flags entry of a format contains the post pixel shader blending capability */
3288     if (format->flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING) return TRUE;
3289
3290     return FALSE;
3291 }
3292
3293 static BOOL CheckWrapAndMipCapability(const struct wined3d_adapter *adapter, const struct wined3d_format *format)
3294 {
3295     /* OpenGL supports mipmapping on all formats basically. Wrapping is unsupported,
3296      * but we have to report mipmapping so we cannot reject this flag. Tests show that
3297      * windows reports WRAPANDMIP on unfilterable surfaces as well, apparently to show
3298      * that wrapping is supported. The lack of filtering will sort out the mipmapping
3299      * capability anyway.
3300      *
3301      * For now lets report this on all formats, but in the future we may want to
3302      * restrict it to some should games need that
3303      */
3304     return TRUE;
3305 }
3306
3307 /* Check if a texture format is supported on the given adapter */
3308 static BOOL CheckTextureCapability(const struct wined3d_adapter *adapter, const struct wined3d_format *format)
3309 {
3310     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
3311
3312     switch (format->id)
3313     {
3314         /*****
3315          *  supported: RGB(A) formats
3316          */
3317         case WINED3DFMT_B8G8R8_UNORM: /* Enable for dx7, blacklisted for 8 and 9 above */
3318         case WINED3DFMT_B8G8R8A8_UNORM:
3319         case WINED3DFMT_B8G8R8X8_UNORM:
3320         case WINED3DFMT_B5G6R5_UNORM:
3321         case WINED3DFMT_B5G5R5X1_UNORM:
3322         case WINED3DFMT_B5G5R5A1_UNORM:
3323         case WINED3DFMT_B4G4R4A4_UNORM:
3324         case WINED3DFMT_A8_UNORM:
3325         case WINED3DFMT_B4G4R4X4_UNORM:
3326         case WINED3DFMT_R8G8B8A8_UNORM:
3327         case WINED3DFMT_R8G8B8X8_UNORM:
3328         case WINED3DFMT_B10G10R10A2_UNORM:
3329         case WINED3DFMT_R10G10B10A2_UNORM:
3330         case WINED3DFMT_R16G16_UNORM:
3331             TRACE_(d3d_caps)("[OK]\n");
3332             return TRUE;
3333
3334         case WINED3DFMT_B2G3R3_UNORM:
3335             TRACE_(d3d_caps)("[FAILED] - Not supported on Windows\n");
3336             return FALSE;
3337
3338         /*****
3339          *  Not supported: Palettized
3340          *  Only some Geforce/Voodoo3/G400 cards offer 8-bit textures in case of <=Direct3D7.
3341          *  Since it is not widely available, don't offer it. Further no Windows driver offers
3342          *  WINED3DFMT_P8_UINT_A8_NORM, so don't offer it either.
3343          */
3344         case WINED3DFMT_P8_UINT:
3345         case WINED3DFMT_P8_UINT_A8_UNORM:
3346             return FALSE;
3347
3348         /*****
3349          *  Supported: (Alpha)-Luminance
3350          */
3351         case WINED3DFMT_L8_UNORM:
3352         case WINED3DFMT_L8A8_UNORM:
3353         case WINED3DFMT_L16_UNORM:
3354             TRACE_(d3d_caps)("[OK]\n");
3355             return TRUE;
3356
3357         /* Not supported on Windows, thus disabled */
3358         case WINED3DFMT_L4A4_UNORM:
3359             TRACE_(d3d_caps)("[FAILED] - not supported on windows\n");
3360             return FALSE;
3361
3362         /*****
3363          *  Supported: Depth/Stencil formats
3364          */
3365         case WINED3DFMT_D16_LOCKABLE:
3366         case WINED3DFMT_D16_UNORM:
3367         case WINED3DFMT_S1_UINT_D15_UNORM:
3368         case WINED3DFMT_X8D24_UNORM:
3369         case WINED3DFMT_S4X4_UINT_D24_UNORM:
3370         case WINED3DFMT_D24_UNORM_S8_UINT:
3371         case WINED3DFMT_S8_UINT_D24_FLOAT:
3372         case WINED3DFMT_D32_UNORM:
3373         case WINED3DFMT_D32_FLOAT:
3374             return TRUE;
3375
3376         case WINED3DFMT_INTZ:
3377             if (gl_info->supported[EXT_PACKED_DEPTH_STENCIL]
3378                     || gl_info->supported[ARB_FRAMEBUFFER_OBJECT])
3379                 return TRUE;
3380             return FALSE;
3381
3382         /*****
3383          *  Not supported everywhere(depends on GL_ATI_envmap_bumpmap or
3384          *  GL_NV_texture_shader). Emulated by shaders
3385          */
3386         case WINED3DFMT_R8G8_SNORM:
3387         case WINED3DFMT_R8G8_SNORM_L8X8_UNORM:
3388         case WINED3DFMT_R5G5_SNORM_L6_UNORM:
3389         case WINED3DFMT_R8G8B8A8_SNORM:
3390         case WINED3DFMT_R16G16_SNORM:
3391             /* Ask the shader backend if it can deal with the conversion. If
3392              * we've got a GL extension giving native support this will be an
3393              * identity conversion. */
3394             if (adapter->shader_backend->shader_color_fixup_supported(format->color_fixup))
3395             {
3396                 TRACE_(d3d_caps)("[OK]\n");
3397                 return TRUE;
3398             }
3399             TRACE_(d3d_caps)("[FAILED]\n");
3400             return FALSE;
3401
3402         case WINED3DFMT_DXT1:
3403         case WINED3DFMT_DXT2:
3404         case WINED3DFMT_DXT3:
3405         case WINED3DFMT_DXT4:
3406         case WINED3DFMT_DXT5:
3407             if (gl_info->supported[EXT_TEXTURE_COMPRESSION_S3TC])
3408             {
3409                 TRACE_(d3d_caps)("[OK]\n");
3410                 return TRUE;
3411             }
3412             TRACE_(d3d_caps)("[FAILED]\n");
3413             return FALSE;
3414
3415
3416         /*****
3417          *  Odd formats - not supported
3418          */
3419         case WINED3DFMT_VERTEXDATA:
3420         case WINED3DFMT_R16_UINT:
3421         case WINED3DFMT_R32_UINT:
3422         case WINED3DFMT_R16G16B16A16_SNORM:
3423         case WINED3DFMT_R10G10B10_SNORM_A2_UNORM:
3424         case WINED3DFMT_R10G11B11_SNORM:
3425             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
3426             return FALSE;
3427
3428         /*****
3429          *  WINED3DFMT_R8G8_SNORM_Cx: Not supported right now
3430          */
3431         case WINED3DFMT_R8G8_SNORM_Cx:
3432             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
3433             return FALSE;
3434
3435         /* YUV formats */
3436         case WINED3DFMT_UYVY:
3437         case WINED3DFMT_YUY2:
3438             if (gl_info->supported[APPLE_YCBCR_422])
3439             {
3440                 TRACE_(d3d_caps)("[OK]\n");
3441                 return TRUE;
3442             }
3443             TRACE_(d3d_caps)("[FAILED]\n");
3444             return FALSE;
3445         case WINED3DFMT_YV12:
3446             TRACE_(d3d_caps)("[FAILED]\n");
3447             return FALSE;
3448
3449             /* Not supported */
3450         case WINED3DFMT_R16G16B16A16_UNORM:
3451         case WINED3DFMT_B2G3R3A8_UNORM:
3452             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
3453             return FALSE;
3454
3455             /* Floating point formats */
3456         case WINED3DFMT_R16_FLOAT:
3457         case WINED3DFMT_R16G16_FLOAT:
3458         case WINED3DFMT_R16G16B16A16_FLOAT:
3459             if (gl_info->supported[ARB_TEXTURE_FLOAT] && gl_info->supported[ARB_HALF_FLOAT_PIXEL])
3460             {
3461                 TRACE_(d3d_caps)("[OK]\n");
3462                 return TRUE;
3463             }
3464             TRACE_(d3d_caps)("[FAILED]\n");
3465             return FALSE;
3466
3467         case WINED3DFMT_R32_FLOAT:
3468         case WINED3DFMT_R32G32_FLOAT:
3469         case WINED3DFMT_R32G32B32A32_FLOAT:
3470             if (gl_info->supported[ARB_TEXTURE_FLOAT])
3471             {
3472                 TRACE_(d3d_caps)("[OK]\n");
3473                 return TRUE;
3474             }
3475             TRACE_(d3d_caps)("[FAILED]\n");
3476             return FALSE;
3477
3478         /* ATI instancing hack: Although ATI cards do not support Shader Model 3.0, they support
3479          * instancing. To query if the card supports instancing CheckDeviceFormat with the special format
3480          * MAKEFOURCC('I','N','S','T') is used. Should a (broken) app check for this provide a proper return value.
3481          * We can do instancing with all shader versions, but we need vertex shaders.
3482          *
3483          * Additionally applications have to set the D3DRS_POINTSIZE render state to MAKEFOURCC('I','N','S','T') once
3484          * to enable instancing. WineD3D doesn't need that and just ignores it.
3485          *
3486          * With Shader Model 3.0 capable cards Instancing 'just works' in Windows.
3487          */
3488         case WINED3DFMT_INST:
3489             TRACE("ATI Instancing check hack\n");
3490             if (gl_info->supported[ARB_VERTEX_PROGRAM] || gl_info->supported[ARB_VERTEX_SHADER])
3491             {
3492                 TRACE_(d3d_caps)("[OK]\n");
3493                 return TRUE;
3494             }
3495             TRACE_(d3d_caps)("[FAILED]\n");
3496             return FALSE;
3497
3498         /* Some weird FOURCC formats */
3499         case WINED3DFMT_R8G8_B8G8:
3500         case WINED3DFMT_G8R8_G8B8:
3501         case WINED3DFMT_MULTI2_ARGB8:
3502             TRACE_(d3d_caps)("[FAILED]\n");
3503             return FALSE;
3504
3505         /* Vendor specific formats */
3506         case WINED3DFMT_ATI2N:
3507             if (gl_info->supported[ATI_TEXTURE_COMPRESSION_3DC]
3508                     || gl_info->supported[ARB_TEXTURE_COMPRESSION_RGTC])
3509             {
3510                 if (adapter->shader_backend->shader_color_fixup_supported(format->color_fixup)
3511                         && adapter->fragment_pipe->color_fixup_supported(format->color_fixup))
3512                 {
3513                     TRACE_(d3d_caps)("[OK]\n");
3514                     return TRUE;
3515                 }
3516
3517                 TRACE_(d3d_caps)("[OK]\n");
3518                 return TRUE;
3519             }
3520             TRACE_(d3d_caps)("[FAILED]\n");
3521             return FALSE;
3522
3523         /* Depth bound test. To query if the card supports it CheckDeviceFormat with the special
3524          * format MAKEFOURCC('N','V','D','B') is used.
3525          * It is enabled by setting D3DRS_ADAPTIVETESS_X render state to MAKEFOURCC('N','V','D','B') and
3526          * then controlled by setting D3DRS_ADAPTIVETESS_Z (zMin) and D3DRS_ADAPTIVETESS_W (zMax)
3527          * to test value.
3528          */
3529         case WINED3DFMT_NVDB:
3530             if (gl_info->supported[EXT_DEPTH_BOUNDS_TEST])
3531             {
3532                 TRACE_(d3d_caps)("[OK]\n");
3533                 return TRUE;
3534             }
3535             TRACE_(d3d_caps)("[FAILED]\n");
3536             return FALSE;
3537
3538         case WINED3DFMT_NVHU:
3539         case WINED3DFMT_NVHS:
3540             /* These formats seem to be similar to the HILO formats in GL_NV_texture_shader. NVHU
3541              * is said to be GL_UNSIGNED_HILO16, NVHS GL_SIGNED_HILO16. Rumours say that d3d computes
3542              * a 3rd channel similarly to D3DFMT_CxV8U8(So NVHS could be called D3DFMT_CxV16U16).
3543              * ATI refused to support formats which can easilly be emulated with pixel shaders, so
3544              * Applications have to deal with not having NVHS and NVHU.
3545              */
3546             TRACE_(d3d_caps)("[FAILED]\n");
3547             return FALSE;
3548
3549         case WINED3DFMT_NULL:
3550             if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT])
3551                 return TRUE;
3552             return FALSE;
3553
3554         case WINED3DFMT_UNKNOWN:
3555             return FALSE;
3556
3557         default:
3558             ERR("Unhandled format %s.\n", debug_d3dformat(format->id));
3559             break;
3560     }
3561     return FALSE;
3562 }
3563
3564 static BOOL CheckSurfaceCapability(const struct wined3d_adapter *adapter,
3565         const struct wined3d_format *adapter_format,
3566         const struct wined3d_format *check_format,
3567         WINED3DSURFTYPE SurfaceType)
3568 {
3569     if (SurfaceType == SURFACE_GDI)
3570     {
3571         switch (check_format->id)
3572         {
3573             case WINED3DFMT_B8G8R8_UNORM:
3574             case WINED3DFMT_B8G8R8A8_UNORM:
3575             case WINED3DFMT_B8G8R8X8_UNORM:
3576             case WINED3DFMT_B5G6R5_UNORM:
3577             case WINED3DFMT_B5G5R5X1_UNORM:
3578             case WINED3DFMT_B5G5R5A1_UNORM:
3579             case WINED3DFMT_B4G4R4A4_UNORM:
3580             case WINED3DFMT_B2G3R3_UNORM:
3581             case WINED3DFMT_A8_UNORM:
3582             case WINED3DFMT_B2G3R3A8_UNORM:
3583             case WINED3DFMT_B4G4R4X4_UNORM:
3584             case WINED3DFMT_R10G10B10A2_UNORM:
3585             case WINED3DFMT_R8G8B8A8_UNORM:
3586             case WINED3DFMT_R8G8B8X8_UNORM:
3587             case WINED3DFMT_R16G16_UNORM:
3588             case WINED3DFMT_B10G10R10A2_UNORM:
3589             case WINED3DFMT_R16G16B16A16_UNORM:
3590             case WINED3DFMT_P8_UINT:
3591                 TRACE_(d3d_caps)("[OK]\n");
3592                 return TRUE;
3593             default:
3594                 TRACE_(d3d_caps)("[FAILED] - not available on GDI surfaces\n");
3595                 return FALSE;
3596         }
3597     }
3598
3599     /* All format that are supported for textures are supported for surfaces as well */
3600     if (CheckTextureCapability(adapter, check_format)) return TRUE;
3601     /* All depth stencil formats are supported on surfaces */
3602     if (CheckDepthStencilCapability(adapter, adapter_format, check_format)) return TRUE;
3603
3604     /* If opengl can't process the format natively, the blitter may be able to convert it */
3605     if (adapter->blitter->blit_supported(&adapter->gl_info, WINED3D_BLIT_OP_COLOR_BLIT,
3606             NULL, WINED3DPOOL_DEFAULT, 0, check_format,
3607             NULL, WINED3DPOOL_DEFAULT, 0, adapter_format))
3608     {
3609         TRACE_(d3d_caps)("[OK]\n");
3610         return TRUE;
3611     }
3612
3613     /* Reject other formats */
3614     TRACE_(d3d_caps)("[FAILED]\n");
3615     return FALSE;
3616 }
3617
3618 static BOOL CheckVertexTextureCapability(const struct wined3d_adapter *adapter,
3619         const struct wined3d_format *format)
3620 {
3621     return adapter->gl_info.limits.vertex_samplers && (format->flags & WINED3DFMT_FLAG_VTF);
3622 }
3623
3624 HRESULT CDECL wined3d_check_device_format(const struct wined3d *wined3d, UINT adapter_idx,
3625         WINED3DDEVTYPE device_type, enum wined3d_format_id adapter_format_id, DWORD usage,
3626         WINED3DRESOURCETYPE resource_type, enum wined3d_format_id check_format_id, WINED3DSURFTYPE surface_type)
3627 {
3628     const struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
3629     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
3630     const struct wined3d_format *adapter_format = wined3d_get_format(gl_info, adapter_format_id);
3631     const struct wined3d_format *format = wined3d_get_format(gl_info, check_format_id);
3632     DWORD usage_caps = 0;
3633
3634     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u, device_type %s, adapter_format %s, usage %s, %s,\n"
3635             "resource_type %s, check_format %s, surface_type %#x.\n",
3636             wined3d, adapter_idx, debug_d3ddevicetype(device_type), debug_d3dformat(adapter_format_id),
3637             debug_d3dusage(usage), debug_d3dusagequery(usage), debug_d3dresourcetype(resource_type),
3638             debug_d3dformat(check_format_id), surface_type);
3639
3640     if (adapter_idx >= wined3d->adapter_count)
3641         return WINED3DERR_INVALIDCALL;
3642
3643     switch (resource_type)
3644     {
3645         case WINED3DRTYPE_CUBETEXTURE:
3646             /* Cubetexture allows:
3647              *      - WINED3DUSAGE_AUTOGENMIPMAP
3648              *      - WINED3DUSAGE_DEPTHSTENCIL
3649              *      - WINED3DUSAGE_DYNAMIC
3650              *      - WINED3DUSAGE_NONSECURE (d3d9ex)
3651              *      - WINED3DUSAGE_RENDERTARGET
3652              *      - WINED3DUSAGE_SOFTWAREPROCESSING
3653              *      - WINED3DUSAGE_QUERY_WRAPANDMIP
3654              */
3655             if (surface_type != SURFACE_OPENGL)
3656             {
3657                 TRACE_(d3d_caps)("[FAILED]\n");
3658                 return WINED3DERR_NOTAVAILABLE;
3659             }
3660
3661             if (!gl_info->supported[ARB_TEXTURE_CUBE_MAP])
3662             {
3663                 TRACE_(d3d_caps)("[FAILED] - No cube texture support\n");
3664                 return WINED3DERR_NOTAVAILABLE;
3665             }
3666
3667             if (!CheckTextureCapability(adapter, format))
3668             {
3669                 TRACE_(d3d_caps)("[FAILED] - Cube texture format not supported\n");
3670                 return WINED3DERR_NOTAVAILABLE;
3671             }
3672
3673             if (usage & WINED3DUSAGE_AUTOGENMIPMAP)
3674             {
3675                 if (!gl_info->supported[SGIS_GENERATE_MIPMAP])
3676                     /* When autogenmipmap isn't around continue and return
3677                      * WINED3DOK_NOAUTOGEN instead of D3D_OK. */
3678                     TRACE_(d3d_caps)("[FAILED] - No autogenmipmap support, but continuing\n");
3679                 else
3680                     usage_caps |= WINED3DUSAGE_AUTOGENMIPMAP;
3681             }
3682
3683             /* Always report dynamic locking. */
3684             if (usage & WINED3DUSAGE_DYNAMIC)
3685                 usage_caps |= WINED3DUSAGE_DYNAMIC;
3686
3687             if (usage & WINED3DUSAGE_RENDERTARGET)
3688             {
3689                 if (!CheckRenderTargetCapability(adapter, adapter_format, format))
3690                 {
3691                     TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
3692                     return WINED3DERR_NOTAVAILABLE;
3693                 }
3694                 usage_caps |= WINED3DUSAGE_RENDERTARGET;
3695             }
3696
3697             /* Always report software processing. */
3698             if (usage & WINED3DUSAGE_SOFTWAREPROCESSING)
3699                 usage_caps |= WINED3DUSAGE_SOFTWAREPROCESSING;
3700
3701             if (usage & WINED3DUSAGE_QUERY_FILTER)
3702             {
3703                 if (!CheckFilterCapability(adapter, format))
3704                 {
3705                     TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
3706                     return WINED3DERR_NOTAVAILABLE;
3707                 }
3708                 usage_caps |= WINED3DUSAGE_QUERY_FILTER;
3709             }
3710
3711             if (usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING)
3712             {
3713                 if (!CheckPostPixelShaderBlendingCapability(adapter, format))
3714                 {
3715                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
3716                     return WINED3DERR_NOTAVAILABLE;
3717                 }
3718                 usage_caps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
3719             }
3720
3721             if (usage & WINED3DUSAGE_QUERY_SRGBREAD)
3722             {
3723                 if (!CheckSrgbReadCapability(adapter, format))
3724                 {
3725                     TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
3726                     return WINED3DERR_NOTAVAILABLE;
3727                 }
3728                 usage_caps |= WINED3DUSAGE_QUERY_SRGBREAD;
3729             }
3730
3731             if (usage & WINED3DUSAGE_QUERY_SRGBWRITE)
3732             {
3733                 if (!CheckSrgbWriteCapability(adapter, format))
3734                 {
3735                     TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
3736                     return WINED3DERR_NOTAVAILABLE;
3737                 }
3738                 usage_caps |= WINED3DUSAGE_QUERY_SRGBWRITE;
3739             }
3740
3741             if (usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE)
3742             {
3743                 if (!CheckVertexTextureCapability(adapter, format))
3744                 {
3745                     TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
3746                     return WINED3DERR_NOTAVAILABLE;
3747                 }
3748                 usage_caps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
3749             }
3750
3751             if (usage & WINED3DUSAGE_QUERY_WRAPANDMIP)
3752             {
3753                 if (!CheckWrapAndMipCapability(adapter, format))
3754                 {
3755                     TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
3756                     return WINED3DERR_NOTAVAILABLE;
3757                 }
3758                 usage_caps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
3759             }
3760             break;
3761
3762         case WINED3DRTYPE_SURFACE:
3763             /* Surface allows:
3764              *      - WINED3DUSAGE_DEPTHSTENCIL
3765              *      - WINED3DUSAGE_NONSECURE (d3d9ex)
3766              *      - WINED3DUSAGE_RENDERTARGET
3767              */
3768             if (!CheckSurfaceCapability(adapter, adapter_format, format, surface_type))
3769             {
3770                 TRACE_(d3d_caps)("[FAILED] - Not supported for plain surfaces\n");
3771                 return WINED3DERR_NOTAVAILABLE;
3772             }
3773
3774             if (usage & WINED3DUSAGE_DEPTHSTENCIL)
3775             {
3776                 if (!CheckDepthStencilCapability(adapter, adapter_format, format))
3777                 {
3778                     TRACE_(d3d_caps)("[FAILED] - No depthstencil support\n");
3779                     return WINED3DERR_NOTAVAILABLE;
3780                 }
3781                 usage_caps |= WINED3DUSAGE_DEPTHSTENCIL;
3782             }
3783
3784             if (usage & WINED3DUSAGE_RENDERTARGET)
3785             {
3786                 if (!CheckRenderTargetCapability(adapter, adapter_format, format))
3787                 {
3788                     TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
3789                     return WINED3DERR_NOTAVAILABLE;
3790                 }
3791                 usage_caps |= WINED3DUSAGE_RENDERTARGET;
3792             }
3793
3794             if (usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING)
3795             {
3796                 if (!CheckPostPixelShaderBlendingCapability(adapter, format))
3797                 {
3798                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
3799                     return WINED3DERR_NOTAVAILABLE;
3800                 }
3801                 usage_caps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
3802             }
3803             break;
3804
3805         case WINED3DRTYPE_TEXTURE:
3806             /* Texture allows:
3807              *      - WINED3DUSAGE_AUTOGENMIPMAP
3808              *      - WINED3DUSAGE_DEPTHSTENCIL
3809              *      - WINED3DUSAGE_DMAP
3810              *      - WINED3DUSAGE_DYNAMIC
3811              *      - WINED3DUSAGE_NONSECURE (d3d9ex)
3812              *      - WINED3DUSAGE_RENDERTARGET
3813              *      - WINED3DUSAGE_SOFTWAREPROCESSING
3814              *      - WINED3DUSAGE_TEXTAPI (d3d9ex)
3815              *      - WINED3DUSAGE_QUERY_WRAPANDMIP
3816              */
3817             if (surface_type != SURFACE_OPENGL)
3818             {
3819                 TRACE_(d3d_caps)("[FAILED]\n");
3820                 return WINED3DERR_NOTAVAILABLE;
3821             }
3822
3823             if (!CheckTextureCapability(adapter, format))
3824             {
3825                 TRACE_(d3d_caps)("[FAILED] - Texture format not supported\n");
3826                 return WINED3DERR_NOTAVAILABLE;
3827             }
3828
3829             if (usage & WINED3DUSAGE_AUTOGENMIPMAP)
3830             {
3831                 if (!gl_info->supported[SGIS_GENERATE_MIPMAP])
3832                     /* When autogenmipmap isn't around continue and return
3833                      * WINED3DOK_NOAUTOGEN instead of D3D_OK. */
3834                     TRACE_(d3d_caps)("[FAILED] - No autogenmipmap support, but continuing\n");
3835                 else
3836                     usage_caps |= WINED3DUSAGE_AUTOGENMIPMAP;
3837             }
3838
3839             /* Always report dynamic locking. */
3840             if (usage & WINED3DUSAGE_DYNAMIC)
3841                 usage_caps |= WINED3DUSAGE_DYNAMIC;
3842
3843             if (usage & WINED3DUSAGE_RENDERTARGET)
3844             {
3845                 if (!CheckRenderTargetCapability(adapter, adapter_format, format))
3846                 {
3847                     TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
3848                     return WINED3DERR_NOTAVAILABLE;
3849                 }
3850                 usage_caps |= WINED3DUSAGE_RENDERTARGET;
3851             }
3852
3853             /* Always report software processing. */
3854             if (usage & WINED3DUSAGE_SOFTWAREPROCESSING)
3855                 usage_caps |= WINED3DUSAGE_SOFTWAREPROCESSING;
3856
3857             if (usage & WINED3DUSAGE_QUERY_FILTER)
3858             {
3859                 if (!CheckFilterCapability(adapter, format))
3860                 {
3861                     TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
3862                     return WINED3DERR_NOTAVAILABLE;
3863                 }
3864                 usage_caps |= WINED3DUSAGE_QUERY_FILTER;
3865             }
3866
3867             if (usage & WINED3DUSAGE_QUERY_LEGACYBUMPMAP)
3868             {
3869                 if (!CheckBumpMapCapability(adapter, format))
3870                 {
3871                     TRACE_(d3d_caps)("[FAILED] - No legacy bumpmap support\n");
3872                     return WINED3DERR_NOTAVAILABLE;
3873                 }
3874                 usage_caps |= WINED3DUSAGE_QUERY_LEGACYBUMPMAP;
3875             }
3876
3877             if (usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING)
3878             {
3879                 if (!CheckPostPixelShaderBlendingCapability(adapter, format))
3880                 {
3881                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
3882                     return WINED3DERR_NOTAVAILABLE;
3883                 }
3884                 usage_caps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
3885             }
3886
3887             if (usage & WINED3DUSAGE_QUERY_SRGBREAD)
3888             {
3889                 if (!CheckSrgbReadCapability(adapter, format))
3890                 {
3891                     TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
3892                     return WINED3DERR_NOTAVAILABLE;
3893                 }
3894                 usage_caps |= WINED3DUSAGE_QUERY_SRGBREAD;
3895             }
3896
3897             if (usage & WINED3DUSAGE_QUERY_SRGBWRITE)
3898             {
3899                 if (!CheckSrgbWriteCapability(adapter, format))
3900                 {
3901                     TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
3902                     return WINED3DERR_NOTAVAILABLE;
3903                 }
3904                 usage_caps |= WINED3DUSAGE_QUERY_SRGBWRITE;
3905             }
3906
3907             if (usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE)
3908             {
3909                 if (!CheckVertexTextureCapability(adapter, format))
3910                 {
3911                     TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
3912                     return WINED3DERR_NOTAVAILABLE;
3913                 }
3914                 usage_caps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
3915             }
3916
3917             if (usage & WINED3DUSAGE_QUERY_WRAPANDMIP)
3918             {
3919                 if (!CheckWrapAndMipCapability(adapter, format))
3920                 {
3921                     TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
3922                     return WINED3DERR_NOTAVAILABLE;
3923                 }
3924                 usage_caps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
3925             }
3926
3927             if (usage & WINED3DUSAGE_DEPTHSTENCIL)
3928             {
3929                 if (!CheckDepthStencilCapability(adapter, adapter_format, format))
3930                 {
3931                     TRACE_(d3d_caps)("[FAILED] - No depth stencil support\n");
3932                     return WINED3DERR_NOTAVAILABLE;
3933                 }
3934                 if ((format->flags & WINED3DFMT_FLAG_SHADOW) && !gl_info->supported[ARB_SHADOW])
3935                 {
3936                     TRACE_(d3d_caps)("[FAILED] - No shadow sampler support.\n");
3937                     return WINED3DERR_NOTAVAILABLE;
3938                 }
3939                 usage_caps |= WINED3DUSAGE_DEPTHSTENCIL;
3940             }
3941             break;
3942
3943         case WINED3DRTYPE_VOLUMETEXTURE:
3944         case WINED3DRTYPE_VOLUME:
3945             /* Volume is to VolumeTexture what Surface is to Texture, but its
3946              * usage caps are not documented. Most driver seem to offer
3947              * (nearly) the same on Volume and VolumeTexture, so do that too.
3948              *
3949              * Volumetexture allows:
3950              *      - D3DUSAGE_DYNAMIC
3951              *      - D3DUSAGE_NONSECURE (d3d9ex)
3952              *      - D3DUSAGE_SOFTWAREPROCESSING
3953              *      - D3DUSAGE_QUERY_WRAPANDMIP
3954              */
3955             if (surface_type != SURFACE_OPENGL)
3956             {
3957                 TRACE_(d3d_caps)("[FAILED]\n");
3958                 return WINED3DERR_NOTAVAILABLE;
3959             }
3960
3961             if (!gl_info->supported[EXT_TEXTURE3D])
3962             {
3963                 TRACE_(d3d_caps)("[FAILED] - No volume texture support\n");
3964                 return WINED3DERR_NOTAVAILABLE;
3965             }
3966
3967             if (!CheckTextureCapability(adapter, format))
3968             {
3969                 TRACE_(d3d_caps)("[FAILED] - Format not supported\n");
3970                 return WINED3DERR_NOTAVAILABLE;
3971             }
3972
3973             /* Filter formats that need conversion; For one part, this
3974              * conversion is unimplemented, and volume textures are huge, so
3975              * it would be a big performance hit. Unless we hit an application
3976              * needing one of those formats, don't advertize them to avoid
3977              * leading applications into temptation. The windows drivers don't
3978              * support most of those formats on volumes anyway, except for
3979              * WINED3DFMT_R32_FLOAT. */
3980             switch (check_format_id)
3981             {
3982                 case WINED3DFMT_P8_UINT:
3983                 case WINED3DFMT_L4A4_UNORM:
3984                 case WINED3DFMT_R32_FLOAT:
3985                 case WINED3DFMT_R16_FLOAT:
3986                 case WINED3DFMT_R8G8_SNORM_L8X8_UNORM:
3987                 case WINED3DFMT_R5G5_SNORM_L6_UNORM:
3988                 case WINED3DFMT_R16G16_UNORM:
3989                     TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3990                     return WINED3DERR_NOTAVAILABLE;
3991
3992                 case WINED3DFMT_R8G8B8A8_SNORM:
3993                 case WINED3DFMT_R16G16_SNORM:
3994                     if (!gl_info->supported[NV_TEXTURE_SHADER])
3995                     {
3996                         TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3997                         return WINED3DERR_NOTAVAILABLE;
3998                     }
3999                     break;
4000
4001                 case WINED3DFMT_R8G8_SNORM:
4002                     if (!gl_info->supported[NV_TEXTURE_SHADER])
4003                     {
4004                         TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
4005                         return WINED3DERR_NOTAVAILABLE;
4006                     }
4007                     break;
4008
4009                 case WINED3DFMT_DXT1:
4010                 case WINED3DFMT_DXT2:
4011                 case WINED3DFMT_DXT3:
4012                 case WINED3DFMT_DXT4:
4013                 case WINED3DFMT_DXT5:
4014                     /* The GL_EXT_texture_compression_s3tc spec requires that
4015                      * loading an s3tc compressed texture results in an error.
4016                      * While the D3D refrast does support s3tc volumes, at
4017                      * least the nvidia windows driver does not, so we're free
4018                      * not to support this format. */
4019                     TRACE_(d3d_caps)("[FAILED] - DXTn does not support 3D textures\n");
4020                     return WINED3DERR_NOTAVAILABLE;
4021
4022                 default:
4023                     /* Do nothing, continue with checking the format below */
4024                     break;
4025             }
4026
4027             /* Always report dynamic locking. */
4028             if (usage & WINED3DUSAGE_DYNAMIC)
4029                 usage_caps |= WINED3DUSAGE_DYNAMIC;
4030
4031             /* Always report software processing. */
4032             if (usage & WINED3DUSAGE_SOFTWAREPROCESSING)
4033                 usage_caps |= WINED3DUSAGE_SOFTWAREPROCESSING;
4034
4035             if (usage & WINED3DUSAGE_QUERY_FILTER)
4036             {
4037                 if (!CheckFilterCapability(adapter, format))
4038                 {
4039                     TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
4040                     return WINED3DERR_NOTAVAILABLE;
4041                 }
4042                 usage_caps |= WINED3DUSAGE_QUERY_FILTER;
4043             }
4044
4045             if (usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING)
4046             {
4047                 if (!CheckPostPixelShaderBlendingCapability(adapter, format))
4048                 {
4049                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
4050                     return WINED3DERR_NOTAVAILABLE;
4051                 }
4052                 usage_caps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
4053             }
4054
4055             if (usage & WINED3DUSAGE_QUERY_SRGBREAD)
4056             {
4057                 if (!CheckSrgbReadCapability(adapter, format))
4058                 {
4059                     TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
4060                     return WINED3DERR_NOTAVAILABLE;
4061                 }
4062                 usage_caps |= WINED3DUSAGE_QUERY_SRGBREAD;
4063             }
4064
4065             if (usage & WINED3DUSAGE_QUERY_SRGBWRITE)
4066             {
4067                 if (!CheckSrgbWriteCapability(adapter, format))
4068                 {
4069                     TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
4070                     return WINED3DERR_NOTAVAILABLE;
4071                 }
4072                 usage_caps |= WINED3DUSAGE_QUERY_SRGBWRITE;
4073             }
4074
4075             if (usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE)
4076             {
4077                 if (!CheckVertexTextureCapability(adapter, format))
4078                 {
4079                     TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
4080                     return WINED3DERR_NOTAVAILABLE;
4081                 }
4082                 usage_caps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
4083             }
4084
4085             if (usage & WINED3DUSAGE_QUERY_WRAPANDMIP)
4086             {
4087                 if (!CheckWrapAndMipCapability(adapter, format))
4088                 {
4089                     TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
4090                     return WINED3DERR_NOTAVAILABLE;
4091                 }
4092                 usage_caps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
4093             }
4094             break;
4095
4096         default:
4097             FIXME_(d3d_caps)("Unhandled resource type %s.\n", debug_d3dresourcetype(resource_type));
4098             return WINED3DERR_NOTAVAILABLE;
4099     }
4100
4101     /* When the usage_caps exactly matches usage return WINED3D_OK except for
4102      * the situation in which WINED3DUSAGE_AUTOGENMIPMAP isn't around, then
4103      * WINED3DOK_NOAUTOGEN is returned if all the other usage flags match. */
4104     if (usage_caps == usage)
4105         return WINED3D_OK;
4106     if (usage_caps == (usage & ~WINED3DUSAGE_AUTOGENMIPMAP))
4107         return WINED3DOK_NOAUTOGEN;
4108
4109     TRACE_(d3d_caps)("[FAILED] - Usage %#x requested for format %s and resource_type %s but only %#x is available.\n",
4110             usage, debug_d3dformat(check_format_id), debug_d3dresourcetype(resource_type), usage_caps);
4111
4112     return WINED3DERR_NOTAVAILABLE;
4113 }
4114
4115 HRESULT CDECL wined3d_check_device_format_conversion(const struct wined3d *wined3d, UINT adapter_idx,
4116         WINED3DDEVTYPE device_type, enum wined3d_format_id src_format, enum wined3d_format_id dst_format)
4117 {
4118     FIXME("wined3d %p, adapter_idx %u, device_type %s, src_format %s, dst_format %s stub!\n",
4119             wined3d, adapter_idx, debug_d3ddevicetype(device_type), debug_d3dformat(src_format),
4120             debug_d3dformat(dst_format));
4121
4122     return WINED3D_OK;
4123 }
4124
4125 HRESULT CDECL wined3d_check_device_type(const struct wined3d *wined3d, UINT adapter_idx, WINED3DDEVTYPE device_type,
4126         enum wined3d_format_id display_format, enum wined3d_format_id backbuffer_format, BOOL windowed)
4127 {
4128     UINT mode_count;
4129     HRESULT hr;
4130
4131     TRACE("wined3d %p, adapter_idx %u, device_type %s, display_format %s, backbuffer_format %s, windowed %#x.\n",
4132             wined3d, adapter_idx, debug_d3ddevicetype(device_type), debug_d3dformat(display_format),
4133             debug_d3dformat(backbuffer_format), windowed);
4134
4135     if (adapter_idx >= wined3d->adapter_count)
4136         return WINED3DERR_INVALIDCALL;
4137
4138     /* The task of this function is to check whether a certain display / backbuffer format
4139      * combination is available on the given adapter. In fullscreen mode microsoft specified
4140      * that the display format shouldn't provide alpha and that ignoring alpha the backbuffer
4141      * and display format should match exactly.
4142      * In windowed mode format conversion can occur and this depends on the driver. When format
4143      * conversion is done, this function should nevertheless fail and applications need to use
4144      * CheckDeviceFormatConversion.
4145      * At the moment we assume that fullscreen and windowed have the same capabilities. */
4146
4147     /* There are only 4 display formats. */
4148     if (!(display_format == WINED3DFMT_B5G6R5_UNORM
4149             || display_format == WINED3DFMT_B5G5R5X1_UNORM
4150             || display_format == WINED3DFMT_B8G8R8X8_UNORM
4151             || display_format == WINED3DFMT_B10G10R10A2_UNORM))
4152     {
4153         TRACE_(d3d_caps)("Format %s is not supported as display format.\n", debug_d3dformat(display_format));
4154         return WINED3DERR_NOTAVAILABLE;
4155     }
4156
4157     /* If the requested display format is not available, don't continue. */
4158     mode_count = wined3d_get_adapter_mode_count(wined3d, adapter_idx, display_format);
4159     if (!mode_count)
4160     {
4161         TRACE_(d3d_caps)("No available modes for display format %s.\n", debug_d3dformat(display_format));
4162         return WINED3DERR_NOTAVAILABLE;
4163     }
4164
4165     /* Windowed mode allows you to specify WINED3DFMT_UNKNOWN for the backbuffer format,
4166      * it means 'reuse' the display format for the backbuffer. */
4167     if (!windowed && backbuffer_format == WINED3DFMT_UNKNOWN)
4168     {
4169         TRACE_(d3d_caps)("backbuffer_format WINED3FMT_UNKNOWN only available in windowed mode.\n");
4170         return WINED3DERR_NOTAVAILABLE;
4171     }
4172
4173     /* In FULLSCREEN mode WINED3DFMT_B5G6R5_UNORM can only be mixed with
4174      * backbuffer format WINED3DFMT_B5G6R5_UNORM. */
4175     if (display_format == WINED3DFMT_B5G6R5_UNORM && backbuffer_format != WINED3DFMT_B5G6R5_UNORM)
4176     {
4177         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s / %s.\n",
4178                 debug_d3dformat(display_format), debug_d3dformat(backbuffer_format));
4179         return WINED3DERR_NOTAVAILABLE;
4180     }
4181
4182     /* In FULLSCREEN mode WINED3DFMT_B5G5R5X1_UNORM can only be mixed with
4183      * backbuffer formats WINED3DFMT_B5G5R5X1_UNORM and
4184      * WINED3DFMT_B5G5R5A1_UNORM. */
4185     if (display_format == WINED3DFMT_B5G5R5X1_UNORM
4186             && !(backbuffer_format == WINED3DFMT_B5G5R5X1_UNORM || backbuffer_format == WINED3DFMT_B5G5R5A1_UNORM))
4187     {
4188         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s / %s.\n",
4189                 debug_d3dformat(display_format), debug_d3dformat(backbuffer_format));
4190         return WINED3DERR_NOTAVAILABLE;
4191     }
4192
4193     /* In FULLSCREEN mode WINED3DFMT_B8G8R8X8_UNORM can only be mixed with
4194      * backbuffer formats WINED3DFMT_B8G8R8X8_UNORM and
4195      * WINED3DFMT_B8G8R8A8_UNORM. */
4196     if (display_format == WINED3DFMT_B8G8R8X8_UNORM
4197             && !(backbuffer_format == WINED3DFMT_B8G8R8X8_UNORM || backbuffer_format == WINED3DFMT_B8G8R8A8_UNORM))
4198     {
4199         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s / %s.\n",
4200                 debug_d3dformat(display_format), debug_d3dformat(backbuffer_format));
4201         return WINED3DERR_NOTAVAILABLE;
4202     }
4203
4204     /* WINED3DFMT_B10G10R10A2_UNORM is only allowed in fullscreen mode and it
4205      * can only be mixed with backbuffer format WINED3DFMT_B10G10R10A2_UNORM. */
4206     if (display_format == WINED3DFMT_B10G10R10A2_UNORM
4207             && (backbuffer_format != WINED3DFMT_B10G10R10A2_UNORM || windowed))
4208     {
4209         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s / %s.\n",
4210                 debug_d3dformat(display_format), debug_d3dformat(backbuffer_format));
4211         return WINED3DERR_NOTAVAILABLE;
4212     }
4213
4214     /* Use CheckDeviceFormat to see if the backbuffer_format is usable with the given display_format */
4215     hr = wined3d_check_device_format(wined3d, adapter_idx, device_type, display_format,
4216             WINED3DUSAGE_RENDERTARGET, WINED3DRTYPE_SURFACE, backbuffer_format, SURFACE_OPENGL);
4217     if (FAILED(hr))
4218         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s / %s.\n",
4219                 debug_d3dformat(display_format), debug_d3dformat(backbuffer_format));
4220
4221     return hr;
4222 }
4223
4224 /* Note: d3d8 passes in a pointer to a D3DCAPS8 structure, which is a true
4225       subset of a D3DCAPS9 structure. However, it has to come via a void *
4226       as the d3d8 interface cannot import the d3d9 header                  */
4227 HRESULT CDECL wined3d_get_device_caps(const struct wined3d *wined3d, UINT adapter_idx,
4228         WINED3DDEVTYPE device_type, WINED3DCAPS *caps)
4229 {
4230     const struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
4231     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
4232     int vs_selected_mode;
4233     int ps_selected_mode;
4234     struct shader_caps shader_caps;
4235     struct fragment_caps fragment_caps;
4236     DWORD ckey_caps, blit_caps, fx_caps, pal_caps;
4237
4238     TRACE_(d3d_caps)("wined3d %p, adapter_idx %u, device_type %s, caps %p.\n",
4239             wined3d, adapter_idx, debug_d3ddevicetype(device_type), caps);
4240
4241     if (adapter_idx >= wined3d->adapter_count)
4242         return WINED3DERR_INVALIDCALL;
4243
4244     select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
4245
4246     /* ------------------------------------------------
4247        The following fields apply to both d3d8 and d3d9
4248        ------------------------------------------------ */
4249     /* Not quite true, but use h/w supported by opengl I suppose */
4250     caps->DeviceType               = (device_type == WINED3DDEVTYPE_HAL) ? WINED3DDEVTYPE_HAL : WINED3DDEVTYPE_REF;
4251     caps->AdapterOrdinal           = adapter_idx;
4252
4253     caps->Caps                     = 0;
4254     caps->Caps2                    = WINED3DCAPS2_CANRENDERWINDOWED |
4255                                      WINED3DCAPS2_FULLSCREENGAMMA |
4256                                      WINED3DCAPS2_DYNAMICTEXTURES;
4257     if (gl_info->supported[SGIS_GENERATE_MIPMAP])
4258         caps->Caps2 |= WINED3DCAPS2_CANAUTOGENMIPMAP;
4259
4260     caps->Caps3                    = WINED3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD |
4261                                      WINED3DCAPS3_COPY_TO_VIDMEM                   |
4262                                      WINED3DCAPS3_COPY_TO_SYSTEMMEM;
4263
4264     caps->PresentationIntervals    = WINED3DPRESENT_INTERVAL_IMMEDIATE  |
4265                                      WINED3DPRESENT_INTERVAL_ONE;
4266
4267     caps->CursorCaps               = WINED3DCURSORCAPS_COLOR            |
4268                                      WINED3DCURSORCAPS_LOWRES;
4269
4270     caps->DevCaps                  = WINED3DDEVCAPS_FLOATTLVERTEX       |
4271                                      WINED3DDEVCAPS_EXECUTESYSTEMMEMORY |
4272                                      WINED3DDEVCAPS_TLVERTEXSYSTEMMEMORY|
4273                                      WINED3DDEVCAPS_TLVERTEXVIDEOMEMORY |
4274                                      WINED3DDEVCAPS_DRAWPRIMTLVERTEX    |
4275                                      WINED3DDEVCAPS_HWTRANSFORMANDLIGHT |
4276                                      WINED3DDEVCAPS_EXECUTEVIDEOMEMORY  |
4277                                      WINED3DDEVCAPS_PUREDEVICE          |
4278                                      WINED3DDEVCAPS_HWRASTERIZATION     |
4279                                      WINED3DDEVCAPS_TEXTUREVIDEOMEMORY  |
4280                                      WINED3DDEVCAPS_TEXTURESYSTEMMEMORY |
4281                                      WINED3DDEVCAPS_CANRENDERAFTERFLIP  |
4282                                      WINED3DDEVCAPS_DRAWPRIMITIVES2     |
4283                                      WINED3DDEVCAPS_DRAWPRIMITIVES2EX   |
4284                                      WINED3DDEVCAPS_RTPATCHES;
4285
4286     caps->PrimitiveMiscCaps        = WINED3DPMISCCAPS_CULLNONE              |
4287                                      WINED3DPMISCCAPS_CULLCCW               |
4288                                      WINED3DPMISCCAPS_CULLCW                |
4289                                      WINED3DPMISCCAPS_COLORWRITEENABLE      |
4290                                      WINED3DPMISCCAPS_CLIPTLVERTS           |
4291                                      WINED3DPMISCCAPS_CLIPPLANESCALEDPOINTS |
4292                                      WINED3DPMISCCAPS_MASKZ                 |
4293                                      WINED3DPMISCCAPS_BLENDOP               |
4294                                      WINED3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING;
4295                                     /* TODO:
4296                                         WINED3DPMISCCAPS_NULLREFERENCE
4297                                         WINED3DPMISCCAPS_FOGANDSPECULARALPHA
4298                                         WINED3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS
4299                                         WINED3DPMISCCAPS_FOGVERTEXCLAMPED */
4300
4301     if (gl_info->supported[EXT_BLEND_EQUATION_SEPARATE] && gl_info->supported[EXT_BLEND_FUNC_SEPARATE])
4302         caps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_SEPARATEALPHABLEND;
4303     if (gl_info->supported[EXT_DRAW_BUFFERS2])
4304         caps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_INDEPENDENTWRITEMASKS;
4305
4306     caps->RasterCaps               = WINED3DPRASTERCAPS_DITHER    |
4307                                      WINED3DPRASTERCAPS_PAT       |
4308                                      WINED3DPRASTERCAPS_WFOG      |
4309                                      WINED3DPRASTERCAPS_ZFOG      |
4310                                      WINED3DPRASTERCAPS_FOGVERTEX |
4311                                      WINED3DPRASTERCAPS_FOGTABLE  |
4312                                      WINED3DPRASTERCAPS_STIPPLE   |
4313                                      WINED3DPRASTERCAPS_SUBPIXEL  |
4314                                      WINED3DPRASTERCAPS_ZTEST     |
4315                                      WINED3DPRASTERCAPS_SCISSORTEST   |
4316                                      WINED3DPRASTERCAPS_SLOPESCALEDEPTHBIAS |
4317                                      WINED3DPRASTERCAPS_DEPTHBIAS;
4318
4319     if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
4320     {
4321         caps->RasterCaps  |= WINED3DPRASTERCAPS_ANISOTROPY    |
4322                              WINED3DPRASTERCAPS_ZBIAS         |
4323                              WINED3DPRASTERCAPS_MIPMAPLODBIAS;
4324     }
4325     if (gl_info->supported[NV_FOG_DISTANCE])
4326     {
4327         caps->RasterCaps          |= WINED3DPRASTERCAPS_FOGRANGE;
4328     }
4329                         /* FIXME Add:
4330                            WINED3DPRASTERCAPS_COLORPERSPECTIVE
4331                            WINED3DPRASTERCAPS_STRETCHBLTMULTISAMPLE
4332                            WINED3DPRASTERCAPS_ANTIALIASEDGES
4333                            WINED3DPRASTERCAPS_ZBUFFERLESSHSR
4334                            WINED3DPRASTERCAPS_WBUFFER */
4335
4336     caps->ZCmpCaps =  WINED3DPCMPCAPS_ALWAYS       |
4337                       WINED3DPCMPCAPS_EQUAL        |
4338                       WINED3DPCMPCAPS_GREATER      |
4339                       WINED3DPCMPCAPS_GREATEREQUAL |
4340                       WINED3DPCMPCAPS_LESS         |
4341                       WINED3DPCMPCAPS_LESSEQUAL    |
4342                       WINED3DPCMPCAPS_NEVER        |
4343                       WINED3DPCMPCAPS_NOTEQUAL;
4344
4345     caps->SrcBlendCaps  =  WINED3DPBLENDCAPS_BOTHINVSRCALPHA |
4346                            WINED3DPBLENDCAPS_BOTHSRCALPHA    |
4347                            WINED3DPBLENDCAPS_DESTALPHA       |
4348                            WINED3DPBLENDCAPS_DESTCOLOR       |
4349                            WINED3DPBLENDCAPS_INVDESTALPHA    |
4350                            WINED3DPBLENDCAPS_INVDESTCOLOR    |
4351                            WINED3DPBLENDCAPS_INVSRCALPHA     |
4352                            WINED3DPBLENDCAPS_INVSRCCOLOR     |
4353                            WINED3DPBLENDCAPS_ONE             |
4354                            WINED3DPBLENDCAPS_SRCALPHA        |
4355                            WINED3DPBLENDCAPS_SRCALPHASAT     |
4356                            WINED3DPBLENDCAPS_SRCCOLOR        |
4357                            WINED3DPBLENDCAPS_ZERO;
4358
4359     caps->DestBlendCaps =  WINED3DPBLENDCAPS_DESTALPHA       |
4360                            WINED3DPBLENDCAPS_DESTCOLOR       |
4361                            WINED3DPBLENDCAPS_INVDESTALPHA    |
4362                            WINED3DPBLENDCAPS_INVDESTCOLOR    |
4363                            WINED3DPBLENDCAPS_INVSRCALPHA     |
4364                            WINED3DPBLENDCAPS_INVSRCCOLOR     |
4365                            WINED3DPBLENDCAPS_ONE             |
4366                            WINED3DPBLENDCAPS_SRCALPHA        |
4367                            WINED3DPBLENDCAPS_SRCCOLOR        |
4368                            WINED3DPBLENDCAPS_ZERO;
4369     /* NOTE: WINED3DPBLENDCAPS_SRCALPHASAT is not supported as dest blend factor,
4370      * according to the glBlendFunc manpage
4371      *
4372      * WINED3DPBLENDCAPS_BOTHINVSRCALPHA and WINED3DPBLENDCAPS_BOTHSRCALPHA are
4373      * legacy settings for srcblend only
4374      */
4375
4376     if (gl_info->supported[EXT_BLEND_COLOR])
4377     {
4378         caps->SrcBlendCaps |= WINED3DPBLENDCAPS_BLENDFACTOR;
4379         caps->DestBlendCaps |= WINED3DPBLENDCAPS_BLENDFACTOR;
4380     }
4381
4382
4383     caps->AlphaCmpCaps  = WINED3DPCMPCAPS_ALWAYS       |
4384                           WINED3DPCMPCAPS_EQUAL        |
4385                           WINED3DPCMPCAPS_GREATER      |
4386                           WINED3DPCMPCAPS_GREATEREQUAL |
4387                           WINED3DPCMPCAPS_LESS         |
4388                           WINED3DPCMPCAPS_LESSEQUAL    |
4389                           WINED3DPCMPCAPS_NEVER        |
4390                           WINED3DPCMPCAPS_NOTEQUAL;
4391
4392     caps->ShadeCaps      = WINED3DPSHADECAPS_SPECULARGOURAUDRGB |
4393                            WINED3DPSHADECAPS_COLORGOURAUDRGB    |
4394                            WINED3DPSHADECAPS_ALPHAFLATBLEND     |
4395                            WINED3DPSHADECAPS_ALPHAGOURAUDBLEND  |
4396                            WINED3DPSHADECAPS_COLORFLATRGB       |
4397                            WINED3DPSHADECAPS_FOGFLAT            |
4398                            WINED3DPSHADECAPS_FOGGOURAUD         |
4399                            WINED3DPSHADECAPS_SPECULARFLATRGB;
4400
4401     caps->TextureCaps   = WINED3DPTEXTURECAPS_ALPHA              |
4402                           WINED3DPTEXTURECAPS_ALPHAPALETTE       |
4403                           WINED3DPTEXTURECAPS_TRANSPARENCY       |
4404                           WINED3DPTEXTURECAPS_BORDER             |
4405                           WINED3DPTEXTURECAPS_MIPMAP             |
4406                           WINED3DPTEXTURECAPS_PROJECTED          |
4407                           WINED3DPTEXTURECAPS_PERSPECTIVE;
4408
4409     if (!gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
4410     {
4411         caps->TextureCaps  |= WINED3DPTEXTURECAPS_POW2 |
4412                               WINED3DPTEXTURECAPS_NONPOW2CONDITIONAL;
4413     }
4414
4415     if (gl_info->supported[EXT_TEXTURE3D])
4416     {
4417         caps->TextureCaps  |=  WINED3DPTEXTURECAPS_VOLUMEMAP      |
4418                                WINED3DPTEXTURECAPS_MIPVOLUMEMAP;
4419         if (!gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
4420         {
4421             caps->TextureCaps |= WINED3DPTEXTURECAPS_VOLUMEMAP_POW2;
4422         }
4423     }
4424
4425     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4426     {
4427         caps->TextureCaps  |= WINED3DPTEXTURECAPS_CUBEMAP     |
4428                               WINED3DPTEXTURECAPS_MIPCUBEMAP;
4429         if (!gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
4430         {
4431             caps->TextureCaps |= WINED3DPTEXTURECAPS_CUBEMAP_POW2;
4432         }
4433     }
4434
4435     caps->TextureFilterCaps =  WINED3DPTFILTERCAPS_MAGFLINEAR       |
4436                                WINED3DPTFILTERCAPS_MAGFPOINT        |
4437                                WINED3DPTFILTERCAPS_MINFLINEAR       |
4438                                WINED3DPTFILTERCAPS_MINFPOINT        |
4439                                WINED3DPTFILTERCAPS_MIPFLINEAR       |
4440                                WINED3DPTFILTERCAPS_MIPFPOINT        |
4441                                WINED3DPTFILTERCAPS_LINEAR           |
4442                                WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
4443                                WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
4444                                WINED3DPTFILTERCAPS_MIPLINEAR        |
4445                                WINED3DPTFILTERCAPS_MIPNEAREST       |
4446                                WINED3DPTFILTERCAPS_NEAREST;
4447
4448     if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
4449     {
4450         caps->TextureFilterCaps  |= WINED3DPTFILTERCAPS_MAGFANISOTROPIC |
4451                                     WINED3DPTFILTERCAPS_MINFANISOTROPIC;
4452     }
4453
4454     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4455     {
4456         caps->CubeTextureFilterCaps =  WINED3DPTFILTERCAPS_MAGFLINEAR       |
4457                                        WINED3DPTFILTERCAPS_MAGFPOINT        |
4458                                        WINED3DPTFILTERCAPS_MINFLINEAR       |
4459                                        WINED3DPTFILTERCAPS_MINFPOINT        |
4460                                        WINED3DPTFILTERCAPS_MIPFLINEAR       |
4461                                        WINED3DPTFILTERCAPS_MIPFPOINT        |
4462                                        WINED3DPTFILTERCAPS_LINEAR           |
4463                                        WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
4464                                        WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
4465                                        WINED3DPTFILTERCAPS_MIPLINEAR        |
4466                                        WINED3DPTFILTERCAPS_MIPNEAREST       |
4467                                        WINED3DPTFILTERCAPS_NEAREST;
4468
4469         if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
4470         {
4471             caps->CubeTextureFilterCaps  |= WINED3DPTFILTERCAPS_MAGFANISOTROPIC |
4472                                             WINED3DPTFILTERCAPS_MINFANISOTROPIC;
4473         }
4474     }
4475     else
4476     {
4477         caps->CubeTextureFilterCaps = 0;
4478     }
4479
4480     if (gl_info->supported[EXT_TEXTURE3D])
4481     {
4482         caps->VolumeTextureFilterCaps  = WINED3DPTFILTERCAPS_MAGFLINEAR       |
4483                                          WINED3DPTFILTERCAPS_MAGFPOINT        |
4484                                          WINED3DPTFILTERCAPS_MINFLINEAR       |
4485                                          WINED3DPTFILTERCAPS_MINFPOINT        |
4486                                          WINED3DPTFILTERCAPS_MIPFLINEAR       |
4487                                          WINED3DPTFILTERCAPS_MIPFPOINT        |
4488                                          WINED3DPTFILTERCAPS_LINEAR           |
4489                                          WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
4490                                          WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
4491                                          WINED3DPTFILTERCAPS_MIPLINEAR        |
4492                                          WINED3DPTFILTERCAPS_MIPNEAREST       |
4493                                          WINED3DPTFILTERCAPS_NEAREST;
4494     }
4495     else
4496     {
4497         caps->VolumeTextureFilterCaps = 0;
4498     }
4499
4500     caps->TextureAddressCaps  =  WINED3DPTADDRESSCAPS_INDEPENDENTUV |
4501                                  WINED3DPTADDRESSCAPS_CLAMP  |
4502                                  WINED3DPTADDRESSCAPS_WRAP;
4503
4504     if (gl_info->supported[ARB_TEXTURE_BORDER_CLAMP])
4505     {
4506         caps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_BORDER;
4507     }
4508     if (gl_info->supported[ARB_TEXTURE_MIRRORED_REPEAT])
4509     {
4510         caps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRROR;
4511     }
4512     if (gl_info->supported[ATI_TEXTURE_MIRROR_ONCE])
4513     {
4514         caps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRRORONCE;
4515     }
4516
4517     if (gl_info->supported[EXT_TEXTURE3D])
4518     {
4519         caps->VolumeTextureAddressCaps =   WINED3DPTADDRESSCAPS_INDEPENDENTUV |
4520                                            WINED3DPTADDRESSCAPS_CLAMP  |
4521                                            WINED3DPTADDRESSCAPS_WRAP;
4522         if (gl_info->supported[ARB_TEXTURE_BORDER_CLAMP])
4523         {
4524             caps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_BORDER;
4525         }
4526         if (gl_info->supported[ARB_TEXTURE_MIRRORED_REPEAT])
4527         {
4528             caps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRROR;
4529         }
4530         if (gl_info->supported[ATI_TEXTURE_MIRROR_ONCE])
4531         {
4532             caps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRRORONCE;
4533         }
4534     }
4535     else
4536     {
4537         caps->VolumeTextureAddressCaps = 0;
4538     }
4539
4540     caps->LineCaps  = WINED3DLINECAPS_TEXTURE       |
4541                       WINED3DLINECAPS_ZTEST         |
4542                       WINED3DLINECAPS_BLEND         |
4543                       WINED3DLINECAPS_ALPHACMP      |
4544                       WINED3DLINECAPS_FOG;
4545     /* WINED3DLINECAPS_ANTIALIAS is not supported on Windows, and dx and gl seem to have a different
4546      * idea how generating the smoothing alpha values works; the result is different
4547      */
4548
4549     caps->MaxTextureWidth = gl_info->limits.texture_size;
4550     caps->MaxTextureHeight = gl_info->limits.texture_size;
4551
4552     if (gl_info->supported[EXT_TEXTURE3D])
4553         caps->MaxVolumeExtent = gl_info->limits.texture3d_size;
4554     else
4555         caps->MaxVolumeExtent = 0;
4556
4557     caps->MaxTextureRepeat = 32768;
4558     caps->MaxTextureAspectRatio = gl_info->limits.texture_size;
4559     caps->MaxVertexW = 1.0f;
4560
4561     caps->GuardBandLeft = 0.0f;
4562     caps->GuardBandTop = 0.0f;
4563     caps->GuardBandRight = 0.0f;
4564     caps->GuardBandBottom = 0.0f;
4565
4566     caps->ExtentsAdjust = 0.0f;
4567
4568     caps->StencilCaps   = WINED3DSTENCILCAPS_DECRSAT |
4569                           WINED3DSTENCILCAPS_INCRSAT |
4570                           WINED3DSTENCILCAPS_INVERT  |
4571                           WINED3DSTENCILCAPS_KEEP    |
4572                           WINED3DSTENCILCAPS_REPLACE |
4573                           WINED3DSTENCILCAPS_ZERO;
4574     if (gl_info->supported[EXT_STENCIL_WRAP])
4575     {
4576         caps->StencilCaps |= WINED3DSTENCILCAPS_DECR  |
4577                               WINED3DSTENCILCAPS_INCR;
4578     }
4579     if (gl_info->supported[EXT_STENCIL_TWO_SIDE] || gl_info->supported[ATI_SEPARATE_STENCIL])
4580     {
4581         caps->StencilCaps |= WINED3DSTENCILCAPS_TWOSIDED;
4582     }
4583
4584     caps->FVFCaps = WINED3DFVFCAPS_PSIZE | 0x0008; /* 8 texture coords */
4585
4586     caps->MaxUserClipPlanes = gl_info->limits.clipplanes;
4587     caps->MaxActiveLights = gl_info->limits.lights;
4588
4589     caps->MaxVertexBlendMatrices = gl_info->limits.blends;
4590     caps->MaxVertexBlendMatrixIndex   = 0;
4591
4592     caps->MaxAnisotropy = gl_info->limits.anisotropy;
4593     caps->MaxPointSize = gl_info->limits.pointsize_max;
4594
4595
4596     /* FIXME: Add D3DVTXPCAPS_TWEENING, D3DVTXPCAPS_TEXGEN_SPHEREMAP */
4597     caps->VertexProcessingCaps  = WINED3DVTXPCAPS_DIRECTIONALLIGHTS |
4598                                   WINED3DVTXPCAPS_MATERIALSOURCE7   |
4599                                   WINED3DVTXPCAPS_POSITIONALLIGHTS  |
4600                                   WINED3DVTXPCAPS_LOCALVIEWER       |
4601                                   WINED3DVTXPCAPS_VERTEXFOG         |
4602                                   WINED3DVTXPCAPS_TEXGEN;
4603
4604     caps->MaxPrimitiveCount   = 0xFFFFF; /* For now set 2^20-1 which is used by most >=Geforce3/Radeon8500 cards */
4605     caps->MaxVertexIndex      = 0xFFFFF;
4606     caps->MaxStreams          = MAX_STREAMS;
4607     caps->MaxStreamStride     = 1024;
4608
4609     /* d3d9.dll sets D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES here because StretchRects is implemented in d3d9 */
4610     caps->DevCaps2                          = WINED3DDEVCAPS2_STREAMOFFSET |
4611                                               WINED3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET;
4612     caps->MaxNpatchTessellationLevel        = 0;
4613     caps->MasterAdapterOrdinal              = 0;
4614     caps->AdapterOrdinalInGroup             = 0;
4615     caps->NumberOfAdaptersInGroup           = 1;
4616
4617     caps->NumSimultaneousRTs = gl_info->limits.buffers;
4618
4619     caps->StretchRectFilterCaps               = WINED3DPTFILTERCAPS_MINFPOINT  |
4620                                                 WINED3DPTFILTERCAPS_MAGFPOINT  |
4621                                                 WINED3DPTFILTERCAPS_MINFLINEAR |
4622                                                 WINED3DPTFILTERCAPS_MAGFLINEAR;
4623     caps->VertexTextureFilterCaps             = 0;
4624
4625     adapter->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
4626     adapter->fragment_pipe->get_caps(&adapter->gl_info, &fragment_caps);
4627
4628     /* Add shader misc caps. Only some of them belong to the shader parts of the pipeline */
4629     caps->PrimitiveMiscCaps |= fragment_caps.PrimitiveMiscCaps;
4630
4631     /* This takes care for disabling vertex shader or pixel shader caps while leaving the other one enabled.
4632      * Ignore shader model capabilities if disabled in config
4633      */
4634     if (vs_selected_mode == SHADER_NONE)
4635     {
4636         TRACE_(d3d_caps)("Vertex shader disabled in config, reporting version 0.0\n");
4637         caps->VertexShaderVersion          = WINED3DVS_VERSION(0,0);
4638         caps->MaxVertexShaderConst         = 0;
4639     }
4640     else
4641     {
4642         caps->VertexShaderVersion          = shader_caps.VertexShaderVersion;
4643         caps->MaxVertexShaderConst         = shader_caps.MaxVertexShaderConst;
4644     }
4645
4646     if (ps_selected_mode == SHADER_NONE)
4647     {
4648         TRACE_(d3d_caps)("Pixel shader disabled in config, reporting version 0.0\n");
4649         caps->PixelShaderVersion           = WINED3DPS_VERSION(0,0);
4650         caps->PixelShader1xMaxValue        = 0.0f;
4651     } else {
4652         caps->PixelShaderVersion           = shader_caps.PixelShaderVersion;
4653         caps->PixelShader1xMaxValue        = shader_caps.PixelShader1xMaxValue;
4654     }
4655
4656     caps->TextureOpCaps                    = fragment_caps.TextureOpCaps;
4657     caps->MaxTextureBlendStages            = fragment_caps.MaxTextureBlendStages;
4658     caps->MaxSimultaneousTextures          = fragment_caps.MaxSimultaneousTextures;
4659
4660     /* The following caps are shader specific, but they are things we cannot detect, or which
4661      * are the same among all shader models. So to avoid code duplication set the shader version
4662      * specific, but otherwise constant caps here
4663      */
4664     if (caps->VertexShaderVersion == WINED3DVS_VERSION(3,0))
4665     {
4666         /* Where possible set the caps based on OpenGL extensions and if they
4667          * aren't set (in case of software rendering) use the VS 3.0 from
4668          * MSDN or else if there's OpenGL spec use a hardcoded value minimum
4669          * VS3.0 value. */
4670         caps->VS20Caps.Caps                     = WINED3DVS20CAPS_PREDICATION;
4671         /* VS 3.0 requires MAX_DYNAMICFLOWCONTROLDEPTH (24) */
4672         caps->VS20Caps.DynamicFlowControlDepth  = WINED3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH;
4673         caps->VS20Caps.NumTemps = max(32, adapter->gl_info.limits.arb_vs_temps);
4674         /* level of nesting in loops / if-statements; VS 3.0 requires MAX (4) */
4675         caps->VS20Caps.StaticFlowControlDepth   = WINED3DVS20_MAX_STATICFLOWCONTROLDEPTH;
4676
4677         caps->MaxVShaderInstructionsExecuted    = 65535; /* VS 3.0 needs at least 65535, some cards even use 2^32-1 */
4678         caps->MaxVertexShader30InstructionSlots = max(512, adapter->gl_info.limits.arb_vs_instructions);
4679     }
4680     else if (caps->VertexShaderVersion == WINED3DVS_VERSION(2,0))
4681     {
4682         caps->VS20Caps.Caps                     = 0;
4683         caps->VS20Caps.DynamicFlowControlDepth  = WINED3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH;
4684         caps->VS20Caps.NumTemps = max(12, adapter->gl_info.limits.arb_vs_temps);
4685         caps->VS20Caps.StaticFlowControlDepth   = 1;
4686
4687         caps->MaxVShaderInstructionsExecuted    = 65535;
4688         caps->MaxVertexShader30InstructionSlots = 0;
4689     }
4690     else
4691     { /* VS 1.x */
4692         caps->VS20Caps.Caps                     = 0;
4693         caps->VS20Caps.DynamicFlowControlDepth  = 0;
4694         caps->VS20Caps.NumTemps                 = 0;
4695         caps->VS20Caps.StaticFlowControlDepth   = 0;
4696
4697         caps->MaxVShaderInstructionsExecuted    = 0;
4698         caps->MaxVertexShader30InstructionSlots = 0;
4699     }
4700
4701     if (caps->PixelShaderVersion == WINED3DPS_VERSION(3,0))
4702     {
4703         /* Where possible set the caps based on OpenGL extensions and if they
4704          * aren't set (in case of software rendering) use the PS 3.0 from
4705          * MSDN or else if there's OpenGL spec use a hardcoded value minimum
4706          * PS 3.0 value. */
4707
4708         /* Caps is more or less undocumented on MSDN but it appears to be
4709          * used for PS20Caps based on results from R9600/FX5900/Geforce6800
4710          * cards from Windows */
4711         caps->PS20Caps.Caps = WINED3DPS20CAPS_ARBITRARYSWIZZLE |
4712                 WINED3DPS20CAPS_GRADIENTINSTRUCTIONS |
4713                 WINED3DPS20CAPS_PREDICATION          |
4714                 WINED3DPS20CAPS_NODEPENDENTREADLIMIT |
4715                 WINED3DPS20CAPS_NOTEXINSTRUCTIONLIMIT;
4716         /* PS 3.0 requires MAX_DYNAMICFLOWCONTROLDEPTH (24) */
4717         caps->PS20Caps.DynamicFlowControlDepth  = WINED3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH;
4718         caps->PS20Caps.NumTemps = max(32, adapter->gl_info.limits.arb_ps_temps);
4719         /* PS 3.0 requires MAX_STATICFLOWCONTROLDEPTH (4) */
4720         caps->PS20Caps.StaticFlowControlDepth = WINED3DPS20_MAX_STATICFLOWCONTROLDEPTH;
4721         /* PS 3.0 requires MAX_NUMINSTRUCTIONSLOTS (512) */
4722         caps->PS20Caps.NumInstructionSlots = WINED3DPS20_MAX_NUMINSTRUCTIONSLOTS;
4723
4724         caps->MaxPShaderInstructionsExecuted = 65535;
4725         caps->MaxPixelShader30InstructionSlots = max(WINED3DMIN30SHADERINSTRUCTIONS,
4726                 adapter->gl_info.limits.arb_ps_instructions);
4727     }
4728     else if(caps->PixelShaderVersion == WINED3DPS_VERSION(2,0))
4729     {
4730         /* Below we assume PS2.0 specs, not extended 2.0a(GeforceFX)/2.0b(Radeon R3xx) ones */
4731         caps->PS20Caps.Caps                     = 0;
4732         caps->PS20Caps.DynamicFlowControlDepth  = 0; /* WINED3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH = 0 */
4733         caps->PS20Caps.NumTemps = max(12, adapter->gl_info.limits.arb_ps_temps);
4734         caps->PS20Caps.StaticFlowControlDepth   = WINED3DPS20_MIN_STATICFLOWCONTROLDEPTH; /* Minimum: 1 */
4735         /* Minimum number (64 ALU + 32 Texture), a GeforceFX uses 512 */
4736         caps->PS20Caps.NumInstructionSlots      = WINED3DPS20_MIN_NUMINSTRUCTIONSLOTS;
4737
4738         caps->MaxPShaderInstructionsExecuted    = 512; /* Minimum value, a GeforceFX uses 1024 */
4739         caps->MaxPixelShader30InstructionSlots  = 0;
4740     }
4741     else /* PS 1.x */
4742     {
4743         caps->PS20Caps.Caps                     = 0;
4744         caps->PS20Caps.DynamicFlowControlDepth  = 0;
4745         caps->PS20Caps.NumTemps                 = 0;
4746         caps->PS20Caps.StaticFlowControlDepth   = 0;
4747         caps->PS20Caps.NumInstructionSlots      = 0;
4748
4749         caps->MaxPShaderInstructionsExecuted    = 0;
4750         caps->MaxPixelShader30InstructionSlots  = 0;
4751     }
4752
4753     if (caps->VertexShaderVersion >= WINED3DVS_VERSION(2,0))
4754     {
4755         /* OpenGL supports all the formats below, perhaps not always
4756          * without conversion, but it supports them.
4757          * Further GLSL doesn't seem to have an official unsigned type so
4758          * don't advertise it yet as I'm not sure how we handle it.
4759          * We might need to add some clamping in the shader engine to
4760          * support it.
4761          * TODO: WINED3DDTCAPS_USHORT2N, WINED3DDTCAPS_USHORT4N, WINED3DDTCAPS_UDEC3, WINED3DDTCAPS_DEC3N */
4762         caps->DeclTypes = WINED3DDTCAPS_UBYTE4    |
4763                           WINED3DDTCAPS_UBYTE4N   |
4764                           WINED3DDTCAPS_SHORT2N   |
4765                           WINED3DDTCAPS_SHORT4N;
4766         if (gl_info->supported[ARB_HALF_FLOAT_VERTEX])
4767         {
4768             caps->DeclTypes |= WINED3DDTCAPS_FLOAT16_2 |
4769                                WINED3DDTCAPS_FLOAT16_4;
4770         }
4771     }
4772     else
4773     {
4774         caps->DeclTypes = 0;
4775     }
4776
4777     /* Set DirectDraw helper Caps */
4778     ckey_caps =                         WINEDDCKEYCAPS_DESTBLT              |
4779                                         WINEDDCKEYCAPS_SRCBLT;
4780     fx_caps =                           WINEDDFXCAPS_BLTALPHA               |
4781                                         WINEDDFXCAPS_BLTMIRRORLEFTRIGHT     |
4782                                         WINEDDFXCAPS_BLTMIRRORUPDOWN        |
4783                                         WINEDDFXCAPS_BLTROTATION90          |
4784                                         WINEDDFXCAPS_BLTSHRINKX             |
4785                                         WINEDDFXCAPS_BLTSHRINKXN            |
4786                                         WINEDDFXCAPS_BLTSHRINKY             |
4787                                         WINEDDFXCAPS_BLTSHRINKXN            |
4788                                         WINEDDFXCAPS_BLTSTRETCHX            |
4789                                         WINEDDFXCAPS_BLTSTRETCHXN           |
4790                                         WINEDDFXCAPS_BLTSTRETCHY            |
4791                                         WINEDDFXCAPS_BLTSTRETCHYN;
4792     blit_caps =                         WINEDDCAPS_BLT                      |
4793                                         WINEDDCAPS_BLTCOLORFILL             |
4794                                         WINEDDCAPS_BLTDEPTHFILL             |
4795                                         WINEDDCAPS_BLTSTRETCH               |
4796                                         WINEDDCAPS_CANBLTSYSMEM             |
4797                                         WINEDDCAPS_CANCLIP                  |
4798                                         WINEDDCAPS_CANCLIPSTRETCHED         |
4799                                         WINEDDCAPS_COLORKEY                 |
4800                                         WINEDDCAPS_COLORKEYHWASSIST         |
4801                                         WINEDDCAPS_ALIGNBOUNDARYSRC;
4802     pal_caps =                          WINEDDPCAPS_8BIT                    |
4803                                         WINEDDPCAPS_PRIMARYSURFACE;
4804
4805     /* Fill the ddraw caps structure */
4806     caps->DirectDrawCaps.Caps =         WINEDDCAPS_GDI                      |
4807                                         WINEDDCAPS_PALETTE                  |
4808                                         blit_caps;
4809     caps->DirectDrawCaps.Caps2 =        WINEDDCAPS2_CERTIFIED                |
4810                                         WINEDDCAPS2_NOPAGELOCKREQUIRED       |
4811                                         WINEDDCAPS2_PRIMARYGAMMA             |
4812                                         WINEDDCAPS2_WIDESURFACES             |
4813                                         WINEDDCAPS2_CANRENDERWINDOWED;
4814     caps->DirectDrawCaps.CKeyCaps =     ckey_caps;
4815     caps->DirectDrawCaps.FXCaps =       fx_caps;
4816     caps->DirectDrawCaps.PalCaps =      pal_caps;
4817     caps->DirectDrawCaps.SVBCaps =      blit_caps;
4818     caps->DirectDrawCaps.SVBCKeyCaps =  ckey_caps;
4819     caps->DirectDrawCaps.SVBFXCaps =    fx_caps;
4820     caps->DirectDrawCaps.VSBCaps =      blit_caps;
4821     caps->DirectDrawCaps.VSBCKeyCaps =  ckey_caps;
4822     caps->DirectDrawCaps.VSBFXCaps =    fx_caps;
4823     caps->DirectDrawCaps.SSBCaps =      blit_caps;
4824     caps->DirectDrawCaps.SSBCKeyCaps =  ckey_caps;
4825     caps->DirectDrawCaps.SSBFXCaps =    fx_caps;
4826
4827     caps->DirectDrawCaps.ddsCaps =      WINEDDSCAPS_ALPHA                   |
4828                                         WINEDDSCAPS_BACKBUFFER              |
4829                                         WINEDDSCAPS_FLIP                    |
4830                                         WINEDDSCAPS_FRONTBUFFER             |
4831                                         WINEDDSCAPS_OFFSCREENPLAIN          |
4832                                         WINEDDSCAPS_PALETTE                 |
4833                                         WINEDDSCAPS_PRIMARYSURFACE          |
4834                                         WINEDDSCAPS_SYSTEMMEMORY            |
4835                                         WINEDDSCAPS_VIDEOMEMORY             |
4836                                         WINEDDSCAPS_VISIBLE;
4837     caps->DirectDrawCaps.StrideAlign = DDRAW_PITCH_ALIGNMENT;
4838
4839     /* Set D3D caps if OpenGL is available. */
4840     if (adapter->opengl)
4841     {
4842         caps->DirectDrawCaps.ddsCaps |= WINEDDSCAPS_3DDEVICE                |
4843                                         WINEDDSCAPS_MIPMAP                  |
4844                                         WINEDDSCAPS_TEXTURE                 |
4845                                         WINEDDSCAPS_ZBUFFER;
4846         caps->DirectDrawCaps.Caps |=    WINEDDCAPS_3D;
4847     }
4848
4849     return WINED3D_OK;
4850 }
4851
4852 HRESULT CDECL wined3d_device_create(struct wined3d *wined3d, UINT adapter_idx, WINED3DDEVTYPE device_type,
4853         HWND focus_window, DWORD flags, IWineD3DDeviceParent *device_parent, IWineD3DDevice **device)
4854 {
4855     IWineD3DDeviceImpl *object;
4856     HRESULT hr;
4857
4858     TRACE("wined3d %p, adapter_idx %u, device_type %#x, focus_window %p, flags %#x, device_parent %p, device %p.\n",
4859             wined3d, adapter_idx, device_type, focus_window, flags, device_parent, device);
4860
4861     /* Validate the adapter number. If no adapters are available(no GL), ignore the adapter
4862      * number and create a device without a 3D adapter for 2D only operation. */
4863     if (wined3d->adapter_count && adapter_idx >= wined3d->adapter_count)
4864         return WINED3DERR_INVALIDCALL;
4865
4866     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4867     if (!object)
4868     {
4869         ERR("Failed to allocate device memory.\n");
4870         return E_OUTOFMEMORY;
4871     }
4872
4873     hr = device_init(object, wined3d, adapter_idx, device_type, focus_window, flags, device_parent);
4874     if (FAILED(hr))
4875     {
4876         WARN("Failed to initialize device, hr %#x.\n", hr);
4877         HeapFree(GetProcessHeap(), 0, object);
4878         return hr;
4879     }
4880
4881     TRACE("Created device %p.\n", object);
4882     *device = (IWineD3DDevice *)object;
4883
4884     IWineD3DDeviceParent_WineD3DDeviceCreated(device_parent, *device);
4885
4886     return WINED3D_OK;
4887 }
4888
4889 void * CDECL wined3d_get_parent(const struct wined3d *wined3d)
4890 {
4891     TRACE("wined3d %p.\n", wined3d);
4892
4893     return wined3d->parent;
4894 }
4895
4896 static void WINE_GLAPI invalid_func(const void *data)
4897 {
4898     ERR("Invalid vertex attribute function called\n");
4899     DebugBreak();
4900 }
4901
4902 static void WINE_GLAPI invalid_texcoord_func(GLenum unit, const void *data)
4903 {
4904     ERR("Invalid texcoord function called\n");
4905     DebugBreak();
4906 }
4907
4908 /* Helper functions for providing vertex data to opengl. The arrays are initialized based on
4909  * the extension detection and are used in drawStridedSlow
4910  */
4911 static void WINE_GLAPI position_d3dcolor(const void *data)
4912 {
4913     DWORD pos = *((const DWORD *)data);
4914
4915     FIXME("Add a test for fixed function position from d3dcolor type\n");
4916     glVertex4s(D3DCOLOR_B_R(pos),
4917                D3DCOLOR_B_G(pos),
4918                D3DCOLOR_B_B(pos),
4919                D3DCOLOR_B_A(pos));
4920 }
4921
4922 static void WINE_GLAPI position_float4(const void *data)
4923 {
4924     const GLfloat *pos = data;
4925
4926     if (pos[3] != 0.0f && pos[3] != 1.0f)
4927     {
4928         float w = 1.0f / pos[3];
4929
4930         glVertex4f(pos[0] * w, pos[1] * w, pos[2] * w, w);
4931     }
4932     else
4933     {
4934         glVertex3fv(pos);
4935     }
4936 }
4937
4938 static void WINE_GLAPI diffuse_d3dcolor(const void *data)
4939 {
4940     DWORD diffuseColor = *((const DWORD *)data);
4941
4942     glColor4ub(D3DCOLOR_B_R(diffuseColor),
4943                D3DCOLOR_B_G(diffuseColor),
4944                D3DCOLOR_B_B(diffuseColor),
4945                D3DCOLOR_B_A(diffuseColor));
4946 }
4947
4948 static void WINE_GLAPI specular_d3dcolor(const void *data)
4949 {
4950     DWORD specularColor = *((const DWORD *)data);
4951     GLbyte d[] = {D3DCOLOR_B_R(specularColor),
4952             D3DCOLOR_B_G(specularColor),
4953             D3DCOLOR_B_B(specularColor)};
4954
4955     specular_func_3ubv(d);
4956 }
4957
4958 static void WINE_GLAPI warn_no_specular_func(const void *data)
4959 {
4960     WARN("GL_EXT_secondary_color not supported\n");
4961 }
4962
4963 static void fillGLAttribFuncs(const struct wined3d_gl_info *gl_info)
4964 {
4965     position_funcs[WINED3D_FFP_EMIT_FLOAT1]      = invalid_func;
4966     position_funcs[WINED3D_FFP_EMIT_FLOAT2]      = invalid_func;
4967     position_funcs[WINED3D_FFP_EMIT_FLOAT3]      = (glAttribFunc)glVertex3fv;
4968     position_funcs[WINED3D_FFP_EMIT_FLOAT4]      = position_float4;
4969     position_funcs[WINED3D_FFP_EMIT_D3DCOLOR]    = position_d3dcolor;
4970     position_funcs[WINED3D_FFP_EMIT_UBYTE4]      = invalid_func;
4971     position_funcs[WINED3D_FFP_EMIT_SHORT2]      = invalid_func;
4972     position_funcs[WINED3D_FFP_EMIT_SHORT4]      = (glAttribFunc)glVertex2sv;
4973     position_funcs[WINED3D_FFP_EMIT_UBYTE4N]     = invalid_func;
4974     position_funcs[WINED3D_FFP_EMIT_SHORT2N]     = invalid_func;
4975     position_funcs[WINED3D_FFP_EMIT_SHORT4N]     = invalid_func;
4976     position_funcs[WINED3D_FFP_EMIT_USHORT2N]    = invalid_func;
4977     position_funcs[WINED3D_FFP_EMIT_USHORT4N]    = invalid_func;
4978     position_funcs[WINED3D_FFP_EMIT_UDEC3]       = invalid_func;
4979     position_funcs[WINED3D_FFP_EMIT_DEC3N]       = invalid_func;
4980     position_funcs[WINED3D_FFP_EMIT_FLOAT16_2]   = invalid_func;
4981     position_funcs[WINED3D_FFP_EMIT_FLOAT16_4]   = invalid_func;
4982
4983     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT1]       = invalid_func;
4984     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT2]       = invalid_func;
4985     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT3]       = (glAttribFunc)glColor3fv;
4986     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT4]       = (glAttribFunc)glColor4fv;
4987     diffuse_funcs[WINED3D_FFP_EMIT_D3DCOLOR]     = diffuse_d3dcolor;
4988     diffuse_funcs[WINED3D_FFP_EMIT_UBYTE4]       = invalid_func;
4989     diffuse_funcs[WINED3D_FFP_EMIT_SHORT2]       = invalid_func;
4990     diffuse_funcs[WINED3D_FFP_EMIT_SHORT4]       = invalid_func;
4991     diffuse_funcs[WINED3D_FFP_EMIT_UBYTE4N]      = (glAttribFunc)glColor4ubv;
4992     diffuse_funcs[WINED3D_FFP_EMIT_SHORT2N]      = invalid_func;
4993     diffuse_funcs[WINED3D_FFP_EMIT_SHORT4N]      = (glAttribFunc)glColor4sv;
4994     diffuse_funcs[WINED3D_FFP_EMIT_USHORT2N]     = invalid_func;
4995     diffuse_funcs[WINED3D_FFP_EMIT_USHORT4N]     = (glAttribFunc)glColor4usv;
4996     diffuse_funcs[WINED3D_FFP_EMIT_UDEC3]        = invalid_func;
4997     diffuse_funcs[WINED3D_FFP_EMIT_DEC3N]        = invalid_func;
4998     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT16_2]    = invalid_func;
4999     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT16_4]    = invalid_func;
5000
5001     /* No 4 component entry points here */
5002     specular_funcs[WINED3D_FFP_EMIT_FLOAT1]      = invalid_func;
5003     specular_funcs[WINED3D_FFP_EMIT_FLOAT2]      = invalid_func;
5004     if (gl_info->supported[EXT_SECONDARY_COLOR])
5005     {
5006         specular_funcs[WINED3D_FFP_EMIT_FLOAT3]  = (glAttribFunc)GL_EXTCALL(glSecondaryColor3fvEXT);
5007     }
5008     else
5009     {
5010         specular_funcs[WINED3D_FFP_EMIT_FLOAT3]  = warn_no_specular_func;
5011     }
5012     specular_funcs[WINED3D_FFP_EMIT_FLOAT4]      = invalid_func;
5013     if (gl_info->supported[EXT_SECONDARY_COLOR])
5014     {
5015         specular_func_3ubv = (glAttribFunc)GL_EXTCALL(glSecondaryColor3ubvEXT);
5016         specular_funcs[WINED3D_FFP_EMIT_D3DCOLOR] = specular_d3dcolor;
5017     }
5018     else
5019     {
5020         specular_funcs[WINED3D_FFP_EMIT_D3DCOLOR] = warn_no_specular_func;
5021     }
5022     specular_funcs[WINED3D_FFP_EMIT_UBYTE4]      = invalid_func;
5023     specular_funcs[WINED3D_FFP_EMIT_SHORT2]      = invalid_func;
5024     specular_funcs[WINED3D_FFP_EMIT_SHORT4]      = invalid_func;
5025     specular_funcs[WINED3D_FFP_EMIT_UBYTE4N]     = invalid_func;
5026     specular_funcs[WINED3D_FFP_EMIT_SHORT2N]     = invalid_func;
5027     specular_funcs[WINED3D_FFP_EMIT_SHORT4N]     = invalid_func;
5028     specular_funcs[WINED3D_FFP_EMIT_USHORT2N]    = invalid_func;
5029     specular_funcs[WINED3D_FFP_EMIT_USHORT4N]    = invalid_func;
5030     specular_funcs[WINED3D_FFP_EMIT_UDEC3]       = invalid_func;
5031     specular_funcs[WINED3D_FFP_EMIT_DEC3N]       = invalid_func;
5032     specular_funcs[WINED3D_FFP_EMIT_FLOAT16_2]   = invalid_func;
5033     specular_funcs[WINED3D_FFP_EMIT_FLOAT16_4]   = invalid_func;
5034
5035     /* Only 3 component entry points here. Test how others behave. Float4 normals are used
5036      * by one of our tests, trying to pass it to the pixel shader, which fails on Windows.
5037      */
5038     normal_funcs[WINED3D_FFP_EMIT_FLOAT1]         = invalid_func;
5039     normal_funcs[WINED3D_FFP_EMIT_FLOAT2]         = invalid_func;
5040     normal_funcs[WINED3D_FFP_EMIT_FLOAT3]         = (glAttribFunc)glNormal3fv;
5041     normal_funcs[WINED3D_FFP_EMIT_FLOAT4]         = (glAttribFunc)glNormal3fv; /* Just ignore the 4th value */
5042     normal_funcs[WINED3D_FFP_EMIT_D3DCOLOR]       = invalid_func;
5043     normal_funcs[WINED3D_FFP_EMIT_UBYTE4]         = invalid_func;
5044     normal_funcs[WINED3D_FFP_EMIT_SHORT2]         = invalid_func;
5045     normal_funcs[WINED3D_FFP_EMIT_SHORT4]         = invalid_func;
5046     normal_funcs[WINED3D_FFP_EMIT_UBYTE4N]        = invalid_func;
5047     normal_funcs[WINED3D_FFP_EMIT_SHORT2N]        = invalid_func;
5048     normal_funcs[WINED3D_FFP_EMIT_SHORT4N]        = invalid_func;
5049     normal_funcs[WINED3D_FFP_EMIT_USHORT2N]       = invalid_func;
5050     normal_funcs[WINED3D_FFP_EMIT_USHORT4N]       = invalid_func;
5051     normal_funcs[WINED3D_FFP_EMIT_UDEC3]          = invalid_func;
5052     normal_funcs[WINED3D_FFP_EMIT_DEC3N]          = invalid_func;
5053     normal_funcs[WINED3D_FFP_EMIT_FLOAT16_2]      = invalid_func;
5054     normal_funcs[WINED3D_FFP_EMIT_FLOAT16_4]      = invalid_func;
5055
5056     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT1]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord1fvARB);
5057     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT2]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2fvARB);
5058     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT3]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord3fvARB);
5059     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT4]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4fvARB);
5060     multi_texcoord_funcs[WINED3D_FFP_EMIT_D3DCOLOR]  = invalid_texcoord_func;
5061     multi_texcoord_funcs[WINED3D_FFP_EMIT_UBYTE4]    = invalid_texcoord_func;
5062     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT2]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2svARB);
5063     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT4]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4svARB);
5064     multi_texcoord_funcs[WINED3D_FFP_EMIT_UBYTE4N]   = invalid_texcoord_func;
5065     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT2N]   = invalid_texcoord_func;
5066     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT4N]   = invalid_texcoord_func;
5067     multi_texcoord_funcs[WINED3D_FFP_EMIT_USHORT2N]  = invalid_texcoord_func;
5068     multi_texcoord_funcs[WINED3D_FFP_EMIT_USHORT4N]  = invalid_texcoord_func;
5069     multi_texcoord_funcs[WINED3D_FFP_EMIT_UDEC3]     = invalid_texcoord_func;
5070     multi_texcoord_funcs[WINED3D_FFP_EMIT_DEC3N]     = invalid_texcoord_func;
5071     if (gl_info->supported[NV_HALF_FLOAT])
5072     {
5073         /* Not supported by ARB_HALF_FLOAT_VERTEX, so check for NV_HALF_FLOAT */
5074         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_2] = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2hvNV);
5075         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_4] = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4hvNV);
5076     } else {
5077         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_2] = invalid_texcoord_func;
5078         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_4] = invalid_texcoord_func;
5079     }
5080 }
5081
5082 /* Do not call while under the GL lock. */
5083 static BOOL InitAdapters(struct wined3d *wined3d)
5084 {
5085     static HMODULE mod_gl;
5086     BOOL ret;
5087     int ps_selected_mode, vs_selected_mode;
5088
5089     /* No need to hold any lock. The calling library makes sure only one thread calls
5090      * wined3d simultaneously
5091      */
5092
5093     TRACE("Initializing adapters\n");
5094
5095     if(!mod_gl) {
5096 #ifdef USE_WIN32_OPENGL
5097 #define USE_GL_FUNC(pfn) pfn = (void*)GetProcAddress(mod_gl, #pfn);
5098         mod_gl = LoadLibraryA("opengl32.dll");
5099         if(!mod_gl) {
5100             ERR("Can't load opengl32.dll!\n");
5101             goto nogl_adapter;
5102         }
5103 #else
5104 #define USE_GL_FUNC(pfn) pfn = (void*)pwglGetProcAddress(#pfn);
5105         /* To bypass the opengl32 thunks load wglGetProcAddress from gdi32 (glXGetProcAddress wrapper) instead of opengl32's */
5106         mod_gl = GetModuleHandleA("gdi32.dll");
5107 #endif
5108     }
5109
5110 /* Load WGL core functions from opengl32.dll */
5111 #define USE_WGL_FUNC(pfn) p##pfn = (void*)GetProcAddress(mod_gl, #pfn);
5112     WGL_FUNCS_GEN;
5113 #undef USE_WGL_FUNC
5114
5115     if(!pwglGetProcAddress) {
5116         ERR("Unable to load wglGetProcAddress!\n");
5117         goto nogl_adapter;
5118     }
5119
5120 /* Dynamically load all GL core functions */
5121     GL_FUNCS_GEN;
5122 #undef USE_GL_FUNC
5123
5124     /* Load glFinish and glFlush from opengl32.dll even if we're not using WIN32 opengl
5125      * otherwise because we have to use winex11.drv's override
5126      */
5127 #ifdef USE_WIN32_OPENGL
5128     wglFinish = (void*)GetProcAddress(mod_gl, "glFinish");
5129     wglFlush = (void*)GetProcAddress(mod_gl, "glFlush");
5130 #else
5131     wglFinish = (void*)pwglGetProcAddress("wglFinish");
5132     wglFlush = (void*)pwglGetProcAddress("wglFlush");
5133 #endif
5134
5135     glEnableWINE = glEnable;
5136     glDisableWINE = glDisable;
5137
5138     /* For now only one default adapter */
5139     {
5140         struct wined3d_adapter *adapter = &wined3d->adapters[0];
5141         const struct wined3d_gl_info *gl_info = &adapter->gl_info;
5142         struct wined3d_fake_gl_ctx fake_gl_ctx = {0};
5143         struct wined3d_pixel_format *cfgs;
5144         int iPixelFormat;
5145         int res;
5146         int i;
5147         DISPLAY_DEVICEW DisplayDevice;
5148         HDC hdc;
5149
5150         TRACE("Initializing default adapter\n");
5151         adapter->ordinal = 0;
5152         adapter->monitorPoint.x = -1;
5153         adapter->monitorPoint.y = -1;
5154
5155         if (!AllocateLocallyUniqueId(&adapter->luid))
5156         {
5157             DWORD err = GetLastError();
5158             ERR("Failed to set adapter LUID (%#x).\n", err);
5159             goto nogl_adapter;
5160         }
5161         TRACE("Allocated LUID %08x:%08x for adapter.\n",
5162                 adapter->luid.HighPart, adapter->luid.LowPart);
5163
5164         if (!WineD3D_CreateFakeGLContext(&fake_gl_ctx))
5165         {
5166             ERR("Failed to get a gl context for default adapter\n");
5167             goto nogl_adapter;
5168         }
5169
5170         ret = IWineD3DImpl_FillGLCaps(adapter);
5171         if(!ret) {
5172             ERR("Failed to initialize gl caps for default adapter\n");
5173             WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
5174             goto nogl_adapter;
5175         }
5176         ret = initPixelFormats(&adapter->gl_info, adapter->driver_info.vendor);
5177         if(!ret) {
5178             ERR("Failed to init gl formats\n");
5179             WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
5180             goto nogl_adapter;
5181         }
5182
5183         hdc = fake_gl_ctx.dc;
5184
5185         adapter->TextureRam = adapter->driver_info.vidmem;
5186         adapter->UsedTextureRam = 0;
5187         TRACE("Emulating %dMB of texture ram\n", adapter->TextureRam/(1024*1024));
5188
5189         /* Initialize the Adapter's DeviceName which is required for ChangeDisplaySettings and friends */
5190         DisplayDevice.cb = sizeof(DisplayDevice);
5191         EnumDisplayDevicesW(NULL, 0 /* Adapter 0 = iDevNum 0 */, &DisplayDevice, 0);
5192         TRACE("DeviceName: %s\n", debugstr_w(DisplayDevice.DeviceName));
5193         strcpyW(adapter->DeviceName, DisplayDevice.DeviceName);
5194
5195         if (gl_info->supported[WGL_ARB_PIXEL_FORMAT])
5196         {
5197             int attribute;
5198             int attribs[11];
5199             int values[11];
5200             int nAttribs = 0;
5201
5202             attribute = WGL_NUMBER_PIXEL_FORMATS_ARB;
5203             GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, 0, 0, 1, &attribute, &adapter->nCfgs));
5204
5205             adapter->cfgs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, adapter->nCfgs * sizeof(*adapter->cfgs));
5206             cfgs = adapter->cfgs;
5207             attribs[nAttribs++] = WGL_RED_BITS_ARB;
5208             attribs[nAttribs++] = WGL_GREEN_BITS_ARB;
5209             attribs[nAttribs++] = WGL_BLUE_BITS_ARB;
5210             attribs[nAttribs++] = WGL_ALPHA_BITS_ARB;
5211             attribs[nAttribs++] = WGL_COLOR_BITS_ARB;
5212             attribs[nAttribs++] = WGL_DEPTH_BITS_ARB;
5213             attribs[nAttribs++] = WGL_STENCIL_BITS_ARB;
5214             attribs[nAttribs++] = WGL_DRAW_TO_WINDOW_ARB;
5215             attribs[nAttribs++] = WGL_PIXEL_TYPE_ARB;
5216             attribs[nAttribs++] = WGL_DOUBLE_BUFFER_ARB;
5217             attribs[nAttribs++] = WGL_AUX_BUFFERS_ARB;
5218
5219             for (iPixelFormat=1; iPixelFormat <= adapter->nCfgs; ++iPixelFormat)
5220             {
5221                 res = GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, nAttribs, attribs, values));
5222
5223                 if(!res)
5224                     continue;
5225
5226                 /* Cache the pixel format */
5227                 cfgs->iPixelFormat = iPixelFormat;
5228                 cfgs->redSize = values[0];
5229                 cfgs->greenSize = values[1];
5230                 cfgs->blueSize = values[2];
5231                 cfgs->alphaSize = values[3];
5232                 cfgs->colorSize = values[4];
5233                 cfgs->depthSize = values[5];
5234                 cfgs->stencilSize = values[6];
5235                 cfgs->windowDrawable = values[7];
5236                 cfgs->iPixelType = values[8];
5237                 cfgs->doubleBuffer = values[9];
5238                 cfgs->auxBuffers = values[10];
5239
5240                 cfgs->numSamples = 0;
5241                 /* Check multisample support */
5242                 if (gl_info->supported[ARB_MULTISAMPLE])
5243                 {
5244                     int attrib[2] = {WGL_SAMPLE_BUFFERS_ARB, WGL_SAMPLES_ARB};
5245                     int value[2];
5246                     if(GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, 2, attrib, value))) {
5247                         /* value[0] = WGL_SAMPLE_BUFFERS_ARB which tells whether multisampling is supported.
5248                         * value[1] = number of multi sample buffers*/
5249                         if(value[0])
5250                             cfgs->numSamples = value[1];
5251                     }
5252                 }
5253
5254                 TRACE("iPixelFormat=%d, iPixelType=%#x, doubleBuffer=%d, RGBA=%d/%d/%d/%d, "
5255                         "depth=%d, stencil=%d, samples=%d, windowDrawable=%d\n",
5256                         cfgs->iPixelFormat, cfgs->iPixelType, cfgs->doubleBuffer,
5257                         cfgs->redSize, cfgs->greenSize, cfgs->blueSize, cfgs->alphaSize,
5258                         cfgs->depthSize, cfgs->stencilSize, cfgs->numSamples, cfgs->windowDrawable);
5259                 cfgs++;
5260             }
5261         }
5262         else
5263         {
5264             int nCfgs = DescribePixelFormat(hdc, 0, 0, 0);
5265             adapter->cfgs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nCfgs * sizeof(*adapter->cfgs));
5266             adapter->nCfgs = 0; /* We won't accept all formats e.g. software accelerated ones will be skipped */
5267
5268             cfgs = adapter->cfgs;
5269             for(iPixelFormat=1; iPixelFormat<=nCfgs; iPixelFormat++)
5270             {
5271                 PIXELFORMATDESCRIPTOR ppfd;
5272
5273                 res = DescribePixelFormat(hdc, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &ppfd);
5274                 if(!res)
5275                     continue;
5276
5277                 /* We only want HW acceleration using an OpenGL ICD driver.
5278                  * PFD_GENERIC_FORMAT = slow opengl 1.1 gdi software rendering
5279                  * PFD_GENERIC_ACCELERATED = partial hw acceleration using a MCD driver (e.g. 3dfx minigl)
5280                  */
5281                 if(ppfd.dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED))
5282                 {
5283                     TRACE("Skipping iPixelFormat=%d because it isn't ICD accelerated\n", iPixelFormat);
5284                     continue;
5285                 }
5286
5287                 cfgs->iPixelFormat = iPixelFormat;
5288                 cfgs->redSize = ppfd.cRedBits;
5289                 cfgs->greenSize = ppfd.cGreenBits;
5290                 cfgs->blueSize = ppfd.cBlueBits;
5291                 cfgs->alphaSize = ppfd.cAlphaBits;
5292                 cfgs->colorSize = ppfd.cColorBits;
5293                 cfgs->depthSize = ppfd.cDepthBits;
5294                 cfgs->stencilSize = ppfd.cStencilBits;
5295                 cfgs->windowDrawable = (ppfd.dwFlags & PFD_DRAW_TO_WINDOW) ? 1 : 0;
5296                 cfgs->iPixelType = (ppfd.iPixelType == PFD_TYPE_RGBA) ? WGL_TYPE_RGBA_ARB : WGL_TYPE_COLORINDEX_ARB;
5297                 cfgs->doubleBuffer = (ppfd.dwFlags & PFD_DOUBLEBUFFER) ? 1 : 0;
5298                 cfgs->auxBuffers = ppfd.cAuxBuffers;
5299                 cfgs->numSamples = 0;
5300
5301                 TRACE("iPixelFormat=%d, iPixelType=%#x, doubleBuffer=%d, RGBA=%d/%d/%d/%d, "
5302                         "depth=%d, stencil=%d, windowDrawable=%d\n",
5303                         cfgs->iPixelFormat, cfgs->iPixelType, cfgs->doubleBuffer,
5304                         cfgs->redSize, cfgs->greenSize, cfgs->blueSize, cfgs->alphaSize,
5305                         cfgs->depthSize, cfgs->stencilSize, cfgs->windowDrawable);
5306                 cfgs++;
5307                 adapter->nCfgs++;
5308             }
5309
5310             /* Yikes we haven't found any suitable formats. This should only happen in case of GDI software rendering which we can't use anyway as its 3D functionality is very, very limited */
5311             if(!adapter->nCfgs)
5312             {
5313                 ERR("Disabling Direct3D because no hardware accelerated pixel formats have been found!\n");
5314
5315                 WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
5316                 HeapFree(GetProcessHeap(), 0, adapter->cfgs);
5317                 goto nogl_adapter;
5318             }
5319         }
5320
5321         /* D16, D24X8 and D24S8 are common depth / depth+stencil formats. All drivers support them though this doesn't
5322          * mean that the format is offered in hardware. For instance Geforce8 cards don't have offer D16 in hardware
5323          * but just fake it using D24(X8?) which is fine. D3D also allows that.
5324          * Some display drivers (i915 on Linux) only report mixed depth+stencil formats like D24S8. MSDN clearly mentions
5325          * that only on lockable formats (e.g. D16_locked) the bit order is guaranteed and that on other formats the
5326          * driver is allowed to consume more bits EXCEPT for stencil bits.
5327          *
5328          * Mark an adapter with this broken stencil behavior.
5329          */
5330         adapter->brokenStencil = TRUE;
5331         for (i = 0, cfgs = adapter->cfgs; i < adapter->nCfgs; ++i)
5332         {
5333             /* Nearly all drivers offer depth formats without stencil, only on i915 this if-statement won't be entered. */
5334             if(cfgs[i].depthSize && !cfgs[i].stencilSize) {
5335                 adapter->brokenStencil = FALSE;
5336                 break;
5337             }
5338         }
5339
5340         WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
5341
5342         select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
5343         fillGLAttribFuncs(&adapter->gl_info);
5344         adapter->opengl = TRUE;
5345     }
5346     wined3d->adapter_count = 1;
5347     TRACE("%u adapters successfully initialized.\n", wined3d->adapter_count);
5348
5349     return TRUE;
5350
5351 nogl_adapter:
5352     /* Initialize an adapter for ddraw-only memory counting */
5353     memset(wined3d->adapters, 0, sizeof(wined3d->adapters));
5354     wined3d->adapters[0].ordinal = 0;
5355     wined3d->adapters[0].opengl = FALSE;
5356     wined3d->adapters[0].monitorPoint.x = -1;
5357     wined3d->adapters[0].monitorPoint.y = -1;
5358
5359     wined3d->adapters[0].driver_info.name = "Display";
5360     wined3d->adapters[0].driver_info.description = "WineD3D DirectDraw Emulation";
5361     if (wined3d_settings.emulated_textureram)
5362         wined3d->adapters[0].TextureRam = wined3d_settings.emulated_textureram;
5363     else
5364         wined3d->adapters[0].TextureRam = 8 * 1024 * 1024; /* This is plenty for a DDraw-only card */
5365
5366     initPixelFormatsNoGL(&wined3d->adapters[0].gl_info);
5367
5368     wined3d->adapter_count = 1;
5369     return FALSE;
5370 }
5371
5372 static void STDMETHODCALLTYPE wined3d_null_wined3d_object_destroyed(void *parent) {}
5373
5374 const struct wined3d_parent_ops wined3d_null_parent_ops =
5375 {
5376     wined3d_null_wined3d_object_destroyed,
5377 };
5378
5379 /* Do not call while under the GL lock. */
5380 HRESULT wined3d_init(struct wined3d *wined3d, UINT version, void *parent)
5381 {
5382     wined3d->dxVersion = version;
5383     wined3d->ref = 1;
5384     wined3d->parent = parent;
5385
5386     if (!InitAdapters(wined3d))
5387     {
5388         WARN("Failed to initialize adapters.\n");
5389         if (version > 7)
5390         {
5391             MESSAGE("Direct3D%u is not available without OpenGL.\n", version);
5392             return E_FAIL;
5393         }
5394     }
5395
5396     return WINED3D_OK;
5397 }