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