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