jscript: Use prototype for builtin Date properties.
[wine] / dlls / ddraw / ddraw.c
1 /*
2  * Copyright 1997-2000 Marcus Meissner
3  * Copyright 1998-2000 Lionel Ulmer
4  * Copyright 2000-2001 TransGaming Technologies Inc.
5  * Copyright 2006 Stefan Dösinger
6  * Copyright 2008 Denver Gingerich
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include "ddraw_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
29
30 /* Device identifier. Don't relay it to WineD3D */
31 static const DDDEVICEIDENTIFIER2 deviceidentifier =
32 {
33     "display",
34     "DirectDraw HAL",
35     { { 0x00010001, 0x00010001 } },
36     0, 0, 0, 0,
37     /* a8373c10-7ac4-4deb-849a-009844d08b2d */
38     {0xa8373c10,0x7ac4,0x4deb, {0x84,0x9a,0x00,0x98,0x44,0xd0,0x8b,0x2d}},
39     0
40 };
41
42 static struct enum_device_entry
43 {
44     char interface_name[100];
45     char device_name[100];
46     const GUID *device_guid;
47 } device_list7[] =
48 {
49     /* T&L HAL device */
50     {
51         "WINE Direct3D7 Hardware Transform and Lighting acceleration using WineD3D",
52         "Wine D3D7 T&L HAL",
53         &IID_IDirect3DTnLHalDevice,
54     },
55
56     /* HAL device */
57     {
58         "WINE Direct3D7 Hardware acceleration using WineD3D",
59         "Direct3D HAL",
60         &IID_IDirect3DHALDevice,
61     },
62
63     /* RGB device */
64     {
65         "WINE Direct3D7 RGB Software Emulation using WineD3D",
66         "Wine D3D7 RGB",
67         &IID_IDirect3DRGBDevice,
68     },
69 };
70
71 static void STDMETHODCALLTYPE ddraw_null_wined3d_object_destroyed(void *parent) {}
72
73 const struct wined3d_parent_ops ddraw_null_wined3d_parent_ops =
74 {
75     ddraw_null_wined3d_object_destroyed,
76 };
77
78 static inline struct ddraw *impl_from_IDirectDraw(IDirectDraw *iface)
79 {
80     return CONTAINING_RECORD(iface, struct ddraw, IDirectDraw_iface);
81 }
82
83 static inline struct ddraw *impl_from_IDirectDraw2(IDirectDraw2 *iface)
84 {
85     return CONTAINING_RECORD(iface, struct ddraw, IDirectDraw2_iface);
86 }
87
88 static inline struct ddraw *impl_from_IDirectDraw4(IDirectDraw4 *iface)
89 {
90     return CONTAINING_RECORD(iface, struct ddraw, IDirectDraw4_iface);
91 }
92
93 static inline struct ddraw *impl_from_IDirectDraw7(IDirectDraw7 *iface)
94 {
95     return CONTAINING_RECORD(iface, struct ddraw, IDirectDraw7_iface);
96 }
97
98 static inline struct ddraw *impl_from_IDirect3D(IDirect3D *iface)
99 {
100     return CONTAINING_RECORD(iface, struct ddraw, IDirect3D_iface);
101 }
102
103 static inline struct ddraw *impl_from_IDirect3D2(IDirect3D2 *iface)
104 {
105     return CONTAINING_RECORD(iface, struct ddraw, IDirect3D2_iface);
106 }
107
108 static inline struct ddraw *impl_from_IDirect3D3(IDirect3D3 *iface)
109 {
110     return CONTAINING_RECORD(iface, struct ddraw, IDirect3D3_iface);
111 }
112
113 static inline struct ddraw *impl_from_IDirect3D7(IDirect3D7 *iface)
114 {
115     return CONTAINING_RECORD(iface, struct ddraw, IDirect3D7_iface);
116 }
117
118 /*****************************************************************************
119  * IUnknown Methods
120  *****************************************************************************/
121
122 /*****************************************************************************
123  * IDirectDraw7::QueryInterface
124  *
125  * Queries different interfaces of the DirectDraw object. It can return
126  * IDirectDraw interfaces in version 1, 2, 4 and 7, and IDirect3D interfaces
127  * in version 1, 2, 3 and 7. An IDirect3DDevice can be created with this
128  * method.
129  * The returned interface is AddRef()-ed before it's returned
130  *
131  * Used for version 1, 2, 4 and 7
132  *
133  * Params:
134  *  refiid: Interface ID asked for
135  *  obj: Used to return the interface pointer
136  *
137  * Returns:
138  *  S_OK if an interface was found
139  *  E_NOINTERFACE if the requested interface wasn't found
140  *
141  *****************************************************************************/
142 static HRESULT WINAPI ddraw7_QueryInterface(IDirectDraw7 *iface, REFIID refiid, void **obj)
143 {
144     struct ddraw *This = impl_from_IDirectDraw7(iface);
145
146     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(refiid), obj);
147
148     /* Can change surface impl type */
149     wined3d_mutex_lock();
150
151     /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
152     *obj = NULL;
153
154     if(!refiid)
155     {
156         wined3d_mutex_unlock();
157         return DDERR_INVALIDPARAMS;
158     }
159
160     /* Check DirectDraw Interfaces */
161     if ( IsEqualGUID( &IID_IUnknown, refiid ) ||
162          IsEqualGUID( &IID_IDirectDraw7, refiid ) )
163     {
164         *obj = &This->IDirectDraw7_iface;
165         TRACE("(%p) Returning IDirectDraw7 interface at %p\n", This, *obj);
166     }
167     else if ( IsEqualGUID( &IID_IDirectDraw4, refiid ) )
168     {
169         *obj = &This->IDirectDraw4_iface;
170         TRACE("(%p) Returning IDirectDraw4 interface at %p\n", This, *obj);
171     }
172     else if ( IsEqualGUID( &IID_IDirectDraw3, refiid ) )
173     {
174         /* This Interface exists in ddrawex.dll, it is implemented in a wrapper */
175         WARN("IDirectDraw3 is not valid in ddraw.dll\n");
176         *obj = NULL;
177         wined3d_mutex_unlock();
178         return E_NOINTERFACE;
179     }
180     else if ( IsEqualGUID( &IID_IDirectDraw2, refiid ) )
181     {
182         *obj = &This->IDirectDraw2_iface;
183         TRACE("(%p) Returning IDirectDraw2 interface at %p\n", This, *obj);
184     }
185     else if ( IsEqualGUID( &IID_IDirectDraw, refiid ) )
186     {
187         *obj = &This->IDirectDraw_iface;
188         TRACE("(%p) Returning IDirectDraw interface at %p\n", This, *obj);
189     }
190
191     /* Direct3D
192      * The refcount unit test revealed that an IDirect3D7 interface can only be queried
193      * from a DirectDraw object that was created as an IDirectDraw7 interface. No idea
194      * who had this idea and why. The older interfaces can query and IDirect3D version
195      * because they are all created as IDirectDraw(1). This isn't really crucial behavior,
196      * and messy to implement with the common creation function, so it has been left out here.
197      */
198     else if ( IsEqualGUID( &IID_IDirect3D  , refiid ) ||
199               IsEqualGUID( &IID_IDirect3D2 , refiid ) ||
200               IsEqualGUID( &IID_IDirect3D3 , refiid ) ||
201               IsEqualGUID( &IID_IDirect3D7 , refiid ) )
202     {
203         /* Check the surface implementation */
204         if (DefaultSurfaceType != WINED3D_SURFACE_TYPE_OPENGL)
205         {
206             WARN("The app requests a Direct3D interface, but non-opengl surfaces where set in winecfg\n");
207             /* Do not abort here, only reject 3D Device creation */
208         }
209
210         if ( IsEqualGUID( &IID_IDirect3D  , refiid ) )
211         {
212             This->d3dversion = 1;
213             *obj = &This->IDirect3D_iface;
214             TRACE(" returning Direct3D interface at %p.\n", *obj);
215         }
216         else if ( IsEqualGUID( &IID_IDirect3D2  , refiid ) )
217         {
218             This->d3dversion = 2;
219             *obj = &This->IDirect3D2_iface;
220             TRACE(" returning Direct3D2 interface at %p.\n", *obj);
221         }
222         else if ( IsEqualGUID( &IID_IDirect3D3  , refiid ) )
223         {
224             This->d3dversion = 3;
225             *obj = &This->IDirect3D3_iface;
226             TRACE(" returning Direct3D3 interface at %p.\n", *obj);
227         }
228         else if(IsEqualGUID( &IID_IDirect3D7  , refiid ))
229         {
230             This->d3dversion = 7;
231             *obj = &This->IDirect3D7_iface;
232             TRACE(" returning Direct3D7 interface at %p.\n", *obj);
233         }
234     }
235     /* Unknown interface */
236     else
237     {
238         ERR("(%p)->(%s, %p): No interface found\n", This, debugstr_guid(refiid), obj);
239         wined3d_mutex_unlock();
240         return E_NOINTERFACE;
241     }
242
243     IUnknown_AddRef( (IUnknown *) *obj );
244     wined3d_mutex_unlock();
245
246     return S_OK;
247 }
248
249 static HRESULT WINAPI ddraw4_QueryInterface(IDirectDraw4 *iface, REFIID riid, void **object)
250 {
251     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
252
253     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
254
255     return ddraw7_QueryInterface(&ddraw->IDirectDraw7_iface, riid, object);
256 }
257
258 static HRESULT WINAPI ddraw2_QueryInterface(IDirectDraw2 *iface, REFIID riid, void **object)
259 {
260     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
261
262     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
263
264     return ddraw7_QueryInterface(&ddraw->IDirectDraw7_iface, riid, object);
265 }
266
267 static HRESULT WINAPI ddraw1_QueryInterface(IDirectDraw *iface, REFIID riid, void **object)
268 {
269     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
270
271     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
272
273     return ddraw7_QueryInterface(&ddraw->IDirectDraw7_iface, riid, object);
274 }
275
276 static HRESULT WINAPI d3d7_QueryInterface(IDirect3D7 *iface, REFIID riid, void **object)
277 {
278     struct ddraw *ddraw = impl_from_IDirect3D7(iface);
279
280     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
281
282     return ddraw7_QueryInterface(&ddraw->IDirectDraw7_iface, riid, object);
283 }
284
285 static HRESULT WINAPI d3d3_QueryInterface(IDirect3D3 *iface, REFIID riid, void **object)
286 {
287     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
288
289     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
290
291     return ddraw7_QueryInterface(&ddraw->IDirectDraw7_iface, riid, object);
292 }
293
294 static HRESULT WINAPI d3d2_QueryInterface(IDirect3D2 *iface, REFIID riid, void **object)
295 {
296     struct ddraw *ddraw = impl_from_IDirect3D2(iface);
297
298     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
299
300     return ddraw7_QueryInterface(&ddraw->IDirectDraw7_iface, riid, object);
301 }
302
303 static HRESULT WINAPI d3d1_QueryInterface(IDirect3D *iface, REFIID riid, void **object)
304 {
305     struct ddraw *ddraw = impl_from_IDirect3D(iface);
306
307     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
308
309     return ddraw7_QueryInterface(&ddraw->IDirectDraw7_iface, riid, object);
310 }
311
312 /*****************************************************************************
313  * IDirectDraw7::AddRef
314  *
315  * Increases the interfaces refcount, basically
316  *
317  * DDraw refcounting is a bit tricky. The different DirectDraw interface
318  * versions have individual refcounts, but the IDirect3D interfaces do not.
319  * All interfaces are from one object, that means calling QueryInterface on an
320  * IDirectDraw7 interface for an IDirectDraw4 interface does not create a new
321  * ddraw object.
322  *
323  * That means all AddRef and Release implementations of IDirectDrawX work
324  * with their own counter, and IDirect3DX::AddRef thunk to IDirectDraw (1),
325  * except of IDirect3D7 which thunks to IDirectDraw7
326  *
327  * Returns: The new refcount
328  *
329  *****************************************************************************/
330 static ULONG WINAPI ddraw7_AddRef(IDirectDraw7 *iface)
331 {
332     struct ddraw *This = impl_from_IDirectDraw7(iface);
333     ULONG ref = InterlockedIncrement(&This->ref7);
334
335     TRACE("%p increasing refcount to %u.\n", This, ref);
336
337     if(ref == 1) InterlockedIncrement(&This->numIfaces);
338
339     return ref;
340 }
341
342 static ULONG WINAPI ddraw4_AddRef(IDirectDraw4 *iface)
343 {
344     struct ddraw *This = impl_from_IDirectDraw4(iface);
345     ULONG ref = InterlockedIncrement(&This->ref4);
346
347     TRACE("%p increasing refcount to %u.\n", This, ref);
348
349     if (ref == 1) InterlockedIncrement(&This->numIfaces);
350
351     return ref;
352 }
353
354 static ULONG WINAPI ddraw2_AddRef(IDirectDraw2 *iface)
355 {
356     struct ddraw *This = impl_from_IDirectDraw2(iface);
357     ULONG ref = InterlockedIncrement(&This->ref2);
358
359     TRACE("%p increasing refcount to %u.\n", This, ref);
360
361     if (ref == 1) InterlockedIncrement(&This->numIfaces);
362
363     return ref;
364 }
365
366 static ULONG WINAPI ddraw1_AddRef(IDirectDraw *iface)
367 {
368     struct ddraw *This = impl_from_IDirectDraw(iface);
369     ULONG ref = InterlockedIncrement(&This->ref1);
370
371     TRACE("%p increasing refcount to %u.\n", This, ref);
372
373     if (ref == 1) InterlockedIncrement(&This->numIfaces);
374
375     return ref;
376 }
377
378 static ULONG WINAPI d3d7_AddRef(IDirect3D7 *iface)
379 {
380     struct ddraw *This = impl_from_IDirect3D7(iface);
381
382     TRACE("iface %p.\n", iface);
383
384     return ddraw7_AddRef(&This->IDirectDraw7_iface);
385 }
386
387 static ULONG WINAPI d3d3_AddRef(IDirect3D3 *iface)
388 {
389     struct ddraw *This = impl_from_IDirect3D3(iface);
390
391     TRACE("iface %p.\n", iface);
392
393     return ddraw1_AddRef(&This->IDirectDraw_iface);
394 }
395
396 static ULONG WINAPI d3d2_AddRef(IDirect3D2 *iface)
397 {
398     struct ddraw *This = impl_from_IDirect3D2(iface);
399
400     TRACE("iface %p.\n", iface);
401
402     return ddraw1_AddRef(&This->IDirectDraw_iface);
403 }
404
405 static ULONG WINAPI d3d1_AddRef(IDirect3D *iface)
406 {
407     struct ddraw *This = impl_from_IDirect3D(iface);
408
409     TRACE("iface %p.\n", iface);
410
411     return ddraw1_AddRef(&This->IDirectDraw_iface);
412 }
413
414 void ddraw_destroy_swapchain(struct ddraw *ddraw)
415 {
416     TRACE("Destroying the swapchain.\n");
417
418     wined3d_swapchain_decref(ddraw->wined3d_swapchain);
419     ddraw->wined3d_swapchain = NULL;
420
421     if (DefaultSurfaceType == WINED3D_SURFACE_TYPE_OPENGL)
422     {
423         UINT i;
424
425         for (i = 0; i < ddraw->numConvertedDecls; ++i)
426         {
427             wined3d_vertex_declaration_decref(ddraw->decls[i].decl);
428         }
429         HeapFree(GetProcessHeap(), 0, ddraw->decls);
430         ddraw->numConvertedDecls = 0;
431
432         if (FAILED(wined3d_device_uninit_3d(ddraw->wined3d_device)))
433         {
434             ERR("Failed to uninit 3D.\n");
435         }
436         else
437         {
438             /* Free the d3d window if one was created. */
439             if (ddraw->d3d_window && ddraw->d3d_window != ddraw->dest_window)
440             {
441                 TRACE("Destroying the hidden render window %p.\n", ddraw->d3d_window);
442                 DestroyWindow(ddraw->d3d_window);
443                 ddraw->d3d_window = 0;
444             }
445         }
446
447         ddraw->d3d_initialized = FALSE;
448     }
449     else
450     {
451         wined3d_device_uninit_gdi(ddraw->wined3d_device);
452     }
453
454     ddraw_set_swapchain_window(ddraw, NULL);
455
456     TRACE("Swapchain destroyed.\n");
457 }
458
459 /*****************************************************************************
460  * ddraw_destroy
461  *
462  * Destroys a ddraw object if all refcounts are 0. This is to share code
463  * between the IDirectDrawX::Release functions
464  *
465  * Params:
466  *  This: DirectDraw object to destroy
467  *
468  *****************************************************************************/
469 static void ddraw_destroy(struct ddraw *This)
470 {
471     IDirectDraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, NULL, DDSCL_NORMAL);
472     IDirectDraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
473
474     /* Destroy the device window if we created one */
475     if(This->devicewindow != 0)
476     {
477         TRACE(" (%p) Destroying the device window %p\n", This, This->devicewindow);
478         DestroyWindow(This->devicewindow);
479         This->devicewindow = 0;
480     }
481
482     wined3d_mutex_lock();
483     list_remove(&This->ddraw_list_entry);
484     wined3d_mutex_unlock();
485
486     if (This->wined3d_swapchain)
487         ddraw_destroy_swapchain(This);
488     wined3d_device_decref(This->wined3d_device);
489     wined3d_decref(This->wined3d);
490
491     /* Now free the object */
492     HeapFree(GetProcessHeap(), 0, This);
493 }
494
495 /*****************************************************************************
496  * IDirectDraw7::Release
497  *
498  * Decreases the refcount. If the refcount falls to 0, the object is destroyed
499  *
500  * Returns: The new refcount
501  *****************************************************************************/
502 static ULONG WINAPI ddraw7_Release(IDirectDraw7 *iface)
503 {
504     struct ddraw *This = impl_from_IDirectDraw7(iface);
505     ULONG ref = InterlockedDecrement(&This->ref7);
506
507     TRACE("%p decreasing refcount to %u.\n", This, ref);
508
509     if (!ref && !InterlockedDecrement(&This->numIfaces))
510         ddraw_destroy(This);
511
512     return ref;
513 }
514
515 static ULONG WINAPI ddraw4_Release(IDirectDraw4 *iface)
516 {
517     struct ddraw *This = impl_from_IDirectDraw4(iface);
518     ULONG ref = InterlockedDecrement(&This->ref4);
519
520     TRACE("%p decreasing refcount to %u.\n", This, ref);
521
522     if (!ref && !InterlockedDecrement(&This->numIfaces))
523         ddraw_destroy(This);
524
525     return ref;
526 }
527
528 static ULONG WINAPI ddraw2_Release(IDirectDraw2 *iface)
529 {
530     struct ddraw *This = impl_from_IDirectDraw2(iface);
531     ULONG ref = InterlockedDecrement(&This->ref2);
532
533     TRACE("%p decreasing refcount to %u.\n", This, ref);
534
535     if (!ref && !InterlockedDecrement(&This->numIfaces))
536         ddraw_destroy(This);
537
538     return ref;
539 }
540
541 static ULONG WINAPI ddraw1_Release(IDirectDraw *iface)
542 {
543     struct ddraw *This = impl_from_IDirectDraw(iface);
544     ULONG ref = InterlockedDecrement(&This->ref1);
545
546     TRACE("%p decreasing refcount to %u.\n", This, ref);
547
548     if (!ref && !InterlockedDecrement(&This->numIfaces))
549         ddraw_destroy(This);
550
551     return ref;
552 }
553
554 static ULONG WINAPI d3d7_Release(IDirect3D7 *iface)
555 {
556     struct ddraw *This = impl_from_IDirect3D7(iface);
557
558     TRACE("iface %p.\n", iface);
559
560     return ddraw7_Release(&This->IDirectDraw7_iface);
561 }
562
563 static ULONG WINAPI d3d3_Release(IDirect3D3 *iface)
564 {
565     struct ddraw *This = impl_from_IDirect3D3(iface);
566
567     TRACE("iface %p.\n", iface);
568
569     return ddraw1_Release(&This->IDirectDraw_iface);
570 }
571
572 static ULONG WINAPI d3d2_Release(IDirect3D2 *iface)
573 {
574     struct ddraw *This = impl_from_IDirect3D2(iface);
575
576     TRACE("iface %p.\n", iface);
577
578     return ddraw1_Release(&This->IDirectDraw_iface);
579 }
580
581 static ULONG WINAPI d3d1_Release(IDirect3D *iface)
582 {
583     struct ddraw *This = impl_from_IDirect3D(iface);
584
585     TRACE("iface %p.\n", iface);
586
587     return ddraw1_Release(&This->IDirectDraw_iface);
588 }
589
590 /*****************************************************************************
591  * IDirectDraw methods
592  *****************************************************************************/
593
594 static HRESULT ddraw_set_focus_window(struct ddraw *ddraw, HWND window)
595 {
596     /* FIXME: This looks wrong, exclusive mode should imply a destination
597      * window. */
598     if ((ddraw->cooperative_level & DDSCL_EXCLUSIVE) && ddraw->dest_window)
599     {
600         TRACE("Setting DDSCL_SETFOCUSWINDOW with an already set window, returning DDERR_HWNDALREADYSET.\n");
601         return DDERR_HWNDALREADYSET;
602     }
603
604     ddraw->focuswindow = window;
605
606     /* Use the focus window for drawing too. */
607     ddraw->dest_window = ddraw->focuswindow;
608
609     return DD_OK;
610 }
611
612 static HRESULT ddraw_attach_d3d_device(struct ddraw *ddraw,
613         struct wined3d_swapchain_desc *swapchain_desc)
614 {
615     HWND window = swapchain_desc->device_window;
616     HRESULT hr;
617
618     TRACE("ddraw %p.\n", ddraw);
619
620     if (!window || window == GetDesktopWindow())
621     {
622         window = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "Hidden D3D Window",
623                 WS_DISABLED, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
624                 NULL, NULL, NULL, NULL);
625         if (!window)
626         {
627             ERR("Failed to create window, last error %#x.\n", GetLastError());
628             return E_FAIL;
629         }
630
631         ShowWindow(window, SW_HIDE);   /* Just to be sure */
632         WARN("No window for the Direct3DDevice, created hidden window %p.\n", window);
633
634         swapchain_desc->device_window = window;
635     }
636     else
637     {
638         TRACE("Using existing window %p for Direct3D rendering.\n", window);
639     }
640     ddraw->d3d_window = window;
641
642     /* Set this NOW, otherwise creating the depth stencil surface will cause a
643      * recursive loop until ram or emulated video memory is full. */
644     ddraw->d3d_initialized = TRUE;
645     hr = wined3d_device_init_3d(ddraw->wined3d_device, swapchain_desc);
646     if (FAILED(hr))
647     {
648         ddraw->d3d_initialized = FALSE;
649         return hr;
650     }
651
652     ddraw->declArraySize = 2;
653     ddraw->decls = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw->decls) * ddraw->declArraySize);
654     if (!ddraw->decls)
655     {
656         ERR("Error allocating an array for the converted vertex decls.\n");
657         ddraw->declArraySize = 0;
658         hr = wined3d_device_uninit_3d(ddraw->wined3d_device);
659         return E_OUTOFMEMORY;
660     }
661
662     TRACE("Successfully initialized 3D.\n");
663
664     return DD_OK;
665 }
666
667 static HRESULT ddraw_create_swapchain(struct ddraw *ddraw, HWND window, BOOL windowed)
668 {
669     struct wined3d_swapchain_desc swapchain_desc;
670     struct wined3d_display_mode mode;
671     HRESULT hr = WINED3D_OK;
672
673     if (FAILED(hr = wined3d_get_adapter_display_mode(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &mode, NULL)))
674     {
675         ERR("Failed to get display mode.\n");
676         return hr;
677     }
678
679     memset(&swapchain_desc, 0, sizeof(swapchain_desc));
680     swapchain_desc.backbuffer_width = mode.width;
681     swapchain_desc.backbuffer_height = mode.height;
682     swapchain_desc.backbuffer_format = mode.format_id;
683     swapchain_desc.swap_effect = WINED3D_SWAP_EFFECT_COPY;
684     swapchain_desc.device_window = window;
685     swapchain_desc.windowed = windowed;
686
687     if (DefaultSurfaceType == WINED3D_SURFACE_TYPE_OPENGL)
688         hr = ddraw_attach_d3d_device(ddraw, &swapchain_desc);
689     else
690         hr = wined3d_device_init_gdi(ddraw->wined3d_device, &swapchain_desc);
691
692     if (FAILED(hr))
693     {
694         ERR("Failed to create swapchain, hr %#x.\n", hr);
695         return hr;
696     }
697
698     if (FAILED(hr = wined3d_device_get_swapchain(ddraw->wined3d_device, 0, &ddraw->wined3d_swapchain)))
699     {
700         ERR("Failed to get swapchain, hr %#x.\n", hr);
701         ddraw->wined3d_swapchain = NULL;
702         return hr;
703     }
704
705     ddraw_set_swapchain_window(ddraw, window);
706
707     return DD_OK;
708 }
709
710 /*****************************************************************************
711  * IDirectDraw7::SetCooperativeLevel
712  *
713  * Sets the cooperative level for the DirectDraw object, and the window
714  * assigned to it. The cooperative level determines the general behavior
715  * of the DirectDraw application
716  *
717  * Warning: This is quite tricky, as it's not really documented which
718  * cooperative levels can be combined with each other. If a game fails
719  * after this function, try to check the cooperative levels passed on
720  * Windows, and if it returns something different.
721  *
722  * If you think that this function caused the failure because it writes a
723  * fixme, be sure to run again with a +ddraw trace.
724  *
725  * What is known about cooperative levels (See the ddraw modes test):
726  * DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN must be used with each other
727  * DDSCL_NORMAL is not compatible with DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN
728  * DDSCL_SETFOCUSWINDOW can be passed only in DDSCL_NORMAL mode, but after that
729  * DDSCL_FULLSCREEN can be activated
730  * DDSCL_SETFOCUSWINDOW may only be used with DDSCL_NOWINDOWCHANGES
731  *
732  * Handled flags: DDSCL_NORMAL, DDSCL_FULLSCREEN, DDSCL_EXCLUSIVE,
733  *                DDSCL_SETFOCUSWINDOW (partially),
734  *                DDSCL_MULTITHREADED (work in progress)
735  *
736  * Unhandled flags, which should be implemented
737  *  DDSCL_SETDEVICEWINDOW: Sets a window specially used for rendering (I don't
738  *  expect any difference to a normal window for wine)
739  *  DDSCL_CREATEDEVICEWINDOW: Tells ddraw to create its own window for
740  *  rendering (Possible test case: Half-Life)
741  *
742  * Unsure about these: DDSCL_FPUSETUP DDSCL_FPURESERVE
743  *
744  * These don't seem very important for wine:
745  *  DDSCL_ALLOWREBOOT, DDSCL_NOWINDOWCHANGES, DDSCL_ALLOWMODEX
746  *
747  * Returns:
748  *  DD_OK if the cooperative level was set successfully
749  *  DDERR_INVALIDPARAMS if the passed cooperative level combination is invalid
750  *  DDERR_HWNDALREADYSET if DDSCL_SETFOCUSWINDOW is passed in exclusive mode
751  *   (Probably others too, have to investigate)
752  *
753  *****************************************************************************/
754 static HRESULT WINAPI ddraw7_SetCooperativeLevel(IDirectDraw7 *iface, HWND hwnd, DWORD cooplevel)
755 {
756     struct ddraw *This = impl_from_IDirectDraw7(iface);
757     struct wined3d_stateblock *stateblock;
758     struct wined3d_surface *rt, *ds;
759     BOOL restore_state = FALSE;
760     HWND window;
761     HRESULT hr;
762
763     TRACE("iface %p, window %p, flags %#x.\n", iface, hwnd, cooplevel);
764     DDRAW_dump_cooperativelevel(cooplevel);
765
766     wined3d_mutex_lock();
767
768     /* Get the old window */
769     window = This->dest_window;
770
771     /* Tests suggest that we need one of them: */
772     if(!(cooplevel & (DDSCL_SETFOCUSWINDOW |
773                       DDSCL_NORMAL         |
774                       DDSCL_EXCLUSIVE      )))
775     {
776         TRACE("Incorrect cooplevel flags, returning DDERR_INVALIDPARAMS\n");
777         wined3d_mutex_unlock();
778         return DDERR_INVALIDPARAMS;
779     }
780
781     if ((cooplevel & DDSCL_CREATEDEVICEWINDOW) && !(cooplevel & DDSCL_EXCLUSIVE))
782     {
783         WARN("DDSCL_CREATEDEVICEWINDOW requires DDSCL_EXCLUSIVE.\n");
784         wined3d_mutex_unlock();
785         return DDERR_INVALIDPARAMS;
786     }
787
788     /* Handle those levels first which set various hwnds */
789     if ((cooplevel & DDSCL_SETFOCUSWINDOW) && !(cooplevel & DDSCL_CREATEDEVICEWINDOW))
790     {
791         /* This isn't compatible with a lot of flags */
792         if (cooplevel & (DDSCL_MULTITHREADED
793                 | DDSCL_FPUSETUP
794                 | DDSCL_FPUPRESERVE
795                 | DDSCL_ALLOWREBOOT
796                 | DDSCL_ALLOWMODEX
797                 | DDSCL_SETDEVICEWINDOW
798                 | DDSCL_NORMAL
799                 | DDSCL_EXCLUSIVE
800                 | DDSCL_FULLSCREEN))
801         {
802             WARN("Called with incompatible flags, returning DDERR_INVALIDPARAMS.\n");
803             wined3d_mutex_unlock();
804             return DDERR_INVALIDPARAMS;
805         }
806
807         hr = ddraw_set_focus_window(This, hwnd);
808         wined3d_mutex_unlock();
809         return hr;
810     }
811
812     if (cooplevel & DDSCL_EXCLUSIVE)
813     {
814         if (!(cooplevel & DDSCL_FULLSCREEN) || !(hwnd || (cooplevel & DDSCL_CREATEDEVICEWINDOW)))
815         {
816             WARN("DDSCL_EXCLUSIVE requires DDSCL_FULLSCREEN and a window.\n");
817             wined3d_mutex_unlock();
818             return DDERR_INVALIDPARAMS;
819         }
820
821         if (cooplevel & DDSCL_CREATEDEVICEWINDOW)
822         {
823             HWND device_window;
824
825             if (!This->focuswindow && !(cooplevel & DDSCL_SETFOCUSWINDOW))
826             {
827                 WARN("No focus window set.\n");
828                 wined3d_mutex_unlock();
829                 return DDERR_NOFOCUSWINDOW;
830             }
831
832             device_window = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "DirectDrawDeviceWnd",
833                     WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
834                     NULL, NULL, NULL, NULL);
835             if (!device_window)
836             {
837                 ERR("Failed to create window, last error %#x.\n", GetLastError());
838                 wined3d_mutex_unlock();
839                 return E_FAIL;
840             }
841
842             ShowWindow(device_window, SW_SHOW);
843             TRACE("Created a device window %p.\n", device_window);
844
845             /* Native apparently leaks the created device window if setting the
846              * focus window below fails. */
847             This->cooperative_level |= DDSCL_CREATEDEVICEWINDOW;
848             This->devicewindow = device_window;
849
850             if (cooplevel & DDSCL_SETFOCUSWINDOW)
851             {
852                 if (!hwnd)
853                 {
854                     wined3d_mutex_unlock();
855                     return DDERR_NOHWND;
856                 }
857
858                 if (FAILED(hr = ddraw_set_focus_window(This, hwnd)))
859                 {
860                     wined3d_mutex_unlock();
861                     return hr;
862                 }
863             }
864
865             hwnd = device_window;
866         }
867     }
868     else
869     {
870         if (This->cooperative_level & DDSCL_CREATEDEVICEWINDOW)
871             DestroyWindow(This->devicewindow);
872         This->devicewindow = NULL;
873         This->focuswindow = NULL;
874     }
875
876     if ((This->cooperative_level & DDSCL_EXCLUSIVE)
877             && (hwnd != window || !(cooplevel & DDSCL_EXCLUSIVE)))
878         wined3d_device_release_focus_window(This->wined3d_device);
879
880     if ((cooplevel & DDSCL_FULLSCREEN) != (This->cooperative_level & DDSCL_FULLSCREEN) || hwnd != window)
881     {
882         if (This->cooperative_level & DDSCL_FULLSCREEN)
883             wined3d_device_restore_fullscreen_window(This->wined3d_device, window);
884
885         if (cooplevel & DDSCL_FULLSCREEN)
886         {
887             struct wined3d_display_mode display_mode;
888
889             wined3d_get_adapter_display_mode(This->wined3d, WINED3DADAPTER_DEFAULT, &display_mode, NULL);
890             wined3d_device_setup_fullscreen_window(This->wined3d_device, hwnd,
891                     display_mode.width, display_mode.height);
892         }
893     }
894
895     if ((cooplevel & DDSCL_EXCLUSIVE)
896             && (hwnd != window || !(This->cooperative_level & DDSCL_EXCLUSIVE)))
897     {
898         hr = wined3d_device_acquire_focus_window(This->wined3d_device, hwnd);
899         if (FAILED(hr))
900         {
901             ERR("Failed to acquire focus window, hr %#x.\n", hr);
902             wined3d_mutex_unlock();
903             return hr;
904         }
905     }
906
907     /* Don't override focus windows or private device windows */
908     if (hwnd && !This->focuswindow && !This->devicewindow && (hwnd != window))
909         This->dest_window = hwnd;
910
911     if (cooplevel & DDSCL_MULTITHREADED && !(This->cooperative_level & DDSCL_MULTITHREADED))
912         wined3d_device_set_multithreaded(This->wined3d_device);
913
914     if (This->wined3d_swapchain)
915     {
916         if (DefaultSurfaceType != WINED3D_SURFACE_TYPE_GDI)
917         {
918             restore_state = TRUE;
919
920             if (FAILED(hr = wined3d_stateblock_create(This->wined3d_device, WINED3D_SBT_ALL, &stateblock)))
921             {
922                 ERR("Failed to create stateblock, hr %#x.\n", hr);
923                 wined3d_mutex_unlock();
924                 return hr;
925             }
926
927             if (FAILED(hr = wined3d_stateblock_capture(stateblock)))
928             {
929                 ERR("Failed to capture stateblock, hr %#x.\n", hr);
930                 wined3d_stateblock_decref(stateblock);
931                 wined3d_mutex_unlock();
932                 return hr;
933             }
934
935             wined3d_device_get_render_target(This->wined3d_device, 0, &rt);
936             if (rt == This->wined3d_frontbuffer)
937             {
938                 wined3d_surface_decref(rt);
939                 rt = NULL;
940             }
941
942             wined3d_device_get_depth_stencil(This->wined3d_device, &ds);
943         }
944
945         ddraw_destroy_swapchain(This);
946     }
947
948     if (FAILED(hr = ddraw_create_swapchain(This, This->dest_window, !(cooplevel & DDSCL_FULLSCREEN))))
949         ERR("Failed to create swapchain, hr %#x.\n", hr);
950
951     if (restore_state)
952     {
953         if (ds)
954         {
955             wined3d_device_set_depth_stencil(This->wined3d_device, ds);
956             wined3d_surface_decref(ds);
957         }
958
959         if (rt)
960         {
961             wined3d_device_set_render_target(This->wined3d_device, 0, rt, FALSE);
962             wined3d_surface_decref(rt);
963         }
964
965         hr = wined3d_stateblock_apply(stateblock);
966         wined3d_stateblock_decref(stateblock);
967         if (FAILED(hr))
968         {
969             ERR("Failed to apply stateblock, hr %#x.\n", hr);
970             wined3d_mutex_unlock();
971             return hr;
972         }
973     }
974
975     /* Unhandled flags */
976     if(cooplevel & DDSCL_ALLOWREBOOT)
977         WARN("(%p) Unhandled flag DDSCL_ALLOWREBOOT, harmless\n", This);
978     if(cooplevel & DDSCL_ALLOWMODEX)
979         WARN("(%p) Unhandled flag DDSCL_ALLOWMODEX, harmless\n", This);
980     if(cooplevel & DDSCL_FPUSETUP)
981         WARN("(%p) Unhandled flag DDSCL_FPUSETUP, harmless\n", This);
982
983     /* Store the cooperative_level */
984     This->cooperative_level = cooplevel;
985     TRACE("SetCooperativeLevel retuning DD_OK\n");
986     wined3d_mutex_unlock();
987
988     return DD_OK;
989 }
990
991 static HRESULT WINAPI ddraw4_SetCooperativeLevel(IDirectDraw4 *iface, HWND window, DWORD flags)
992 {
993     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
994
995     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
996
997     return ddraw7_SetCooperativeLevel(&ddraw->IDirectDraw7_iface, window, flags);
998 }
999
1000 static HRESULT WINAPI ddraw2_SetCooperativeLevel(IDirectDraw2 *iface, HWND window, DWORD flags)
1001 {
1002     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1003
1004     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
1005
1006     return ddraw7_SetCooperativeLevel(&ddraw->IDirectDraw7_iface, window, flags);
1007 }
1008
1009 static HRESULT WINAPI ddraw1_SetCooperativeLevel(IDirectDraw *iface, HWND window, DWORD flags)
1010 {
1011     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1012
1013     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
1014
1015     return ddraw7_SetCooperativeLevel(&ddraw->IDirectDraw7_iface, window, flags);
1016 }
1017
1018 /*****************************************************************************
1019  *
1020  * Helper function for SetDisplayMode and RestoreDisplayMode
1021  *
1022  * Implements DirectDraw's SetDisplayMode, but ignores the value of
1023  * ForceRefreshRate, since it is already handled by
1024  * ddraw7_SetDisplayMode.  RestoreDisplayMode can use this function
1025  * without worrying that ForceRefreshRate will override the refresh rate.  For
1026  * argument and return value documentation, see
1027  * ddraw7_SetDisplayMode.
1028  *
1029  *****************************************************************************/
1030 static HRESULT ddraw_set_display_mode(struct ddraw *ddraw, DWORD Width, DWORD Height,
1031         DWORD BPP, DWORD RefreshRate, DWORD Flags)
1032 {
1033     struct wined3d_display_mode mode;
1034     enum wined3d_format_id format;
1035     HRESULT hr;
1036
1037     TRACE("ddraw %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n", ddraw, Width,
1038             Height, BPP, RefreshRate, Flags);
1039
1040     wined3d_mutex_lock();
1041     if( !Width || !Height )
1042     {
1043         ERR("Width %u, Height %u, what to do?\n", Width, Height);
1044         /* It looks like Need for Speed Porsche Unleashed expects DD_OK here */
1045         wined3d_mutex_unlock();
1046         return DD_OK;
1047     }
1048
1049     switch(BPP)
1050     {
1051         case 8:  format = WINED3DFMT_P8_UINT;          break;
1052         case 15: format = WINED3DFMT_B5G5R5X1_UNORM;   break;
1053         case 16: format = WINED3DFMT_B5G6R5_UNORM;     break;
1054         case 24: format = WINED3DFMT_B8G8R8_UNORM;     break;
1055         case 32: format = WINED3DFMT_B8G8R8X8_UNORM;   break;
1056         default: format = WINED3DFMT_UNKNOWN;          break;
1057     }
1058
1059     /* Check the exclusive mode
1060     if(!(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
1061         return DDERR_NOEXCLUSIVEMODE;
1062      * This is WRONG. Don't know if the SDK is completely
1063      * wrong and if there are any conditions when DDERR_NOEXCLUSIVE
1064      * is returned, but Half-Life 1.1.1.1 (Steam version)
1065      * depends on this
1066      */
1067
1068     mode.width = Width;
1069     mode.height = Height;
1070     mode.refresh_rate = RefreshRate;
1071     mode.format_id = format;
1072     mode.scanline_ordering = WINED3D_SCANLINE_ORDERING_UNKNOWN;
1073
1074     /* TODO: The possible return values from msdn suggest that
1075      * the screen mode can't be changed if a surface is locked
1076      * or some drawing is in progress
1077      */
1078
1079     /* TODO: Lose the primary surface */
1080     hr = wined3d_set_adapter_display_mode(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &mode);
1081
1082     wined3d_mutex_unlock();
1083
1084     switch(hr)
1085     {
1086         case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
1087         default:                            return hr;
1088     }
1089 }
1090
1091 /*****************************************************************************
1092  * IDirectDraw7::SetDisplayMode
1093  *
1094  * Sets the display screen resolution, color depth and refresh frequency
1095  * when in fullscreen mode (in theory).
1096  * Possible return values listed in the SDK suggest that this method fails
1097  * when not in fullscreen mode, but this is wrong. Windows 2000 happily sets
1098  * the display mode in DDSCL_NORMAL mode without an hwnd specified.
1099  * It seems to be valid to pass 0 for With and Height, this has to be tested
1100  * It could mean that the current video mode should be left as-is. (But why
1101  * call it then?)
1102  *
1103  * Params:
1104  *  Height, Width: Screen dimension
1105  *  BPP: Color depth in Bits per pixel
1106  *  Refreshrate: Screen refresh rate
1107  *  Flags: Other stuff
1108  *
1109  * Returns
1110  *  DD_OK on success
1111  *
1112  *****************************************************************************/
1113 static HRESULT WINAPI ddraw7_SetDisplayMode(IDirectDraw7 *iface, DWORD Width, DWORD Height,
1114         DWORD BPP, DWORD RefreshRate, DWORD Flags)
1115 {
1116     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1117
1118     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
1119             iface, Width, Height, BPP, RefreshRate, Flags);
1120
1121     if (force_refresh_rate != 0)
1122     {
1123         TRACE("ForceRefreshRate overriding passed-in refresh rate (%u Hz) to %u Hz\n",
1124                 RefreshRate, force_refresh_rate);
1125         RefreshRate = force_refresh_rate;
1126     }
1127
1128     return ddraw_set_display_mode(ddraw, Width, Height, BPP, RefreshRate, Flags);
1129 }
1130
1131 static HRESULT WINAPI ddraw4_SetDisplayMode(IDirectDraw4 *iface, DWORD width, DWORD height,
1132         DWORD bpp, DWORD refresh_rate, DWORD flags)
1133 {
1134     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1135
1136     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
1137             iface, width, height, bpp, refresh_rate, flags);
1138
1139     return ddraw7_SetDisplayMode(&ddraw->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
1140 }
1141
1142 static HRESULT WINAPI ddraw2_SetDisplayMode(IDirectDraw2 *iface,
1143         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
1144 {
1145     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1146
1147     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
1148             iface, width, height, bpp, refresh_rate, flags);
1149
1150     return ddraw7_SetDisplayMode(&ddraw->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
1151 }
1152
1153 static HRESULT WINAPI ddraw1_SetDisplayMode(IDirectDraw *iface, DWORD width, DWORD height, DWORD bpp)
1154 {
1155     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1156
1157     TRACE("iface %p, width %u, height %u, bpp %u.\n", iface, width, height, bpp);
1158
1159     return ddraw7_SetDisplayMode(&ddraw->IDirectDraw7_iface, width, height, bpp, 0, 0);
1160 }
1161
1162 /*****************************************************************************
1163  * IDirectDraw7::RestoreDisplayMode
1164  *
1165  * Restores the display mode to what it was at creation time. Basically.
1166  *
1167  * A problem arises when there are 2 DirectDraw objects using the same hwnd:
1168  *  -> DD_1 finds the screen at 1400x1050x32 when created, sets it to 640x480x16
1169  *  -> DD_2 is created, finds the screen at 640x480x16, sets it to 1024x768x32
1170  *  -> DD_1 is released. The screen should be left at 1024x768x32.
1171  *  -> DD_2 is released. The screen should be set to 1400x1050x32
1172  * This case is unhandled right now, but Empire Earth does it this way.
1173  * (But perhaps there is something in SetCooperativeLevel to prevent this)
1174  *
1175  * The msdn says that this method resets the display mode to what it was before
1176  * SetDisplayMode was called. What if SetDisplayModes is called 2 times??
1177  *
1178  * Returns
1179  *  DD_OK on success
1180  *  DDERR_NOEXCLUSIVE mode if the device isn't in fullscreen mode
1181  *
1182  *****************************************************************************/
1183 static HRESULT WINAPI ddraw7_RestoreDisplayMode(IDirectDraw7 *iface)
1184 {
1185     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1186
1187     TRACE("iface %p.\n", iface);
1188
1189     return ddraw_set_display_mode(ddraw, ddraw->orig_width, ddraw->orig_height, ddraw->orig_bpp, 0, 0);
1190 }
1191
1192 static HRESULT WINAPI ddraw4_RestoreDisplayMode(IDirectDraw4 *iface)
1193 {
1194     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1195
1196     TRACE("iface %p.\n", iface);
1197
1198     return ddraw7_RestoreDisplayMode(&ddraw->IDirectDraw7_iface);
1199 }
1200
1201 static HRESULT WINAPI ddraw2_RestoreDisplayMode(IDirectDraw2 *iface)
1202 {
1203     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1204
1205     TRACE("iface %p.\n", iface);
1206
1207     return ddraw7_RestoreDisplayMode(&ddraw->IDirectDraw7_iface);
1208 }
1209
1210 static HRESULT WINAPI ddraw1_RestoreDisplayMode(IDirectDraw *iface)
1211 {
1212     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1213
1214     TRACE("iface %p.\n", iface);
1215
1216     return ddraw7_RestoreDisplayMode(&ddraw->IDirectDraw7_iface);
1217 }
1218
1219 /*****************************************************************************
1220  * IDirectDraw7::GetCaps
1221  *
1222  * Returns the drives capabilities
1223  *
1224  * Used for version 1, 2, 4 and 7
1225  *
1226  * Params:
1227  *  DriverCaps: Structure to write the Hardware accelerated caps to
1228  *  HelCaps: Structure to write the emulation caps to
1229  *
1230  * Returns
1231  *  This implementation returns DD_OK only
1232  *
1233  *****************************************************************************/
1234 static HRESULT WINAPI ddraw7_GetCaps(IDirectDraw7 *iface, DDCAPS *DriverCaps, DDCAPS *HELCaps)
1235 {
1236     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1237     DDCAPS caps;
1238     WINED3DCAPS winecaps;
1239     HRESULT hr;
1240     DDSCAPS2 ddscaps = {0, 0, 0, 0};
1241
1242     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, DriverCaps, HELCaps);
1243
1244     /* One structure must be != NULL */
1245     if (!DriverCaps && !HELCaps)
1246     {
1247         WARN("Invalid parameters.\n");
1248         return DDERR_INVALIDPARAMS;
1249     }
1250
1251     memset(&caps, 0, sizeof(caps));
1252     memset(&winecaps, 0, sizeof(winecaps));
1253     caps.dwSize = sizeof(caps);
1254
1255     wined3d_mutex_lock();
1256     hr = wined3d_device_get_device_caps(ddraw->wined3d_device, &winecaps);
1257     if (FAILED(hr))
1258     {
1259         WARN("IWineD3DDevice::GetDeviceCaps failed\n");
1260         wined3d_mutex_unlock();
1261         return hr;
1262     }
1263
1264     hr = IDirectDraw7_GetAvailableVidMem(iface, &ddscaps, &caps.dwVidMemTotal, &caps.dwVidMemFree);
1265     wined3d_mutex_unlock();
1266     if(FAILED(hr)) {
1267         WARN("IDirectDraw7::GetAvailableVidMem failed\n");
1268         return hr;
1269     }
1270
1271     caps.dwCaps = winecaps.ddraw_caps.caps;
1272     caps.dwCaps2 = winecaps.ddraw_caps.caps2;
1273     caps.dwCKeyCaps = winecaps.ddraw_caps.color_key_caps;
1274     caps.dwFXCaps = winecaps.ddraw_caps.fx_caps;
1275     caps.dwPalCaps = winecaps.ddraw_caps.pal_caps;
1276     caps.ddsCaps.dwCaps = winecaps.ddraw_caps.dds_caps;
1277     caps.dwSVBCaps = winecaps.ddraw_caps.svb_caps;
1278     caps.dwSVBCKeyCaps = winecaps.ddraw_caps.svb_color_key_caps;
1279     caps.dwSVBFXCaps = winecaps.ddraw_caps.svb_fx_caps;
1280     caps.dwVSBCaps = winecaps.ddraw_caps.vsb_caps;
1281     caps.dwVSBCKeyCaps = winecaps.ddraw_caps.vsb_color_key_caps;
1282     caps.dwVSBFXCaps = winecaps.ddraw_caps.vsb_fx_caps;
1283     caps.dwSSBCaps = winecaps.ddraw_caps.ssb_caps;
1284     caps.dwSSBCKeyCaps = winecaps.ddraw_caps.ssb_color_key_caps;
1285     caps.dwSSBFXCaps = winecaps.ddraw_caps.ssb_fx_caps;
1286
1287     /* Even if WineD3D supports 3D rendering, remove the cap if ddraw is configured
1288      * not to use it
1289      */
1290     if (DefaultSurfaceType == WINED3D_SURFACE_TYPE_GDI)
1291     {
1292         caps.dwCaps &= ~DDCAPS_3D;
1293         caps.ddsCaps.dwCaps &= ~(DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER);
1294     }
1295     if (winecaps.ddraw_caps.stride_align)
1296     {
1297         caps.dwCaps |= DDCAPS_ALIGNSTRIDE;
1298         caps.dwAlignStrideAlign = winecaps.ddraw_caps.stride_align;
1299     }
1300
1301     if(DriverCaps)
1302     {
1303         DD_STRUCT_COPY_BYSIZE(DriverCaps, &caps);
1304         if (TRACE_ON(ddraw))
1305         {
1306             TRACE("Driver Caps :\n");
1307             DDRAW_dump_DDCAPS(DriverCaps);
1308         }
1309
1310     }
1311     if(HELCaps)
1312     {
1313         DD_STRUCT_COPY_BYSIZE(HELCaps, &caps);
1314         if (TRACE_ON(ddraw))
1315         {
1316             TRACE("HEL Caps :\n");
1317             DDRAW_dump_DDCAPS(HELCaps);
1318         }
1319     }
1320
1321     return DD_OK;
1322 }
1323
1324 static HRESULT WINAPI ddraw4_GetCaps(IDirectDraw4 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1325 {
1326     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1327
1328     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1329
1330     return ddraw7_GetCaps(&ddraw->IDirectDraw7_iface, driver_caps, hel_caps);
1331 }
1332
1333 static HRESULT WINAPI ddraw2_GetCaps(IDirectDraw2 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1334 {
1335     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1336
1337     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1338
1339     return ddraw7_GetCaps(&ddraw->IDirectDraw7_iface, driver_caps, hel_caps);
1340 }
1341
1342 static HRESULT WINAPI ddraw1_GetCaps(IDirectDraw *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1343 {
1344     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1345
1346     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1347
1348     return ddraw7_GetCaps(&ddraw->IDirectDraw7_iface, driver_caps, hel_caps);
1349 }
1350
1351 /*****************************************************************************
1352  * IDirectDraw7::Compact
1353  *
1354  * No idea what it does, MSDN says it's not implemented.
1355  *
1356  * Returns
1357  *  DD_OK, but this is unchecked
1358  *
1359  *****************************************************************************/
1360 static HRESULT WINAPI ddraw7_Compact(IDirectDraw7 *iface)
1361 {
1362     TRACE("iface %p.\n", iface);
1363
1364     return DD_OK;
1365 }
1366
1367 static HRESULT WINAPI ddraw4_Compact(IDirectDraw4 *iface)
1368 {
1369     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1370
1371     TRACE("iface %p.\n", iface);
1372
1373     return ddraw7_Compact(&ddraw->IDirectDraw7_iface);
1374 }
1375
1376 static HRESULT WINAPI ddraw2_Compact(IDirectDraw2 *iface)
1377 {
1378     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1379
1380     TRACE("iface %p.\n", iface);
1381
1382     return ddraw7_Compact(&ddraw->IDirectDraw7_iface);
1383 }
1384
1385 static HRESULT WINAPI ddraw1_Compact(IDirectDraw *iface)
1386 {
1387     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1388
1389     TRACE("iface %p.\n", iface);
1390
1391     return ddraw7_Compact(&ddraw->IDirectDraw7_iface);
1392 }
1393
1394 /*****************************************************************************
1395  * IDirectDraw7::GetDisplayMode
1396  *
1397  * Returns information about the current display mode
1398  *
1399  * Exists in Version 1, 2, 4 and 7
1400  *
1401  * Params:
1402  *  DDSD: Address of a surface description structure to write the info to
1403  *
1404  * Returns
1405  *  DD_OK
1406  *
1407  *****************************************************************************/
1408 static HRESULT WINAPI ddraw7_GetDisplayMode(IDirectDraw7 *iface, DDSURFACEDESC2 *DDSD)
1409 {
1410     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1411     struct wined3d_display_mode mode;
1412     HRESULT hr;
1413     DWORD Size;
1414
1415     TRACE("iface %p, surface_desc %p.\n", iface, DDSD);
1416
1417     wined3d_mutex_lock();
1418     /* This seems sane */
1419     if (!DDSD)
1420     {
1421         wined3d_mutex_unlock();
1422         return DDERR_INVALIDPARAMS;
1423     }
1424
1425     if (FAILED(hr = wined3d_get_adapter_display_mode(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &mode, NULL)))
1426     {
1427         ERR("Failed to get display mode, hr %#x.\n", hr);
1428         wined3d_mutex_unlock();
1429         return hr;
1430     }
1431
1432     Size = DDSD->dwSize;
1433     memset(DDSD, 0, Size);
1434
1435     DDSD->dwSize = Size;
1436     DDSD->dwFlags |= DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_PITCH | DDSD_REFRESHRATE;
1437     DDSD->dwWidth = mode.width;
1438     DDSD->dwHeight = mode.height;
1439     DDSD->u2.dwRefreshRate = 60;
1440     DDSD->ddsCaps.dwCaps = 0;
1441     DDSD->u4.ddpfPixelFormat.dwSize = sizeof(DDSD->u4.ddpfPixelFormat);
1442     PixelFormat_WineD3DtoDD(&DDSD->u4.ddpfPixelFormat, mode.format_id);
1443     DDSD->u1.lPitch = mode.width * DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount / 8;
1444
1445     if(TRACE_ON(ddraw))
1446     {
1447         TRACE("Returning surface desc :\n");
1448         DDRAW_dump_surface_desc(DDSD);
1449     }
1450
1451     wined3d_mutex_unlock();
1452
1453     return DD_OK;
1454 }
1455
1456 static HRESULT WINAPI ddraw4_GetDisplayMode(IDirectDraw4 *iface, DDSURFACEDESC2 *surface_desc)
1457 {
1458     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1459
1460     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1461
1462     return ddraw7_GetDisplayMode(&ddraw->IDirectDraw7_iface, surface_desc);
1463 }
1464
1465 static HRESULT WINAPI ddraw2_GetDisplayMode(IDirectDraw2 *iface, DDSURFACEDESC *surface_desc)
1466 {
1467     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1468
1469     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1470
1471     /* FIXME: Test sizes, properly convert surface_desc */
1472     return ddraw7_GetDisplayMode(&ddraw->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1473 }
1474
1475 static HRESULT WINAPI ddraw1_GetDisplayMode(IDirectDraw *iface, DDSURFACEDESC *surface_desc)
1476 {
1477     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1478
1479     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1480
1481     /* FIXME: Test sizes, properly convert surface_desc */
1482     return ddraw7_GetDisplayMode(&ddraw->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1483 }
1484
1485 /*****************************************************************************
1486  * IDirectDraw7::GetFourCCCodes
1487  *
1488  * Returns an array of supported FourCC codes.
1489  *
1490  * Exists in Version 1, 2, 4 and 7
1491  *
1492  * Params:
1493  *  NumCodes: Contains the number of Codes that Codes can carry. Returns the number
1494  *            of enumerated codes
1495  *  Codes: Pointer to an array of DWORDs where the supported codes are written
1496  *         to
1497  *
1498  * Returns
1499  *  Always returns DD_OK, as it's a stub for now
1500  *
1501  *****************************************************************************/
1502 static HRESULT WINAPI ddraw7_GetFourCCCodes(IDirectDraw7 *iface, DWORD *NumCodes, DWORD *Codes)
1503 {
1504     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1505     static const enum wined3d_format_id formats[] =
1506     {
1507         WINED3DFMT_YUY2, WINED3DFMT_UYVY, WINED3DFMT_YV12,
1508         WINED3DFMT_DXT1, WINED3DFMT_DXT2, WINED3DFMT_DXT3, WINED3DFMT_DXT4, WINED3DFMT_DXT5,
1509         WINED3DFMT_ATI2N, WINED3DFMT_NVHU, WINED3DFMT_NVHS
1510     };
1511     struct wined3d_display_mode mode;
1512     DWORD count = 0, i, outsize;
1513     HRESULT hr;
1514
1515     TRACE("iface %p, codes_count %p, codes %p.\n", iface, NumCodes, Codes);
1516
1517     if (FAILED(hr = wined3d_get_adapter_display_mode(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &mode, NULL)))
1518     {
1519         ERR("Failed to get display mode, hr %#x.\n", hr);
1520         return hr;
1521     }
1522
1523     outsize = NumCodes && Codes ? *NumCodes : 0;
1524
1525     for (i = 0; i < (sizeof(formats) / sizeof(formats[0])); ++i)
1526     {
1527         hr = wined3d_check_device_format(ddraw->wined3d, WINED3DADAPTER_DEFAULT, WINED3D_DEVICE_TYPE_HAL,
1528                 mode.format_id, 0, WINED3D_RTYPE_SURFACE, formats[i], DefaultSurfaceType);
1529         if (SUCCEEDED(hr))
1530         {
1531             if (count < outsize)
1532                 Codes[count] = formats[i];
1533             ++count;
1534         }
1535     }
1536     if(NumCodes) {
1537         TRACE("Returning %u FourCC codes\n", count);
1538         *NumCodes = count;
1539     }
1540
1541     return DD_OK;
1542 }
1543
1544 static HRESULT WINAPI ddraw4_GetFourCCCodes(IDirectDraw4 *iface, DWORD *codes_count, DWORD *codes)
1545 {
1546     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1547
1548     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1549
1550     return ddraw7_GetFourCCCodes(&ddraw->IDirectDraw7_iface, codes_count, codes);
1551 }
1552
1553 static HRESULT WINAPI ddraw2_GetFourCCCodes(IDirectDraw2 *iface, DWORD *codes_count, DWORD *codes)
1554 {
1555     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1556
1557     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1558
1559     return ddraw7_GetFourCCCodes(&ddraw->IDirectDraw7_iface, codes_count, codes);
1560 }
1561
1562 static HRESULT WINAPI ddraw1_GetFourCCCodes(IDirectDraw *iface, DWORD *codes_count, DWORD *codes)
1563 {
1564     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1565
1566     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1567
1568     return ddraw7_GetFourCCCodes(&ddraw->IDirectDraw7_iface, codes_count, codes);
1569 }
1570
1571 /*****************************************************************************
1572  * IDirectDraw7::GetMonitorFrequency
1573  *
1574  * Returns the monitor's frequency
1575  *
1576  * Exists in Version 1, 2, 4 and 7
1577  *
1578  * Params:
1579  *  Freq: Pointer to a DWORD to write the frequency to
1580  *
1581  * Returns
1582  *  Always returns DD_OK
1583  *
1584  *****************************************************************************/
1585 static HRESULT WINAPI ddraw7_GetMonitorFrequency(IDirectDraw7 *iface, DWORD *Freq)
1586 {
1587     FIXME("iface %p, frequency %p stub!\n", iface, Freq);
1588
1589     /* Ideally this should be in WineD3D, as it concerns the screen setup,
1590      * but for now this should make the games happy
1591      */
1592     *Freq = 60;
1593     return DD_OK;
1594 }
1595
1596 static HRESULT WINAPI ddraw4_GetMonitorFrequency(IDirectDraw4 *iface, DWORD *frequency)
1597 {
1598     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1599
1600     TRACE("iface %p, frequency %p.\n", iface, frequency);
1601
1602     return ddraw7_GetMonitorFrequency(&ddraw->IDirectDraw7_iface, frequency);
1603 }
1604
1605 static HRESULT WINAPI ddraw2_GetMonitorFrequency(IDirectDraw2 *iface, DWORD *frequency)
1606 {
1607     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1608
1609     TRACE("iface %p, frequency %p.\n", iface, frequency);
1610
1611     return ddraw7_GetMonitorFrequency(&ddraw->IDirectDraw7_iface, frequency);
1612 }
1613
1614 static HRESULT WINAPI ddraw1_GetMonitorFrequency(IDirectDraw *iface, DWORD *frequency)
1615 {
1616     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1617
1618     TRACE("iface %p, frequency %p.\n", iface, frequency);
1619
1620     return ddraw7_GetMonitorFrequency(&ddraw->IDirectDraw7_iface, frequency);
1621 }
1622
1623 static HRESULT WINAPI ddraw7_GetVerticalBlankStatus(IDirectDraw7 *iface, BOOL *status)
1624 {
1625     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1626     struct wined3d_raster_status raster_status;
1627     HRESULT hr;
1628
1629     TRACE("iface %p, status %p.\n", iface, status);
1630
1631     if(!status)
1632         return DDERR_INVALIDPARAMS;
1633
1634     wined3d_mutex_lock();
1635     hr = wined3d_get_adapter_raster_status(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &raster_status);
1636     wined3d_mutex_unlock();
1637     if (FAILED(hr))
1638     {
1639         WARN("Failed to get raster status, hr %#x.\n", hr);
1640         return hr;
1641     }
1642
1643     *status = raster_status.in_vblank;
1644
1645     return DD_OK;
1646 }
1647
1648 static HRESULT WINAPI ddraw4_GetVerticalBlankStatus(IDirectDraw4 *iface, BOOL *status)
1649 {
1650     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1651
1652     TRACE("iface %p, status %p.\n", iface, status);
1653
1654     return ddraw7_GetVerticalBlankStatus(&ddraw->IDirectDraw7_iface, status);
1655 }
1656
1657 static HRESULT WINAPI ddraw2_GetVerticalBlankStatus(IDirectDraw2 *iface, BOOL *status)
1658 {
1659     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1660
1661     TRACE("iface %p, status %p.\n", iface, status);
1662
1663     return ddraw7_GetVerticalBlankStatus(&ddraw->IDirectDraw7_iface, status);
1664 }
1665
1666 static HRESULT WINAPI ddraw1_GetVerticalBlankStatus(IDirectDraw *iface, BOOL *status)
1667 {
1668     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1669
1670     TRACE("iface %p, status %p.\n", iface, status);
1671
1672     return ddraw7_GetVerticalBlankStatus(&ddraw->IDirectDraw7_iface, status);
1673 }
1674
1675 /*****************************************************************************
1676  * IDirectDraw7::GetAvailableVidMem
1677  *
1678  * Returns the total and free video memory
1679  *
1680  * Params:
1681  *  Caps: Specifies the memory type asked for
1682  *  total: Pointer to a DWORD to be filled with the total memory
1683  *  free: Pointer to a DWORD to be filled with the free memory
1684  *
1685  * Returns
1686  *  DD_OK on success
1687  *  DDERR_INVALIDPARAMS of free and total are NULL
1688  *
1689  *****************************************************************************/
1690 static HRESULT WINAPI ddraw7_GetAvailableVidMem(IDirectDraw7 *iface, DDSCAPS2 *Caps, DWORD *total,
1691         DWORD *free)
1692 {
1693     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1694     HRESULT hr = DD_OK;
1695
1696     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, Caps, total, free);
1697
1698     if (TRACE_ON(ddraw))
1699     {
1700         TRACE("Asked for memory with description: ");
1701         DDRAW_dump_DDSCAPS2(Caps);
1702     }
1703     wined3d_mutex_lock();
1704
1705     /* Todo: System memory vs local video memory vs non-local video memory
1706      * The MSDN also mentions differences between texture memory and other
1707      * resources, but that's not important
1708      */
1709
1710     if( (!total) && (!free) )
1711     {
1712         wined3d_mutex_unlock();
1713         return DDERR_INVALIDPARAMS;
1714     }
1715
1716     if (free)
1717         *free = wined3d_device_get_available_texture_mem(ddraw->wined3d_device);
1718     if (total)
1719     {
1720         struct wined3d_adapter_identifier desc = {0};
1721
1722         hr = wined3d_get_adapter_identifier(ddraw->wined3d, WINED3DADAPTER_DEFAULT, 0, &desc);
1723         *total = desc.video_memory;
1724     }
1725
1726     wined3d_mutex_unlock();
1727
1728     return hr;
1729 }
1730
1731 static HRESULT WINAPI ddraw4_GetAvailableVidMem(IDirectDraw4 *iface,
1732         DDSCAPS2 *caps, DWORD *total, DWORD *free)
1733 {
1734     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1735
1736     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1737
1738     return ddraw7_GetAvailableVidMem(&ddraw->IDirectDraw7_iface, caps, total, free);
1739 }
1740
1741 static HRESULT WINAPI ddraw2_GetAvailableVidMem(IDirectDraw2 *iface,
1742         DDSCAPS *caps, DWORD *total, DWORD *free)
1743 {
1744     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1745     DDSCAPS2 caps2;
1746
1747     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1748
1749     DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1750     return ddraw7_GetAvailableVidMem(&ddraw->IDirectDraw7_iface, &caps2, total, free);
1751 }
1752
1753 /*****************************************************************************
1754  * IDirectDraw7::Initialize
1755  *
1756  * Initializes a DirectDraw interface.
1757  *
1758  * Params:
1759  *  GUID: Interface identifier. Well, don't know what this is really good
1760  *   for
1761  *
1762  * Returns
1763  *  Returns DD_OK on the first call,
1764  *  DDERR_ALREADYINITIALIZED on repeated calls
1765  *
1766  *****************************************************************************/
1767 static HRESULT WINAPI ddraw7_Initialize(IDirectDraw7 *iface, GUID *guid)
1768 {
1769     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1770
1771     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1772
1773     if (ddraw->initialized)
1774         return DDERR_ALREADYINITIALIZED;
1775
1776     /* FIXME: To properly take the GUID into account we should call
1777      * ddraw_init() here instead of in DDRAW_Create(). */
1778     if (guid)
1779         FIXME("Ignoring guid %s.\n", debugstr_guid(guid));
1780
1781     ddraw->initialized = TRUE;
1782     return DD_OK;
1783 }
1784
1785 static HRESULT WINAPI ddraw4_Initialize(IDirectDraw4 *iface, GUID *guid)
1786 {
1787     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1788
1789     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1790
1791     return ddraw7_Initialize(&ddraw->IDirectDraw7_iface, guid);
1792 }
1793
1794 static HRESULT WINAPI ddraw2_Initialize(IDirectDraw2 *iface, GUID *guid)
1795 {
1796     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1797
1798     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1799
1800     return ddraw7_Initialize(&ddraw->IDirectDraw7_iface, guid);
1801 }
1802
1803 static HRESULT WINAPI ddraw1_Initialize(IDirectDraw *iface, GUID *guid)
1804 {
1805     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1806
1807     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1808
1809     return ddraw7_Initialize(&ddraw->IDirectDraw7_iface, guid);
1810 }
1811
1812 static HRESULT WINAPI d3d1_Initialize(IDirect3D *iface, REFIID riid)
1813 {
1814     TRACE("iface %p, riid %s.\n", iface, debugstr_guid(riid));
1815
1816     return DDERR_ALREADYINITIALIZED;
1817 }
1818
1819 /*****************************************************************************
1820  * IDirectDraw7::FlipToGDISurface
1821  *
1822  * "Makes the surface that the GDI writes to the primary surface"
1823  * Looks like some windows specific thing we don't have to care about.
1824  * According to MSDN it permits GDI dialog boxes in FULLSCREEN mode. Good to
1825  * show error boxes ;)
1826  * Well, just return DD_OK.
1827  *
1828  * Returns:
1829  *  Always returns DD_OK
1830  *
1831  *****************************************************************************/
1832 static HRESULT WINAPI ddraw7_FlipToGDISurface(IDirectDraw7 *iface)
1833 {
1834     FIXME("iface %p stub!\n", iface);
1835
1836     return DD_OK;
1837 }
1838
1839 static HRESULT WINAPI ddraw4_FlipToGDISurface(IDirectDraw4 *iface)
1840 {
1841     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1842
1843     TRACE("iface %p.\n", iface);
1844
1845     return ddraw7_FlipToGDISurface(&ddraw->IDirectDraw7_iface);
1846 }
1847
1848 static HRESULT WINAPI ddraw2_FlipToGDISurface(IDirectDraw2 *iface)
1849 {
1850     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1851
1852     TRACE("iface %p.\n", iface);
1853
1854     return ddraw7_FlipToGDISurface(&ddraw->IDirectDraw7_iface);
1855 }
1856
1857 static HRESULT WINAPI ddraw1_FlipToGDISurface(IDirectDraw *iface)
1858 {
1859     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1860
1861     TRACE("iface %p.\n", iface);
1862
1863     return ddraw7_FlipToGDISurface(&ddraw->IDirectDraw7_iface);
1864 }
1865
1866 /*****************************************************************************
1867  * IDirectDraw7::WaitForVerticalBlank
1868  *
1869  * This method allows applications to get in sync with the vertical blank
1870  * interval.
1871  * The wormhole demo in the DirectX 7 sdk uses this call, and it doesn't
1872  * redraw the screen, most likely because of this stub
1873  *
1874  * Parameters:
1875  *  Flags: one of DDWAITVB_BLOCKBEGIN, DDWAITVB_BLOCKBEGINEVENT
1876  *         or DDWAITVB_BLOCKEND
1877  *  h: Not used, according to MSDN
1878  *
1879  * Returns:
1880  *  Always returns DD_OK
1881  *
1882  *****************************************************************************/
1883 static HRESULT WINAPI ddraw7_WaitForVerticalBlank(IDirectDraw7 *iface, DWORD Flags, HANDLE event)
1884 {
1885     static BOOL hide;
1886
1887     TRACE("iface %p, flags %#x, event %p.\n", iface, Flags, event);
1888
1889     /* This function is called often, so print the fixme only once */
1890     if(!hide)
1891     {
1892         FIXME("iface %p, flags %#x, event %p stub!\n", iface, Flags, event);
1893         hide = TRUE;
1894     }
1895
1896     /* MSDN says DDWAITVB_BLOCKBEGINEVENT is not supported */
1897     if(Flags & DDWAITVB_BLOCKBEGINEVENT)
1898         return DDERR_UNSUPPORTED; /* unchecked */
1899
1900     return DD_OK;
1901 }
1902
1903 static HRESULT WINAPI ddraw4_WaitForVerticalBlank(IDirectDraw4 *iface, DWORD flags, HANDLE event)
1904 {
1905     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1906
1907     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1908
1909     return ddraw7_WaitForVerticalBlank(&ddraw->IDirectDraw7_iface, flags, event);
1910 }
1911
1912 static HRESULT WINAPI ddraw2_WaitForVerticalBlank(IDirectDraw2 *iface, DWORD flags, HANDLE event)
1913 {
1914     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1915
1916     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1917
1918     return ddraw7_WaitForVerticalBlank(&ddraw->IDirectDraw7_iface, flags, event);
1919 }
1920
1921 static HRESULT WINAPI ddraw1_WaitForVerticalBlank(IDirectDraw *iface, DWORD flags, HANDLE event)
1922 {
1923     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1924
1925     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1926
1927     return ddraw7_WaitForVerticalBlank(&ddraw->IDirectDraw7_iface, flags, event);
1928 }
1929
1930 static HRESULT WINAPI ddraw7_GetScanLine(IDirectDraw7 *iface, DWORD *Scanline)
1931 {
1932     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
1933     struct wined3d_raster_status raster_status;
1934     HRESULT hr;
1935
1936     TRACE("iface %p, line %p.\n", iface, Scanline);
1937
1938     wined3d_mutex_lock();
1939     hr = wined3d_get_adapter_raster_status(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &raster_status);
1940     wined3d_mutex_unlock();
1941     if (FAILED(hr))
1942     {
1943         WARN("Failed to get raster status, hr %#x.\n", hr);
1944         return hr;
1945     }
1946
1947     *Scanline = raster_status.scan_line;
1948
1949     if (raster_status.in_vblank)
1950         return DDERR_VERTICALBLANKINPROGRESS;
1951
1952     return DD_OK;
1953 }
1954
1955 static HRESULT WINAPI ddraw4_GetScanLine(IDirectDraw4 *iface, DWORD *line)
1956 {
1957     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
1958
1959     TRACE("iface %p, line %p.\n", iface, line);
1960
1961     return ddraw7_GetScanLine(&ddraw->IDirectDraw7_iface, line);
1962 }
1963
1964 static HRESULT WINAPI ddraw2_GetScanLine(IDirectDraw2 *iface, DWORD *line)
1965 {
1966     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
1967
1968     TRACE("iface %p, line %p.\n", iface, line);
1969
1970     return ddraw7_GetScanLine(&ddraw->IDirectDraw7_iface, line);
1971 }
1972
1973 static HRESULT WINAPI ddraw1_GetScanLine(IDirectDraw *iface, DWORD *line)
1974 {
1975     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
1976
1977     TRACE("iface %p, line %p.\n", iface, line);
1978
1979     return ddraw7_GetScanLine(&ddraw->IDirectDraw7_iface, line);
1980 }
1981
1982 /*****************************************************************************
1983  * IDirectDraw7::TestCooperativeLevel
1984  *
1985  * Informs the application about the state of the video adapter, depending
1986  * on the cooperative level
1987  *
1988  * Returns:
1989  *  DD_OK if the device is in a sane state
1990  *  DDERR_NOEXCLUSIVEMODE or DDERR_EXCLUSIVEMODEALREADYSET
1991  *  if the state is not correct(See below)
1992  *
1993  *****************************************************************************/
1994 static HRESULT WINAPI ddraw7_TestCooperativeLevel(IDirectDraw7 *iface)
1995 {
1996     TRACE("iface %p.\n", iface);
1997
1998     return DD_OK;
1999 }
2000
2001 static HRESULT WINAPI ddraw4_TestCooperativeLevel(IDirectDraw4 *iface)
2002 {
2003     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
2004
2005     TRACE("iface %p.\n", iface);
2006
2007     return ddraw7_TestCooperativeLevel(&ddraw->IDirectDraw7_iface);
2008 }
2009
2010 /*****************************************************************************
2011  * IDirectDraw7::GetGDISurface
2012  *
2013  * Returns the surface that GDI is treating as the primary surface.
2014  * For Wine this is the front buffer
2015  *
2016  * Params:
2017  *  GDISurface: Address to write the surface pointer to
2018  *
2019  * Returns:
2020  *  DD_OK if the surface was found
2021  *  DDERR_NOTFOUND if the GDI surface wasn't found
2022  *
2023  *****************************************************************************/
2024 static HRESULT WINAPI ddraw7_GetGDISurface(IDirectDraw7 *iface, IDirectDrawSurface7 **GDISurface)
2025 {
2026     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
2027
2028     TRACE("iface %p, surface %p.\n", iface, GDISurface);
2029
2030     wined3d_mutex_lock();
2031
2032     if (!(*GDISurface = &ddraw->primary->IDirectDrawSurface7_iface))
2033     {
2034         WARN("Primary not created yet.\n");
2035         wined3d_mutex_unlock();
2036         return DDERR_NOTFOUND;
2037     }
2038     IDirectDrawSurface7_AddRef(*GDISurface);
2039
2040     wined3d_mutex_unlock();
2041
2042     return DD_OK;
2043 }
2044
2045 static HRESULT WINAPI ddraw4_GetGDISurface(IDirectDraw4 *iface, IDirectDrawSurface4 **surface)
2046 {
2047     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
2048     struct ddraw_surface *surface_impl;
2049     IDirectDrawSurface7 *surface7;
2050     HRESULT hr;
2051
2052     TRACE("iface %p, surface %p.\n", iface, surface);
2053
2054     hr = ddraw7_GetGDISurface(&ddraw->IDirectDraw7_iface, &surface7);
2055     if (FAILED(hr))
2056     {
2057         *surface = NULL;
2058         return hr;
2059     }
2060     surface_impl = impl_from_IDirectDrawSurface7(surface7);
2061     *surface = &surface_impl->IDirectDrawSurface4_iface;
2062     IDirectDrawSurface4_AddRef(*surface);
2063     IDirectDrawSurface7_Release(surface7);
2064
2065     return hr;
2066 }
2067
2068 static HRESULT WINAPI ddraw2_GetGDISurface(IDirectDraw2 *iface, IDirectDrawSurface **surface)
2069 {
2070     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
2071     struct ddraw_surface *surface_impl;
2072     IDirectDrawSurface7 *surface7;
2073     HRESULT hr;
2074
2075     TRACE("iface %p, surface %p.\n", iface, surface);
2076
2077     hr = ddraw7_GetGDISurface(&ddraw->IDirectDraw7_iface, &surface7);
2078     if (FAILED(hr))
2079     {
2080         *surface = NULL;
2081         return hr;
2082     }
2083     surface_impl = impl_from_IDirectDrawSurface7(surface7);
2084     *surface = &surface_impl->IDirectDrawSurface_iface;
2085     IDirectDrawSurface_AddRef(*surface);
2086     IDirectDrawSurface7_Release(surface7);
2087
2088     return hr;
2089 }
2090
2091 static HRESULT WINAPI ddraw1_GetGDISurface(IDirectDraw *iface, IDirectDrawSurface **surface)
2092 {
2093     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
2094     struct ddraw_surface *surface_impl;
2095     IDirectDrawSurface7 *surface7;
2096     HRESULT hr;
2097
2098     TRACE("iface %p, surface %p.\n", iface, surface);
2099
2100     hr = ddraw7_GetGDISurface(&ddraw->IDirectDraw7_iface, &surface7);
2101     if (FAILED(hr))
2102     {
2103         *surface = NULL;
2104         return hr;
2105     }
2106     surface_impl = impl_from_IDirectDrawSurface7(surface7);
2107     *surface = &surface_impl->IDirectDrawSurface_iface;
2108     IDirectDrawSurface_AddRef(*surface);
2109     IDirectDrawSurface7_Release(surface7);
2110
2111     return hr;
2112 }
2113
2114 struct displaymodescallback_context
2115 {
2116     LPDDENUMMODESCALLBACK func;
2117     void *context;
2118 };
2119
2120 static HRESULT CALLBACK EnumDisplayModesCallbackThunk(DDSURFACEDESC2 *surface_desc, void *context)
2121 {
2122     struct displaymodescallback_context *cbcontext = context;
2123     DDSURFACEDESC desc;
2124
2125     DDSD2_to_DDSD(surface_desc, &desc);
2126     return cbcontext->func(&desc, cbcontext->context);
2127 }
2128
2129 /*****************************************************************************
2130  * IDirectDraw7::EnumDisplayModes
2131  *
2132  * Enumerates the supported Display modes. The modes can be filtered with
2133  * the DDSD parameter.
2134  *
2135  * Params:
2136  *  Flags: can be DDEDM_REFRESHRATES and DDEDM_STANDARDVGAMODES. For old ddraw
2137  *         versions (3 and older?) this is reserved and must be 0.
2138  *  DDSD: Surface description to filter the modes
2139  *  Context: Pointer passed back to the callback function
2140  *  cb: Application-provided callback function
2141  *
2142  * Returns:
2143  *  DD_OK on success
2144  *  DDERR_INVALIDPARAMS if the callback wasn't set
2145  *
2146  *****************************************************************************/
2147 static HRESULT WINAPI ddraw7_EnumDisplayModes(IDirectDraw7 *iface, DWORD Flags,
2148         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMMODESCALLBACK2 cb)
2149 {
2150     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
2151     struct wined3d_display_mode *enum_modes = NULL;
2152     struct wined3d_display_mode mode;
2153     unsigned int modenum, fmt;
2154     DDSURFACEDESC2 callback_sd;
2155     unsigned enum_mode_count = 0, enum_mode_array_size = 0;
2156     DDPIXELFORMAT pixelformat;
2157
2158     static const enum wined3d_format_id checkFormatList[] =
2159     {
2160         WINED3DFMT_B8G8R8X8_UNORM,
2161         WINED3DFMT_B5G6R5_UNORM,
2162         WINED3DFMT_P8_UINT,
2163     };
2164
2165     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2166             iface, Flags, DDSD, Context, cb);
2167
2168     if (!cb)
2169         return DDERR_INVALIDPARAMS;
2170
2171     wined3d_mutex_lock();
2172     if(!(Flags & DDEDM_REFRESHRATES))
2173     {
2174         enum_mode_array_size = 16;
2175         enum_modes = HeapAlloc(GetProcessHeap(), 0, sizeof(*enum_modes) * enum_mode_array_size);
2176         if (!enum_modes)
2177         {
2178             ERR("Out of memory\n");
2179             wined3d_mutex_unlock();
2180             return DDERR_OUTOFMEMORY;
2181         }
2182     }
2183
2184     pixelformat.dwSize = sizeof(pixelformat);
2185     for(fmt = 0; fmt < (sizeof(checkFormatList) / sizeof(checkFormatList[0])); fmt++)
2186     {
2187         modenum = 0;
2188         while (wined3d_enum_adapter_modes(ddraw->wined3d, WINED3DADAPTER_DEFAULT, checkFormatList[fmt],
2189                 WINED3D_SCANLINE_ORDERING_UNKNOWN, modenum++, &mode) == WINED3D_OK)
2190         {
2191             PixelFormat_WineD3DtoDD(&pixelformat, mode.format_id);
2192             if (DDSD)
2193             {
2194                 if (DDSD->dwFlags & DDSD_WIDTH && mode.width != DDSD->dwWidth)
2195                     continue;
2196                 if (DDSD->dwFlags & DDSD_HEIGHT && mode.height != DDSD->dwHeight)
2197                     continue;
2198                 if (DDSD->dwFlags & DDSD_REFRESHRATE && mode.refresh_rate != DDSD->u2.dwRefreshRate)
2199                     continue;
2200                 if (DDSD->dwFlags & DDSD_PIXELFORMAT
2201                         && pixelformat.u1.dwRGBBitCount != DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount)
2202                     continue;
2203             }
2204
2205             if(!(Flags & DDEDM_REFRESHRATES))
2206             {
2207                 /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
2208                  * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
2209                  * to be reduced to a single unique result in such case.
2210                  */
2211                 BOOL found = FALSE;
2212                 unsigned i;
2213
2214                 for (i = 0; i < enum_mode_count; i++)
2215                 {
2216                     if (enum_modes[i].width == mode.width && enum_modes[i].height == mode.height
2217                             && enum_modes[i].format_id == mode.format_id)
2218                     {
2219                         found = TRUE;
2220                         break;
2221                     }
2222                 }
2223
2224                 if(found) continue;
2225             }
2226
2227             memset(&callback_sd, 0, sizeof(callback_sd));
2228             callback_sd.dwSize = sizeof(callback_sd);
2229             callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2230
2231             callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH|DDSD_REFRESHRATE;
2232             if (Flags & DDEDM_REFRESHRATES)
2233                 callback_sd.u2.dwRefreshRate = mode.refresh_rate;
2234
2235             callback_sd.dwWidth = mode.width;
2236             callback_sd.dwHeight = mode.height;
2237
2238             callback_sd.u4.ddpfPixelFormat=pixelformat;
2239
2240             /* Calc pitch and DWORD align like MSDN says */
2241             callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.width;
2242             callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;
2243
2244             TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
2245               callback_sd.u2.dwRefreshRate);
2246
2247             if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
2248             {
2249                 TRACE("Application asked to terminate the enumeration\n");
2250                 HeapFree(GetProcessHeap(), 0, enum_modes);
2251                 wined3d_mutex_unlock();
2252                 return DD_OK;
2253             }
2254
2255             if(!(Flags & DDEDM_REFRESHRATES))
2256             {
2257                 if (enum_mode_count == enum_mode_array_size)
2258                 {
2259                     struct wined3d_display_mode *new_enum_modes;
2260
2261                     enum_mode_array_size *= 2;
2262                     new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes,
2263                             sizeof(*new_enum_modes) * enum_mode_array_size);
2264                     if (!new_enum_modes)
2265                     {
2266                         ERR("Out of memory\n");
2267                         HeapFree(GetProcessHeap(), 0, enum_modes);
2268                         wined3d_mutex_unlock();
2269                         return DDERR_OUTOFMEMORY;
2270                     }
2271
2272                     enum_modes = new_enum_modes;
2273                 }
2274
2275                 enum_modes[enum_mode_count++] = mode;
2276             }
2277         }
2278     }
2279
2280     TRACE("End of enumeration\n");
2281     HeapFree(GetProcessHeap(), 0, enum_modes);
2282     wined3d_mutex_unlock();
2283
2284     return DD_OK;
2285 }
2286
2287 static HRESULT WINAPI ddraw4_EnumDisplayModes(IDirectDraw4 *iface, DWORD flags,
2288         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMMODESCALLBACK2 callback)
2289 {
2290     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
2291
2292     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2293             iface, flags, surface_desc, context, callback);
2294
2295     return ddraw7_EnumDisplayModes(&ddraw->IDirectDraw7_iface, flags, surface_desc, context, callback);
2296 }
2297
2298 static HRESULT WINAPI ddraw2_EnumDisplayModes(IDirectDraw2 *iface, DWORD flags,
2299         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2300 {
2301     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
2302     struct displaymodescallback_context cbcontext;
2303     DDSURFACEDESC2 surface_desc2;
2304
2305     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2306             iface, flags, surface_desc, context, callback);
2307
2308     cbcontext.func = callback;
2309     cbcontext.context = context;
2310
2311     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
2312     return ddraw7_EnumDisplayModes(&ddraw->IDirectDraw7_iface, flags,
2313             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumDisplayModesCallbackThunk);
2314 }
2315
2316 static HRESULT WINAPI ddraw1_EnumDisplayModes(IDirectDraw *iface, DWORD flags,
2317         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2318 {
2319     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
2320     struct displaymodescallback_context cbcontext;
2321     DDSURFACEDESC2 surface_desc2;
2322
2323     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2324             iface, flags, surface_desc, context, callback);
2325
2326     cbcontext.func = callback;
2327     cbcontext.context = context;
2328
2329     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
2330     return ddraw7_EnumDisplayModes(&ddraw->IDirectDraw7_iface, flags,
2331             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumDisplayModesCallbackThunk);
2332 }
2333
2334 /*****************************************************************************
2335  * IDirectDraw7::EvaluateMode
2336  *
2337  * Used with IDirectDraw7::StartModeTest to test video modes.
2338  * EvaluateMode is used to pass or fail a mode, and continue with the next
2339  * mode
2340  *
2341  * Params:
2342  *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
2343  *  Timeout: Returns the amount of seconds left before the mode would have
2344  *           been failed automatically
2345  *
2346  * Returns:
2347  *  This implementation always DD_OK, because it's a stub
2348  *
2349  *****************************************************************************/
2350 static HRESULT WINAPI ddraw7_EvaluateMode(IDirectDraw7 *iface, DWORD Flags, DWORD *Timeout)
2351 {
2352     FIXME("iface %p, flags %#x, timeout %p stub!\n", iface, Flags, Timeout);
2353
2354     /* When implementing this, implement it in WineD3D */
2355
2356     return DD_OK;
2357 }
2358
2359 /*****************************************************************************
2360  * IDirectDraw7::GetDeviceIdentifier
2361  *
2362  * Returns the device identifier, which gives information about the driver
2363  * Our device identifier is defined at the beginning of this file.
2364  *
2365  * Params:
2366  *  DDDI: Address for the returned structure
2367  *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
2368  *
2369  * Returns:
2370  *  On success it returns DD_OK
2371  *  DDERR_INVALIDPARAMS if DDDI is NULL
2372  *
2373  *****************************************************************************/
2374 static HRESULT WINAPI ddraw7_GetDeviceIdentifier(IDirectDraw7 *iface,
2375         DDDEVICEIDENTIFIER2 *DDDI, DWORD Flags)
2376 {
2377     TRACE("iface %p, device_identifier %p, flags %#x.\n", iface, DDDI, Flags);
2378
2379     if(!DDDI)
2380         return DDERR_INVALIDPARAMS;
2381
2382     /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
2383      * host adapter, if there's a secondary 3D adapter. This doesn't apply
2384      * to any modern hardware, nor is it interesting for Wine, so ignore it.
2385      * Size of DDDEVICEIDENTIFIER2 may be aligned to 8 bytes and thus 4
2386      * bytes too long. So only copy the relevant part of the structure
2387      */
2388
2389     memcpy(DDDI, &deviceidentifier, FIELD_OFFSET(DDDEVICEIDENTIFIER2, dwWHQLLevel) + sizeof(DWORD));
2390     return DD_OK;
2391 }
2392
2393 static HRESULT WINAPI ddraw4_GetDeviceIdentifier(IDirectDraw4 *iface,
2394         DDDEVICEIDENTIFIER *identifier, DWORD flags)
2395 {
2396     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
2397     DDDEVICEIDENTIFIER2 identifier2;
2398     HRESULT hr;
2399
2400     TRACE("iface %p, identifier %p, flags %#x.\n", iface, identifier, flags);
2401
2402     hr = ddraw7_GetDeviceIdentifier(&ddraw->IDirectDraw7_iface, &identifier2, flags);
2403     DDRAW_Convert_DDDEVICEIDENTIFIER_2_To_1(&identifier2, identifier);
2404
2405     return hr;
2406 }
2407
2408 /*****************************************************************************
2409  * IDirectDraw7::GetSurfaceFromDC
2410  *
2411  * Returns the Surface for a GDI device context handle.
2412  * Is this related to IDirectDrawSurface::GetDC ???
2413  *
2414  * Params:
2415  *  hdc: hdc to return the surface for
2416  *  Surface: Address to write the surface pointer to
2417  *
2418  * Returns:
2419  *  Always returns DD_OK because it's a stub
2420  *
2421  *****************************************************************************/
2422 static HRESULT WINAPI ddraw7_GetSurfaceFromDC(IDirectDraw7 *iface, HDC hdc,
2423         IDirectDrawSurface7 **Surface)
2424 {
2425     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
2426     struct wined3d_surface *wined3d_surface;
2427     struct ddraw_surface *surface_impl;
2428     HRESULT hr;
2429
2430     TRACE("iface %p, dc %p, surface %p.\n", iface, hdc, Surface);
2431
2432     if (!Surface) return E_INVALIDARG;
2433
2434     hr = wined3d_device_get_surface_from_dc(ddraw->wined3d_device, hdc, &wined3d_surface);
2435     if (FAILED(hr))
2436     {
2437         TRACE("No surface found for dc %p.\n", hdc);
2438         *Surface = NULL;
2439         return DDERR_NOTFOUND;
2440     }
2441
2442     surface_impl = wined3d_surface_get_parent(wined3d_surface);
2443     *Surface = &surface_impl->IDirectDrawSurface7_iface;
2444     IDirectDrawSurface7_AddRef(*Surface);
2445     TRACE("Returning surface %p.\n", Surface);
2446     return DD_OK;
2447 }
2448
2449 static HRESULT WINAPI ddraw4_GetSurfaceFromDC(IDirectDraw4 *iface, HDC dc,
2450         IDirectDrawSurface4 **surface)
2451 {
2452     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
2453     struct ddraw_surface *surface_impl;
2454     IDirectDrawSurface7 *surface7;
2455     HRESULT hr;
2456
2457     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2458
2459     if (!surface) return E_INVALIDARG;
2460
2461     hr = ddraw7_GetSurfaceFromDC(&ddraw->IDirectDraw7_iface, dc, &surface7);
2462     if (FAILED(hr))
2463     {
2464         *surface = NULL;
2465         return hr;
2466     }
2467     surface_impl = impl_from_IDirectDrawSurface7(surface7);
2468     /* Tests say this is true */
2469     *surface = (IDirectDrawSurface4 *)&surface_impl->IDirectDrawSurface_iface;
2470     IDirectDrawSurface_AddRef(&surface_impl->IDirectDrawSurface_iface);
2471     IDirectDrawSurface7_Release(surface7);
2472
2473     return hr;
2474 }
2475
2476 /*****************************************************************************
2477  * IDirectDraw7::RestoreAllSurfaces
2478  *
2479  * Calls the restore method of all surfaces
2480  *
2481  * Params:
2482  *
2483  * Returns:
2484  *  Always returns DD_OK because it's a stub
2485  *
2486  *****************************************************************************/
2487 static HRESULT WINAPI ddraw7_RestoreAllSurfaces(IDirectDraw7 *iface)
2488 {
2489     FIXME("iface %p stub!\n", iface);
2490
2491     /* This isn't hard to implement: Enumerate all WineD3D surfaces,
2492      * get their parent and call their restore method. Do not implement
2493      * it in WineD3D, as restoring a surface means re-creating the
2494      * WineD3DDSurface
2495      */
2496     return DD_OK;
2497 }
2498
2499 static HRESULT WINAPI ddraw4_RestoreAllSurfaces(IDirectDraw4 *iface)
2500 {
2501     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
2502
2503     TRACE("iface %p.\n", iface);
2504
2505     return ddraw7_RestoreAllSurfaces(&ddraw->IDirectDraw7_iface);
2506 }
2507
2508 /*****************************************************************************
2509  * IDirectDraw7::StartModeTest
2510  *
2511  * Tests the specified video modes to update the system registry with
2512  * refresh rate information. StartModeTest starts the mode test,
2513  * EvaluateMode is used to fail or pass a mode. If EvaluateMode
2514  * isn't called within 15 seconds, the mode is failed automatically
2515  *
2516  * As refresh rates are handled by the X server, I don't think this
2517  * Method is important
2518  *
2519  * Params:
2520  *  Modes: An array of mode specifications
2521  *  NumModes: The number of modes in Modes
2522  *  Flags: Some flags...
2523  *
2524  * Returns:
2525  *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
2526  *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
2527  *  otherwise DD_OK
2528  *
2529  *****************************************************************************/
2530 static HRESULT WINAPI ddraw7_StartModeTest(IDirectDraw7 *iface, SIZE *Modes, DWORD NumModes, DWORD Flags)
2531 {
2532     FIXME("iface %p, modes %p, mode_count %u, flags %#x partial stub!\n",
2533             iface, Modes, NumModes, Flags);
2534
2535     /* This looks sane */
2536     if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;
2537
2538     /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
2539      * As it is not, DDERR_TESTFINISHED is returned
2540      * (hopefully that's correct
2541      *
2542     if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
2543      * well, that value doesn't (yet) exist in the wine headers, so ignore it
2544      */
2545
2546     return DD_OK;
2547 }
2548
2549 /*****************************************************************************
2550  * ddraw_create_surface
2551  *
2552  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
2553  * with the passed parameters.
2554  *
2555  * Params:
2556  *  DDSD: Description of the surface to create
2557  *  Surf: Address to store the interface pointer at
2558  *
2559  * Returns:
2560  *  DD_OK on success
2561  *
2562  *****************************************************************************/
2563 static HRESULT ddraw_create_surface(struct ddraw *ddraw, DDSURFACEDESC2 *pDDSD,
2564         struct ddraw_surface **surface, UINT level, UINT version)
2565 {
2566     HRESULT hr;
2567
2568     TRACE("ddraw %p, surface_desc %p, surface %p, level %u.\n",
2569             ddraw, pDDSD, surface, level);
2570
2571     if (TRACE_ON(ddraw))
2572     {
2573         TRACE("Requesting surface desc:\n");
2574         DDRAW_dump_surface_desc(pDDSD);
2575     }
2576
2577     if ((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE) && DefaultSurfaceType != WINED3D_SURFACE_TYPE_OPENGL)
2578     {
2579         WARN("The application requests a 3D capable surface, but a non-OpenGL surface type was set in the registry.\n");
2580         /* Do not fail surface creation, only fail 3D device creation. */
2581     }
2582
2583     /* Create the Surface object */
2584     *surface = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**surface));
2585     if (!*surface)
2586     {
2587         ERR("Failed to allocate surface memory.\n");
2588         return DDERR_OUTOFVIDEOMEMORY;
2589     }
2590
2591     hr = ddraw_surface_init(*surface, ddraw, pDDSD, level, version);
2592     if (FAILED(hr))
2593     {
2594         WARN("Failed to initialize surface, hr %#x.\n", hr);
2595         HeapFree(GetProcessHeap(), 0, *surface);
2596         return hr;
2597     }
2598
2599     /* Increase the surface counter, and attach the surface */
2600     list_add_head(&ddraw->surface_list, &(*surface)->surface_list_entry);
2601
2602     TRACE("Created surface %p.\n", *surface);
2603
2604     return DD_OK;
2605 }
2606
2607 static HRESULT CDECL ddraw_reset_enum_callback(struct wined3d_resource *resource)
2608 {
2609     return DD_OK;
2610 }
2611
2612 /*****************************************************************************
2613  * IDirectDraw7::CreateSurface
2614  *
2615  * Creates a new IDirectDrawSurface object and returns its interface.
2616  *
2617  * The surface connections with wined3d are a bit tricky. Basically it works
2618  * like this:
2619  *
2620  * |------------------------|               |-----------------|
2621  * | DDraw surface          |               | WineD3DSurface  |
2622  * |                        |               |                 |
2623  * |        WineD3DSurface  |-------------->|                 |
2624  * |        Child           |<------------->| Parent          |
2625  * |------------------------|               |-----------------|
2626  *
2627  * The DDraw surface is the parent of the wined3d surface, and it releases
2628  * the WineD3DSurface when the ddraw surface is destroyed.
2629  *
2630  * However, for all surfaces which can be in a container in WineD3D,
2631  * we have to do this. These surfaces are usually complex surfaces,
2632  * so this concerns primary surfaces with a front and a back buffer,
2633  * and textures.
2634  *
2635  * |------------------------|               |-----------------|
2636  * | DDraw surface          |               | Container       |
2637  * |                        |               |                 |
2638  * |                  Child |<------------->| Parent          |
2639  * |                Texture |<------------->|                 |
2640  * |         WineD3DSurface |<----|         |          Levels |<--|
2641  * | Complex connection     |     |         |                 |   |
2642  * |------------------------|     |         |-----------------|   |
2643  *  ^                             |                               |
2644  *  |                             |                               |
2645  *  |                             |                               |
2646  *  |    |------------------|     |         |-----------------|   |
2647  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2648  *  |    |                  |               |                 |   |
2649  *  |    |            Child |<------------->| Parent          |   |
2650  *  |    |                  |               |       Container |<--|
2651  *  |    |------------------|               |-----------------|   |
2652  *  |                                                             |
2653  *  |   |----------------------|                                  |
2654  *  |   | DDraw surface 2      |                                  |
2655  *  |   |                      |                                  |
2656  *  |<->| Complex root   Child |                                  |
2657  *  |   |              Texture |                                  |
2658  *  |   |       WineD3DSurface |<----|                            |
2659  *  |   |----------------------|     |                            |
2660  *  |                                |                            |
2661  *  |    |---------------------|     |      |-----------------|   |
2662  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2663  *  |    |                     |            |                 |   |
2664  *  |    |               Child |<---------->| Parent          |   |
2665  *  |    |---------------------|            |       Container |<--|
2666  *  |                                       |-----------------|   |
2667  *  |                                                             |
2668  *  |             ---More surfaces can follow---                  |
2669  *
2670  * The reason is that the IWineD3DSwapchain(render target container)
2671  * and the IWineD3DTexure(Texture container) release the parents
2672  * of their surface's children, but by releasing the complex root
2673  * the surfaces which are complexly attached to it are destroyed
2674  * too. See IDirectDrawSurface::Release for a more detailed
2675  * explanation.
2676  *
2677  * Params:
2678  *  DDSD: Description of the surface to create
2679  *  Surf: Address to store the interface pointer at
2680  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2681  *            aggregation, so it has to be NULL
2682  *
2683  * Returns:
2684  *  DD_OK on success
2685  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2686  *  DDERR_* if an error occurs
2687  *
2688  *****************************************************************************/
2689 static HRESULT CreateSurface(struct ddraw *ddraw, DDSURFACEDESC2 *DDSD,
2690         struct ddraw_surface **surface, IUnknown *UnkOuter, UINT version)
2691 {
2692     struct ddraw_surface *object = NULL;
2693     struct wined3d_display_mode mode;
2694     HRESULT hr;
2695     DDSURFACEDESC2 desc2;
2696     const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
2697
2698     TRACE("ddraw %p, surface_desc %p, surface %p, outer_unknown %p.\n", ddraw, DDSD, surface, UnkOuter);
2699
2700     /* Some checks before we start */
2701     if (TRACE_ON(ddraw))
2702     {
2703         TRACE(" (%p) Requesting surface desc :\n", ddraw);
2704         DDRAW_dump_surface_desc(DDSD);
2705     }
2706
2707     if (UnkOuter != NULL)
2708     {
2709         FIXME("(%p) : outer != NULL?\n", ddraw);
2710         return CLASS_E_NOAGGREGATION; /* unchecked */
2711     }
2712
2713     if (!surface)
2714     {
2715         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", ddraw);
2716         return E_POINTER; /* unchecked */
2717     }
2718
2719     if (!(DDSD->dwFlags & DDSD_CAPS))
2720     {
2721         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2722         DDSD->dwFlags |= DDSD_CAPS;
2723     }
2724
2725     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2726     {
2727         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2728         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2729     }
2730
2731     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2732     {
2733         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2734         WARN("(%p) Null surface pointer specified, ignore it!\n", ddraw);
2735         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2736     }
2737
2738     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2739        !(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
2740     {
2741         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n",
2742                 ddraw);
2743         *surface = NULL;
2744         return DDERR_NOEXCLUSIVEMODE;
2745     }
2746
2747     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE))
2748     {
2749         WARN("Application wanted to create back buffer primary surface\n");
2750         return DDERR_INVALIDCAPS;
2751     }
2752
2753     if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
2754     {
2755         /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
2756         WARN("Application tries to put the surface in both system and video memory\n");
2757         *surface = NULL;
2758         return DDERR_INVALIDCAPS;
2759     }
2760
2761     /* Check cube maps but only if the size includes them */
2762     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2763     {
2764         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
2765            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
2766         {
2767             WARN("Cube map faces requested without cube map flag\n");
2768             return DDERR_INVALIDCAPS;
2769         }
2770         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2771            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
2772         {
2773             WARN("Cube map without faces requested\n");
2774             return DDERR_INVALIDPARAMS;
2775         }
2776
2777         /* Quick tests confirm those can be created, but we don't do that yet */
2778         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2779            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
2780         {
2781             FIXME("Partial cube maps not supported yet\n");
2782         }
2783     }
2784
2785     /* According to the msdn this flag is ignored by CreateSurface */
2786     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2787         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2788
2789     /* Modify some flags */
2790     copy_to_surfacedesc2(&desc2, DDSD);
2791     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
2792
2793     /* Get the video mode from WineD3D - we will need it */
2794     if (FAILED(hr = wined3d_get_adapter_display_mode(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &mode, NULL)))
2795     {
2796         ERR("Failed to get display mode, hr %#x.\n", hr);
2797
2798         switch (ddraw->orig_bpp)
2799         {
2800             case 8:
2801                 mode.format_id = WINED3DFMT_P8_UINT;
2802                 break;
2803
2804             case 15:
2805                 mode.format_id = WINED3DFMT_B5G5R5X1_UNORM;
2806                 break;
2807
2808             case 16:
2809                 mode.format_id = WINED3DFMT_B5G6R5_UNORM;
2810                 break;
2811
2812             case 24:
2813                 mode.format_id = WINED3DFMT_B8G8R8_UNORM;
2814                 break;
2815
2816             case 32:
2817                 mode.format_id = WINED3DFMT_B8G8R8X8_UNORM;
2818                 break;
2819         }
2820         mode.width = ddraw->orig_width;
2821         mode.height = ddraw->orig_height;
2822     }
2823
2824     /* No pixelformat given? Use the current screen format */
2825     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
2826     {
2827         desc2.dwFlags |= DDSD_PIXELFORMAT;
2828         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
2829
2830         PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, mode.format_id);
2831     }
2832
2833     /* No Width or no Height? Use the original screen size
2834      */
2835     if(!(desc2.dwFlags & DDSD_WIDTH) ||
2836        !(desc2.dwFlags & DDSD_HEIGHT) )
2837     {
2838         /* Invalid for non-render targets */
2839         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
2840         {
2841             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
2842             *surface = NULL;
2843             return DDERR_INVALIDPARAMS;
2844         }
2845
2846         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
2847         desc2.dwWidth = mode.width;
2848         desc2.dwHeight = mode.height;
2849     }
2850
2851     if (!desc2.dwWidth || !desc2.dwHeight)
2852         return DDERR_INVALIDPARAMS;
2853
2854     /* Mipmap count fixes */
2855     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2856     {
2857         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
2858         {
2859             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
2860             {
2861                 /* Mipmap count is given, should not be 0 */
2862                 if( desc2.u2.dwMipMapCount == 0 )
2863                     return DDERR_INVALIDPARAMS;
2864             }
2865             else
2866             {
2867                 /* Undocumented feature: Create sublevels until
2868                  * either the width or the height is 1
2869                  */
2870                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
2871                             desc2.dwWidth : desc2.dwHeight;
2872                 desc2.u2.dwMipMapCount = 0;
2873                 while( min )
2874                 {
2875                     desc2.u2.dwMipMapCount += 1;
2876                     min >>= 1;
2877                 }
2878             }
2879         }
2880         else
2881         {
2882             /* Not-complex mipmap -> Mipmapcount = 1 */
2883             desc2.u2.dwMipMapCount = 1;
2884         }
2885
2886         /* There's a mipmap count in the created surface in any case */
2887         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
2888     }
2889     /* If no mipmap is given, the texture has only one level */
2890
2891     /* The first surface is a front buffer, the back buffer is created afterwards */
2892     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
2893     {
2894         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
2895     }
2896
2897     /* The root surface in a cube map is positive x */
2898     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2899     {
2900         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
2901         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
2902     }
2903
2904     if ((desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) && (ddraw->cooperative_level & DDSCL_EXCLUSIVE))
2905     {
2906         struct wined3d_swapchain_desc swapchain_desc;
2907
2908         hr = wined3d_swapchain_get_desc(ddraw->wined3d_swapchain, &swapchain_desc);
2909         if (FAILED(hr))
2910         {
2911             ERR("Failed to get present parameters.\n");
2912             return hr;
2913         }
2914
2915         swapchain_desc.backbuffer_width = mode.width;
2916         swapchain_desc.backbuffer_height = mode.height;
2917         swapchain_desc.backbuffer_format = mode.format_id;
2918
2919         hr = wined3d_device_reset(ddraw->wined3d_device,
2920                 &swapchain_desc, NULL, ddraw_reset_enum_callback);
2921         if (FAILED(hr))
2922         {
2923             ERR("Failed to reset device.\n");
2924             return hr;
2925         }
2926     }
2927
2928     /* Create the first surface */
2929     hr = ddraw_create_surface(ddraw, &desc2, &object, 0, version);
2930     if (FAILED(hr))
2931     {
2932         WARN("ddraw_create_surface failed, hr %#x.\n", hr);
2933         return hr;
2934     }
2935     object->is_complex_root = TRUE;
2936
2937     *surface = object;
2938
2939     /* Create Additional surfaces if necessary
2940      * This applies to Primary surfaces which have a back buffer count
2941      * set, but not to mipmap textures. In case of Mipmap textures,
2942      * wineD3D takes care of the creation of additional surfaces
2943      */
2944     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
2945     {
2946         struct ddraw_surface *last = object;
2947         UINT i;
2948
2949         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
2950         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
2951         desc2.dwBackBufferCount = 0;
2952
2953         for (i = 0; i < DDSD->dwBackBufferCount; ++i)
2954         {
2955             struct ddraw_surface *object2 = NULL;
2956
2957             if (FAILED(hr = ddraw_create_surface(ddraw, &desc2, &object2, 0, version)))
2958             {
2959                 if (version == 7)
2960                     IDirectDrawSurface7_Release(&object->IDirectDrawSurface7_iface);
2961                 else if (version == 4)
2962                     IDirectDrawSurface4_Release(&object->IDirectDrawSurface4_iface);
2963                 else
2964                     IDirectDrawSurface_Release(&object->IDirectDrawSurface_iface);
2965
2966                 return hr;
2967             }
2968
2969             /* Add the new surface to the complex attachment array. */
2970             last->complex_array[0] = object2;
2971             last = object2;
2972
2973             /* Remove the (possible) back buffer cap from the new surface
2974              * description, because only one surface in the flipping chain is a
2975              * back buffer, one is a front buffer, the others are just primary
2976              * surfaces. */
2977             desc2.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2978         }
2979     }
2980
2981     if (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
2982         ddraw->primary = object;
2983
2984     /* Create a WineD3DTexture if a texture was requested */
2985     if (desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
2986         ddraw_surface_create_texture(object);
2987
2988     return hr;
2989 }
2990
2991 static HRESULT WINAPI ddraw7_CreateSurface(IDirectDraw7 *iface, DDSURFACEDESC2 *surface_desc,
2992         IDirectDrawSurface7 **surface, IUnknown *outer_unknown)
2993 {
2994     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
2995     struct ddraw_surface *impl;
2996     HRESULT hr;
2997
2998     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
2999             iface, surface_desc, surface, outer_unknown);
3000
3001     wined3d_mutex_lock();
3002
3003     if (!(ddraw->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3004     {
3005         WARN("Cooperative level not set.\n");
3006         wined3d_mutex_unlock();
3007         return DDERR_NOCOOPERATIVELEVELSET;
3008     }
3009
3010     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3011     {
3012         WARN("Application supplied invalid surface descriptor\n");
3013         wined3d_mutex_unlock();
3014         return DDERR_INVALIDPARAMS;
3015     }
3016
3017     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3018     {
3019         if (TRACE_ON(ddraw))
3020         {
3021             TRACE(" (%p) Requesting surface desc :\n", iface);
3022             DDRAW_dump_surface_desc(surface_desc);
3023         }
3024
3025         WARN("Application tried to create an explicit front or back buffer\n");
3026         wined3d_mutex_unlock();
3027         return DDERR_INVALIDCAPS;
3028     }
3029
3030     hr = CreateSurface(ddraw, surface_desc, &impl, outer_unknown, 7);
3031     wined3d_mutex_unlock();
3032     if (FAILED(hr))
3033     {
3034         *surface = NULL;
3035         return hr;
3036     }
3037
3038     *surface = &impl->IDirectDrawSurface7_iface;
3039     IDirectDraw7_AddRef(iface);
3040     impl->ifaceToRelease = (IUnknown *)iface;
3041
3042     return hr;
3043 }
3044
3045 static HRESULT WINAPI ddraw4_CreateSurface(IDirectDraw4 *iface,
3046         DDSURFACEDESC2 *surface_desc, IDirectDrawSurface4 **surface, IUnknown *outer_unknown)
3047 {
3048     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
3049     struct ddraw_surface *impl;
3050     HRESULT hr;
3051
3052     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3053             iface, surface_desc, surface, outer_unknown);
3054
3055     wined3d_mutex_lock();
3056
3057     if (!(ddraw->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3058     {
3059         WARN("Cooperative level not set.\n");
3060         wined3d_mutex_unlock();
3061         return DDERR_NOCOOPERATIVELEVELSET;
3062     }
3063
3064     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3065     {
3066         WARN("Application supplied invalid surface descriptor\n");
3067         wined3d_mutex_unlock();
3068         return DDERR_INVALIDPARAMS;
3069     }
3070
3071     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3072     {
3073         if (TRACE_ON(ddraw))
3074         {
3075             TRACE(" (%p) Requesting surface desc :\n", iface);
3076             DDRAW_dump_surface_desc(surface_desc);
3077         }
3078
3079         WARN("Application tried to create an explicit front or back buffer\n");
3080         wined3d_mutex_unlock();
3081         return DDERR_INVALIDCAPS;
3082     }
3083
3084     hr = CreateSurface(ddraw, surface_desc, &impl, outer_unknown, 4);
3085     wined3d_mutex_unlock();
3086     if (FAILED(hr))
3087     {
3088         *surface = NULL;
3089         return hr;
3090     }
3091
3092     *surface = &impl->IDirectDrawSurface4_iface;
3093     IDirectDraw4_AddRef(iface);
3094     impl->ifaceToRelease = (IUnknown *)iface;
3095
3096     return hr;
3097 }
3098
3099 static HRESULT WINAPI ddraw2_CreateSurface(IDirectDraw2 *iface,
3100         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3101 {
3102     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
3103     struct ddraw_surface *impl;
3104     HRESULT hr;
3105     DDSURFACEDESC2 surface_desc2;
3106
3107     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3108             iface, surface_desc, surface, outer_unknown);
3109
3110     wined3d_mutex_lock();
3111
3112     if (!(ddraw->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3113     {
3114         WARN("Cooperative level not set.\n");
3115         wined3d_mutex_unlock();
3116         return DDERR_NOCOOPERATIVELEVELSET;
3117     }
3118
3119     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3120     {
3121         WARN("Application supplied invalid surface descriptor\n");
3122         wined3d_mutex_unlock();
3123         return DDERR_INVALIDPARAMS;
3124     }
3125
3126     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3127     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3128     {
3129         if (TRACE_ON(ddraw))
3130         {
3131             TRACE(" (%p) Requesting surface desc :\n", iface);
3132             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3133         }
3134
3135         WARN("Application tried to create an explicit front or back buffer\n");
3136         wined3d_mutex_unlock();
3137         return DDERR_INVALIDCAPS;
3138     }
3139
3140     hr = CreateSurface(ddraw, &surface_desc2, &impl, outer_unknown, 2);
3141     wined3d_mutex_unlock();
3142     if (FAILED(hr))
3143     {
3144         *surface = NULL;
3145         return hr;
3146     }
3147
3148     *surface = &impl->IDirectDrawSurface_iface;
3149     impl->ifaceToRelease = NULL;
3150
3151     return hr;
3152 }
3153
3154 static HRESULT WINAPI ddraw1_CreateSurface(IDirectDraw *iface,
3155         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3156 {
3157     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
3158     struct ddraw_surface *impl;
3159     HRESULT hr;
3160     DDSURFACEDESC2 surface_desc2;
3161
3162     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3163             iface, surface_desc, surface, outer_unknown);
3164
3165     wined3d_mutex_lock();
3166
3167     if (!(ddraw->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3168     {
3169         WARN("Cooperative level not set.\n");
3170         wined3d_mutex_unlock();
3171         return DDERR_NOCOOPERATIVELEVELSET;
3172     }
3173
3174     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3175     {
3176         WARN("Application supplied invalid surface descriptor\n");
3177         wined3d_mutex_unlock();
3178         return DDERR_INVALIDPARAMS;
3179     }
3180
3181     /* Remove front buffer flag, this causes failure in v7, and its added to normal
3182      * primaries anyway. */
3183     surface_desc->ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER;
3184     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3185     hr = CreateSurface(ddraw, &surface_desc2, &impl, outer_unknown, 1);
3186     wined3d_mutex_unlock();
3187     if (FAILED(hr))
3188     {
3189         *surface = NULL;
3190         return hr;
3191     }
3192
3193     *surface = &impl->IDirectDrawSurface_iface;
3194     impl->ifaceToRelease = NULL;
3195
3196     return hr;
3197 }
3198
3199 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
3200 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
3201
3202 static BOOL
3203 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
3204                                     const DDPIXELFORMAT *provided)
3205 {
3206     /* Some flags must be present in both or neither for a match. */
3207     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
3208         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
3209         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
3210
3211     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3212         return FALSE;
3213
3214     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
3215         return FALSE;
3216
3217     if (requested->dwFlags & DDPF_FOURCC)
3218         if (requested->dwFourCC != provided->dwFourCC)
3219             return FALSE;
3220
3221     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
3222                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3223         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
3224             return FALSE;
3225
3226     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3227                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3228         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
3229             return FALSE;
3230
3231     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
3232         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
3233             return FALSE;
3234
3235     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
3236     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3237                               |DDPF_BUMPDUDV))
3238         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
3239             return FALSE;
3240
3241     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
3242         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
3243             return FALSE;
3244
3245     return TRUE;
3246 }
3247
3248 static BOOL ddraw_match_surface_desc(const DDSURFACEDESC2 *requested, const DDSURFACEDESC2 *provided)
3249 {
3250     struct compare_info
3251     {
3252         DWORD flag;
3253         ptrdiff_t offset;
3254         size_t size;
3255     };
3256
3257 #define CMP(FLAG, FIELD)                                \
3258         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
3259           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
3260
3261     static const struct compare_info compare[] =
3262     {
3263         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
3264         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
3265         CMP(CAPS, ddsCaps),
3266         CMP(CKDESTBLT, ddckCKDestBlt),
3267         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
3268         CMP(CKSRCBLT, ddckCKSrcBlt),
3269         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
3270         CMP(HEIGHT, dwHeight),
3271         CMP(LINEARSIZE, u1 /* dwLinearSize */),
3272         CMP(LPSURFACE, lpSurface),
3273         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
3274         CMP(PITCH, u1 /* lPitch */),
3275         /* PIXELFORMAT: manual */
3276         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
3277         CMP(TEXTURESTAGE, dwTextureStage),
3278         CMP(WIDTH, dwWidth),
3279         /* ZBUFFERBITDEPTH: "obsolete" */
3280     };
3281
3282 #undef CMP
3283
3284     unsigned int i;
3285
3286     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3287         return FALSE;
3288
3289     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
3290     {
3291         if (requested->dwFlags & compare[i].flag
3292             && memcmp((const char *)provided + compare[i].offset,
3293                       (const char *)requested + compare[i].offset,
3294                       compare[i].size) != 0)
3295             return FALSE;
3296     }
3297
3298     if (requested->dwFlags & DDSD_PIXELFORMAT)
3299     {
3300         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
3301                                                 &provided->u4.ddpfPixelFormat))
3302             return FALSE;
3303     }
3304
3305     return TRUE;
3306 }
3307
3308 #undef DDENUMSURFACES_SEARCHTYPE
3309 #undef DDENUMSURFACES_MATCHTYPE
3310
3311 struct surfacescallback2_context
3312 {
3313     LPDDENUMSURFACESCALLBACK2 func;
3314     void *context;
3315 };
3316
3317 struct surfacescallback_context
3318 {
3319     LPDDENUMSURFACESCALLBACK func;
3320     void *context;
3321 };
3322
3323 static HRESULT CALLBACK EnumSurfacesCallback2Thunk(IDirectDrawSurface7 *surface,
3324         DDSURFACEDESC2 *surface_desc, void *context)
3325 {
3326     struct ddraw_surface *surface_impl = impl_from_IDirectDrawSurface7(surface);
3327     struct surfacescallback2_context *cbcontext = context;
3328
3329     IDirectDrawSurface4_AddRef(&surface_impl->IDirectDrawSurface4_iface);
3330     IDirectDrawSurface7_Release(surface);
3331
3332     return cbcontext->func(&surface_impl->IDirectDrawSurface4_iface,
3333             surface_desc, cbcontext->context);
3334 }
3335
3336 static HRESULT CALLBACK EnumSurfacesCallbackThunk(IDirectDrawSurface7 *surface,
3337         DDSURFACEDESC2 *surface_desc, void *context)
3338 {
3339     struct ddraw_surface *surface_impl = impl_from_IDirectDrawSurface7(surface);
3340     struct surfacescallback_context *cbcontext = context;
3341
3342     IDirectDrawSurface_AddRef(&surface_impl->IDirectDrawSurface_iface);
3343     IDirectDrawSurface7_Release(surface);
3344
3345     return cbcontext->func(&surface_impl->IDirectDrawSurface_iface,
3346             (DDSURFACEDESC *)surface_desc, cbcontext->context);
3347 }
3348
3349 /*****************************************************************************
3350  * IDirectDraw7::EnumSurfaces
3351  *
3352  * Loops through all surfaces attached to this device and calls the
3353  * application callback. This can't be relayed to WineD3DDevice,
3354  * because some WineD3DSurfaces' parents are IParent objects
3355  *
3356  * Params:
3357  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
3358  *  DDSD: Description to filter for
3359  *  Context: Application-provided pointer, it's passed unmodified to the
3360  *           Callback function
3361  *  Callback: Address to call for each surface
3362  *
3363  * Returns:
3364  *  DDERR_INVALIDPARAMS if the callback is NULL
3365  *  DD_OK on success
3366  *
3367  *****************************************************************************/
3368 static HRESULT WINAPI ddraw7_EnumSurfaces(IDirectDraw7 *iface, DWORD Flags,
3369         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMSURFACESCALLBACK7 Callback)
3370 {
3371     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
3372     struct ddraw_surface *surf;
3373     BOOL all, nomatch;
3374     DDSURFACEDESC2 desc;
3375     struct list *entry, *entry2;
3376
3377     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3378             iface, Flags, DDSD, Context, Callback);
3379
3380     all = Flags & DDENUMSURFACES_ALL;
3381     nomatch = Flags & DDENUMSURFACES_NOMATCH;
3382
3383     if (!Callback)
3384         return DDERR_INVALIDPARAMS;
3385
3386     wined3d_mutex_lock();
3387
3388     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
3389     LIST_FOR_EACH_SAFE(entry, entry2, &ddraw->surface_list)
3390     {
3391         surf = LIST_ENTRY(entry, struct ddraw_surface, surface_list_entry);
3392
3393         if (!surf->iface_count)
3394         {
3395             WARN("Not enumerating surface %p because it doesn't have any references.\n", surf);
3396             continue;
3397         }
3398
3399         if (all || (nomatch != ddraw_match_surface_desc(DDSD, &surf->surface_desc)))
3400         {
3401             TRACE("Enumerating surface %p.\n", surf);
3402             desc = surf->surface_desc;
3403             IDirectDrawSurface7_AddRef(&surf->IDirectDrawSurface7_iface);
3404             if (Callback(&surf->IDirectDrawSurface7_iface, &desc, Context) != DDENUMRET_OK)
3405             {
3406                 wined3d_mutex_unlock();
3407                 return DD_OK;
3408             }
3409         }
3410     }
3411
3412     wined3d_mutex_unlock();
3413
3414     return DD_OK;
3415 }
3416
3417 static HRESULT WINAPI ddraw4_EnumSurfaces(IDirectDraw4 *iface, DWORD flags,
3418         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMSURFACESCALLBACK2 callback)
3419 {
3420     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
3421     struct surfacescallback2_context cbcontext;
3422
3423     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3424             iface, flags, surface_desc, context, callback);
3425
3426     cbcontext.func = callback;
3427     cbcontext.context = context;
3428
3429     return ddraw7_EnumSurfaces(&ddraw->IDirectDraw7_iface, flags, surface_desc,
3430             &cbcontext, EnumSurfacesCallback2Thunk);
3431 }
3432
3433 static HRESULT WINAPI ddraw2_EnumSurfaces(IDirectDraw2 *iface, DWORD flags,
3434         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3435 {
3436     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
3437     struct surfacescallback_context cbcontext;
3438     DDSURFACEDESC2 surface_desc2;
3439
3440     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3441             iface, flags, surface_desc, context, callback);
3442
3443     cbcontext.func = callback;
3444     cbcontext.context = context;
3445
3446     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
3447     return ddraw7_EnumSurfaces(&ddraw->IDirectDraw7_iface, flags,
3448             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumSurfacesCallbackThunk);
3449 }
3450
3451 static HRESULT WINAPI ddraw1_EnumSurfaces(IDirectDraw *iface, DWORD flags,
3452         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3453 {
3454     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
3455     struct surfacescallback_context cbcontext;
3456     DDSURFACEDESC2 surface_desc2;
3457
3458     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3459             iface, flags, surface_desc, context, callback);
3460
3461     cbcontext.func = callback;
3462     cbcontext.context = context;
3463
3464     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
3465     return ddraw7_EnumSurfaces(&ddraw->IDirectDraw7_iface, flags,
3466             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumSurfacesCallbackThunk);
3467 }
3468
3469 /*****************************************************************************
3470  * DirectDrawCreateClipper (DDRAW.@)
3471  *
3472  * Creates a new IDirectDrawClipper object.
3473  *
3474  * Params:
3475  *  Clipper: Address to write the interface pointer to
3476  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3477  *            NULL
3478  *
3479  * Returns:
3480  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3481  *  E_OUTOFMEMORY if allocating the object failed
3482  *
3483  *****************************************************************************/
3484 HRESULT WINAPI DirectDrawCreateClipper(DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3485 {
3486     struct ddraw_clipper *object;
3487     HRESULT hr;
3488
3489     TRACE("flags %#x, clipper %p, outer_unknown %p.\n",
3490             flags, clipper, outer_unknown);
3491
3492     if (outer_unknown)
3493         return CLASS_E_NOAGGREGATION;
3494
3495     wined3d_mutex_lock();
3496
3497     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
3498     if (!object)
3499     {
3500         wined3d_mutex_unlock();
3501         return E_OUTOFMEMORY;
3502     }
3503
3504     hr = ddraw_clipper_init(object);
3505     if (FAILED(hr))
3506     {
3507         WARN("Failed to initialize clipper, hr %#x.\n", hr);
3508         HeapFree(GetProcessHeap(), 0, object);
3509         wined3d_mutex_unlock();
3510         return hr;
3511     }
3512
3513     TRACE("Created clipper %p.\n", object);
3514     *clipper = &object->IDirectDrawClipper_iface;
3515     wined3d_mutex_unlock();
3516
3517     return DD_OK;
3518 }
3519
3520 /*****************************************************************************
3521  * IDirectDraw7::CreateClipper
3522  *
3523  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3524  *
3525  *****************************************************************************/
3526 static HRESULT WINAPI ddraw7_CreateClipper(IDirectDraw7 *iface, DWORD Flags,
3527         IDirectDrawClipper **Clipper, IUnknown *UnkOuter)
3528 {
3529     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3530             iface, Flags, Clipper, UnkOuter);
3531
3532     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3533 }
3534
3535 static HRESULT WINAPI ddraw4_CreateClipper(IDirectDraw4 *iface, DWORD flags,
3536         IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3537 {
3538     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
3539
3540     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3541             iface, flags, clipper, outer_unknown);
3542
3543     return ddraw7_CreateClipper(&ddraw->IDirectDraw7_iface, flags, clipper, outer_unknown);
3544 }
3545
3546 static HRESULT WINAPI ddraw2_CreateClipper(IDirectDraw2 *iface,
3547         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3548 {
3549     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
3550
3551     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3552             iface, flags, clipper, outer_unknown);
3553
3554     return ddraw7_CreateClipper(&ddraw->IDirectDraw7_iface, flags, clipper, outer_unknown);
3555 }
3556
3557 static HRESULT WINAPI ddraw1_CreateClipper(IDirectDraw *iface,
3558         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3559 {
3560     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
3561
3562     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3563             iface, flags, clipper, outer_unknown);
3564
3565     return ddraw7_CreateClipper(&ddraw->IDirectDraw7_iface, flags, clipper, outer_unknown);
3566 }
3567
3568 /*****************************************************************************
3569  * IDirectDraw7::CreatePalette
3570  *
3571  * Creates a new IDirectDrawPalette object
3572  *
3573  * Params:
3574  *  Flags: The flags for the new clipper
3575  *  ColorTable: Color table to assign to the new clipper
3576  *  Palette: Address to write the interface pointer to
3577  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3578  *            NULL
3579  *
3580  * Returns:
3581  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3582  *  E_OUTOFMEMORY if allocating the object failed
3583  *
3584  *****************************************************************************/
3585 static HRESULT WINAPI ddraw7_CreatePalette(IDirectDraw7 *iface, DWORD Flags,
3586         PALETTEENTRY *ColorTable, IDirectDrawPalette **Palette, IUnknown *pUnkOuter)
3587 {
3588     struct ddraw *ddraw = impl_from_IDirectDraw7(iface);
3589     struct ddraw_palette *object;
3590     HRESULT hr;
3591
3592     TRACE("iface %p, flags %#x, color_table %p, palette %p, outer_unknown %p.\n",
3593             iface, Flags, ColorTable, Palette, pUnkOuter);
3594
3595     if (pUnkOuter)
3596         return CLASS_E_NOAGGREGATION;
3597
3598     wined3d_mutex_lock();
3599
3600     /* The refcount test shows that a cooplevel is required for this */
3601     if (!ddraw->cooperative_level)
3602     {
3603         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
3604         wined3d_mutex_unlock();
3605         return DDERR_NOCOOPERATIVELEVELSET;
3606     }
3607
3608     object = HeapAlloc(GetProcessHeap(), 0, sizeof(*object));
3609     if (!object)
3610     {
3611         ERR("Out of memory when allocating memory for a palette implementation\n");
3612         wined3d_mutex_unlock();
3613         return E_OUTOFMEMORY;
3614     }
3615
3616     hr = ddraw_palette_init(object, ddraw, Flags, ColorTable);
3617     if (FAILED(hr))
3618     {
3619         WARN("Failed to initialize palette, hr %#x.\n", hr);
3620         HeapFree(GetProcessHeap(), 0, object);
3621         wined3d_mutex_unlock();
3622         return hr;
3623     }
3624
3625     TRACE("Created palette %p.\n", object);
3626     *Palette = &object->IDirectDrawPalette_iface;
3627     wined3d_mutex_unlock();
3628
3629     return DD_OK;
3630 }
3631
3632 static HRESULT WINAPI ddraw4_CreatePalette(IDirectDraw4 *iface, DWORD flags, PALETTEENTRY *entries,
3633         IDirectDrawPalette **palette, IUnknown *outer_unknown)
3634 {
3635     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
3636     HRESULT hr;
3637
3638     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3639             iface, flags, entries, palette, outer_unknown);
3640
3641     hr = ddraw7_CreatePalette(&ddraw->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3642     if (SUCCEEDED(hr) && *palette)
3643     {
3644         struct ddraw_palette *impl = impl_from_IDirectDrawPalette(*palette);
3645         IDirectDraw7_Release(&ddraw->IDirectDraw7_iface);
3646         IDirectDraw4_AddRef(iface);
3647         impl->ifaceToRelease = (IUnknown *)iface;
3648     }
3649     return hr;
3650 }
3651
3652 static HRESULT WINAPI ddraw2_CreatePalette(IDirectDraw2 *iface, DWORD flags,
3653         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3654 {
3655     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
3656     HRESULT hr;
3657
3658     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3659             iface, flags, entries, palette, outer_unknown);
3660
3661     hr = ddraw7_CreatePalette(&ddraw->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3662     if (SUCCEEDED(hr) && *palette)
3663     {
3664         struct ddraw_palette *impl = impl_from_IDirectDrawPalette(*palette);
3665         IDirectDraw7_Release(&ddraw->IDirectDraw7_iface);
3666         impl->ifaceToRelease = NULL;
3667     }
3668
3669     return hr;
3670 }
3671
3672 static HRESULT WINAPI ddraw1_CreatePalette(IDirectDraw *iface, DWORD flags,
3673         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3674 {
3675     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
3676     HRESULT hr;
3677
3678     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3679             iface, flags, entries, palette, outer_unknown);
3680
3681     hr = ddraw7_CreatePalette(&ddraw->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3682     if (SUCCEEDED(hr) && *palette)
3683     {
3684         struct ddraw_palette *impl = impl_from_IDirectDrawPalette(*palette);
3685         IDirectDraw7_Release(&ddraw->IDirectDraw7_iface);
3686         impl->ifaceToRelease = NULL;
3687     }
3688
3689     return hr;
3690 }
3691
3692 /*****************************************************************************
3693  * IDirectDraw7::DuplicateSurface
3694  *
3695  * Duplicates a surface. The surface memory points to the same memory as
3696  * the original surface, and it's released when the last surface referencing
3697  * it is released. I guess that's beyond Wine's surface management right now
3698  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
3699  * test application to implement this)
3700  *
3701  * Params:
3702  *  Src: Address of the source surface
3703  *  Dest: Address to write the new surface pointer to
3704  *
3705  * Returns:
3706  *  See IDirectDraw7::CreateSurface
3707  *
3708  *****************************************************************************/
3709 static HRESULT WINAPI ddraw7_DuplicateSurface(IDirectDraw7 *iface,
3710         IDirectDrawSurface7 *Src, IDirectDrawSurface7 **Dest)
3711 {
3712     struct ddraw_surface *src_surface = unsafe_impl_from_IDirectDrawSurface7(Src);
3713
3714     FIXME("iface %p, src %p, dst %p partial stub!\n", iface, Src, Dest);
3715
3716     /* For now, simply create a new, independent surface */
3717     return IDirectDraw7_CreateSurface(iface, &src_surface->surface_desc, Dest, NULL);
3718 }
3719
3720 static HRESULT WINAPI ddraw4_DuplicateSurface(IDirectDraw4 *iface, IDirectDrawSurface4 *src,
3721         IDirectDrawSurface4 **dst)
3722 {
3723     struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface4(src);
3724     struct ddraw *ddraw = impl_from_IDirectDraw4(iface);
3725     struct ddraw_surface *dst_impl;
3726     IDirectDrawSurface7 *dst7;
3727     HRESULT hr;
3728
3729     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3730
3731     hr = ddraw7_DuplicateSurface(&ddraw->IDirectDraw7_iface,
3732             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
3733     if (FAILED(hr))
3734     {
3735         *dst = NULL;
3736         return hr;
3737     }
3738     dst_impl = impl_from_IDirectDrawSurface7(dst7);
3739     *dst = &dst_impl->IDirectDrawSurface4_iface;
3740     IDirectDrawSurface4_AddRef(*dst);
3741     IDirectDrawSurface7_Release(dst7);
3742
3743     return hr;
3744 }
3745
3746 static HRESULT WINAPI ddraw2_DuplicateSurface(IDirectDraw2 *iface,
3747         IDirectDrawSurface *src, IDirectDrawSurface **dst)
3748 {
3749     struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface(src);
3750     struct ddraw *ddraw = impl_from_IDirectDraw2(iface);
3751     struct ddraw_surface *dst_impl;
3752     IDirectDrawSurface7 *dst7;
3753     HRESULT hr;
3754
3755     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3756
3757     hr = ddraw7_DuplicateSurface(&ddraw->IDirectDraw7_iface,
3758             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
3759     if (FAILED(hr))
3760         return hr;
3761     dst_impl = impl_from_IDirectDrawSurface7(dst7);
3762     *dst = &dst_impl->IDirectDrawSurface_iface;
3763     IDirectDrawSurface_AddRef(*dst);
3764     IDirectDrawSurface7_Release(dst7);
3765
3766     return hr;
3767 }
3768
3769 static HRESULT WINAPI ddraw1_DuplicateSurface(IDirectDraw *iface, IDirectDrawSurface *src,
3770         IDirectDrawSurface **dst)
3771 {
3772     struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface(src);
3773     struct ddraw *ddraw = impl_from_IDirectDraw(iface);
3774     struct ddraw_surface *dst_impl;
3775     IDirectDrawSurface7 *dst7;
3776     HRESULT hr;
3777
3778     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3779
3780     hr = ddraw7_DuplicateSurface(&ddraw->IDirectDraw7_iface,
3781             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
3782     if (FAILED(hr))
3783         return hr;
3784     dst_impl = impl_from_IDirectDrawSurface7(dst7);
3785     *dst = &dst_impl->IDirectDrawSurface_iface;
3786     IDirectDrawSurface_AddRef(*dst);
3787     IDirectDrawSurface7_Release(dst7);
3788
3789     return hr;
3790 }
3791
3792 /*****************************************************************************
3793  * IDirect3D7::EnumDevices
3794  *
3795  * The EnumDevices method for IDirect3D7. It enumerates all supported
3796  * D3D7 devices. Currently the T&L, HAL and RGB devices are enumerated.
3797  *
3798  * Params:
3799  *  callback: Function to call for each enumerated device
3800  *  context: Pointer to pass back to the app
3801  *
3802  * Returns:
3803  *  D3D_OK, or the return value of the GetCaps call
3804  *
3805  *****************************************************************************/
3806 static HRESULT WINAPI d3d7_EnumDevices(IDirect3D7 *iface, LPD3DENUMDEVICESCALLBACK7 callback, void *context)
3807 {
3808     struct ddraw *ddraw = impl_from_IDirect3D7(iface);
3809     D3DDEVICEDESC7 device_desc7;
3810     D3DDEVICEDESC device_desc1;
3811     HRESULT hr;
3812     size_t i;
3813
3814     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
3815
3816     if (!callback)
3817         return DDERR_INVALIDPARAMS;
3818
3819     wined3d_mutex_lock();
3820
3821     hr = IDirect3DImpl_GetCaps(ddraw->wined3d, &device_desc1, &device_desc7);
3822     if (hr != D3D_OK)
3823     {
3824         wined3d_mutex_unlock();
3825         return hr;
3826     }
3827
3828     for (i = 0; i < sizeof(device_list7)/sizeof(device_list7[0]); i++)
3829     {
3830         HRESULT ret;
3831
3832         device_desc7.deviceGUID = *device_list7[i].device_guid;
3833         ret = callback(device_list7[i].interface_name, device_list7[i].device_name, &device_desc7, context);
3834         if (ret != DDENUMRET_OK)
3835         {
3836             TRACE("Application cancelled the enumeration.\n");
3837             wined3d_mutex_unlock();
3838             return D3D_OK;
3839         }
3840     }
3841
3842     TRACE("End of enumeration.\n");
3843
3844     wined3d_mutex_unlock();
3845
3846     return D3D_OK;
3847 }
3848
3849 /*****************************************************************************
3850  * IDirect3D3::EnumDevices
3851  *
3852  * Enumerates all supported Direct3DDevice interfaces. This is the
3853  * implementation for Direct3D 1 to Direc3D 3, Version 7 has its own.
3854  *
3855  * Version 1, 2 and 3
3856  *
3857  * Params:
3858  *  callback: Application-provided routine to call for each enumerated device
3859  *  Context: Pointer to pass to the callback
3860  *
3861  * Returns:
3862  *  D3D_OK on success,
3863  *  The result of IDirect3DImpl_GetCaps if it failed
3864  *
3865  *****************************************************************************/
3866 static HRESULT WINAPI d3d3_EnumDevices(IDirect3D3 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
3867 {
3868     static CHAR wined3d_description[] = "Wine D3DDevice using WineD3D and OpenGL";
3869
3870     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
3871     D3DDEVICEDESC device_desc1, hal_desc, hel_desc;
3872     D3DDEVICEDESC7 device_desc7;
3873     HRESULT hr;
3874
3875     /* Some games (Motoracer 2 demo) have the bad idea to modify the device
3876      * name string. Let's put the string in a sufficiently sized array in
3877      * writable memory. */
3878     char device_name[50];
3879     strcpy(device_name,"Direct3D HEL");
3880
3881     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
3882
3883     if (!callback)
3884         return DDERR_INVALIDPARAMS;
3885
3886     wined3d_mutex_lock();
3887
3888     hr = IDirect3DImpl_GetCaps(ddraw->wined3d, &device_desc1, &device_desc7);
3889     if (hr != D3D_OK)
3890     {
3891         wined3d_mutex_unlock();
3892         return hr;
3893     }
3894
3895     /* Do I have to enumerate the reference id? Note from old d3d7:
3896      * "It seems that enumerating the reference IID on Direct3D 1 games
3897      * (AvP / Motoracer2) breaks them". So do not enumerate this iid in V1
3898      *
3899      * There's a registry key HKLM\Software\Microsoft\Direct3D\Drivers,
3900      * EnumReference which enables / disables enumerating the reference
3901      * rasterizer. It's a DWORD, 0 means disabled, 2 means enabled. The
3902      * enablerefrast.reg and disablerefrast.reg files in the DirectX 7.0 sdk
3903      * demo directory suggest this.
3904      *
3905      * Some games(GTA 2) seem to use the second enumerated device, so I have
3906      * to enumerate at least 2 devices. So enumerate the reference device to
3907      * have 2 devices.
3908      *
3909      * Other games (Rollcage) tell emulation and hal device apart by certain
3910      * flags. Rollcage expects D3DPTEXTURECAPS_POW2 to be set (yeah, it is a
3911      * limitation flag), and it refuses all devices that have the perspective
3912      * flag set. This way it refuses the emulation device, and HAL devices
3913      * never have POW2 unset in d3d7 on windows. */
3914     if (ddraw->d3dversion != 1)
3915     {
3916         static CHAR reference_description[] = "RGB Direct3D emulation";
3917
3918         TRACE("Enumerating WineD3D D3DDevice interface.\n");
3919         hal_desc = device_desc1;
3920         hel_desc = device_desc1;
3921         /* The rgb device has the pow2 flag set in the hel caps, but not in the hal caps. */
3922         hal_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3923                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3924         hal_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3925                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3926         /* RGB, RAMP and MMX devices have a HAL dcmColorModel of 0 */
3927         hal_desc.dcmColorModel = 0;
3928
3929         hr = callback((GUID *)&IID_IDirect3DRGBDevice, reference_description,
3930                 device_name, &hal_desc, &hel_desc, context);
3931         if (hr != D3DENUMRET_OK)
3932         {
3933             TRACE("Application cancelled the enumeration.\n");
3934             wined3d_mutex_unlock();
3935             return D3D_OK;
3936         }
3937     }
3938
3939     strcpy(device_name,"Direct3D HAL");
3940
3941     TRACE("Enumerating HAL Direct3D device.\n");
3942     hal_desc = device_desc1;
3943     hel_desc = device_desc1;
3944
3945     /* The hal device does not have the pow2 flag set in hel, but in hal. */
3946     hel_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3947             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3948     hel_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3949             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3950     /* HAL devices have a HEL dcmColorModel of 0 */
3951     hel_desc.dcmColorModel = 0;
3952
3953     hr = callback((GUID *)&IID_IDirect3DHALDevice, wined3d_description,
3954             device_name, &hal_desc, &hel_desc, context);
3955     if (hr != D3DENUMRET_OK)
3956     {
3957         TRACE("Application cancelled the enumeration.\n");
3958         wined3d_mutex_unlock();
3959         return D3D_OK;
3960     }
3961
3962     TRACE("End of enumeration.\n");
3963
3964     wined3d_mutex_unlock();
3965
3966     return D3D_OK;
3967 }
3968
3969 static HRESULT WINAPI d3d2_EnumDevices(IDirect3D2 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
3970 {
3971     struct ddraw *ddraw = impl_from_IDirect3D2(iface);
3972
3973     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
3974
3975     return d3d3_EnumDevices(&ddraw->IDirect3D3_iface, callback, context);
3976 }
3977
3978 static HRESULT WINAPI d3d1_EnumDevices(IDirect3D *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
3979 {
3980     struct ddraw *ddraw = impl_from_IDirect3D(iface);
3981
3982     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
3983
3984     return d3d3_EnumDevices(&ddraw->IDirect3D3_iface, callback, context);
3985 }
3986
3987 /*****************************************************************************
3988  * IDirect3D3::CreateLight
3989  *
3990  * Creates an IDirect3DLight interface. This interface is used in
3991  * Direct3D3 or earlier for lighting. In Direct3D7 it has been replaced
3992  * by the DIRECT3DLIGHT7 structure. Wine's Direct3DLight implementation
3993  * uses the IDirect3DDevice7 interface with D3D7 lights.
3994  *
3995  * Version 1, 2 and 3
3996  *
3997  * Params:
3998  *  light: Address to store the new interface pointer
3999  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4000  *                 Must be NULL
4001  *
4002  * Returns:
4003  *  D3D_OK on success
4004  *  DDERR_OUTOFMEMORY if memory allocation failed
4005  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4006  *
4007  *****************************************************************************/
4008 static HRESULT WINAPI d3d3_CreateLight(IDirect3D3 *iface, IDirect3DLight **light,
4009         IUnknown *outer_unknown)
4010 {
4011     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4012     struct d3d_light *object;
4013
4014     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4015
4016     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4017
4018     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4019     if (!object)
4020     {
4021         ERR("Failed to allocate light memory.\n");
4022         return DDERR_OUTOFMEMORY;
4023     }
4024
4025     d3d_light_init(object, ddraw);
4026
4027     TRACE("Created light %p.\n", object);
4028     *light = &object->IDirect3DLight_iface;
4029
4030     return D3D_OK;
4031 }
4032
4033 static HRESULT WINAPI d3d2_CreateLight(IDirect3D2 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4034 {
4035     struct ddraw *ddraw = impl_from_IDirect3D2(iface);
4036
4037     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4038
4039     return d3d3_CreateLight(&ddraw->IDirect3D3_iface, light, outer_unknown);
4040 }
4041
4042 static HRESULT WINAPI d3d1_CreateLight(IDirect3D *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4043 {
4044     struct ddraw *ddraw = impl_from_IDirect3D(iface);
4045
4046     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4047
4048     return d3d3_CreateLight(&ddraw->IDirect3D3_iface, light, outer_unknown);
4049 }
4050
4051 /*****************************************************************************
4052  * IDirect3D3::CreateMaterial
4053  *
4054  * Creates an IDirect3DMaterial interface. This interface is used by Direct3D3
4055  * and older versions. The IDirect3DMaterial implementation wraps its
4056  * functionality to IDirect3DDevice7::SetMaterial and friends.
4057  *
4058  * Version 1, 2 and 3
4059  *
4060  * Params:
4061  *  material: Address to store the new interface's pointer to
4062  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4063  *                 Must be NULL
4064  *
4065  * Returns:
4066  *  D3D_OK on success
4067  *  DDERR_OUTOFMEMORY if memory allocation failed
4068  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4069  *
4070  *****************************************************************************/
4071 static HRESULT WINAPI d3d3_CreateMaterial(IDirect3D3 *iface, IDirect3DMaterial3 **material,
4072         IUnknown *outer_unknown)
4073 {
4074     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4075     struct d3d_material *object;
4076
4077     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4078
4079     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4080
4081     object = d3d_material_create(ddraw);
4082     if (!object)
4083     {
4084         ERR("Failed to allocate material memory.\n");
4085         return DDERR_OUTOFMEMORY;
4086     }
4087
4088     TRACE("Created material %p.\n", object);
4089     *material = &object->IDirect3DMaterial3_iface;
4090
4091     return D3D_OK;
4092 }
4093
4094 static HRESULT WINAPI d3d2_CreateMaterial(IDirect3D2 *iface, IDirect3DMaterial2 **material,
4095         IUnknown *outer_unknown)
4096 {
4097     struct ddraw *ddraw = impl_from_IDirect3D2(iface);
4098     struct d3d_material *object;
4099
4100     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4101
4102     object = d3d_material_create(ddraw);
4103     if (!object)
4104     {
4105         ERR("Failed to allocate material memory.\n");
4106         return DDERR_OUTOFMEMORY;
4107     }
4108
4109     TRACE("Created material %p.\n", object);
4110     *material = &object->IDirect3DMaterial2_iface;
4111
4112     return D3D_OK;
4113 }
4114
4115 static HRESULT WINAPI d3d1_CreateMaterial(IDirect3D *iface, IDirect3DMaterial **material,
4116         IUnknown *outer_unknown)
4117 {
4118     struct ddraw *ddraw = impl_from_IDirect3D(iface);
4119     struct d3d_material *object;
4120
4121     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4122
4123     object = d3d_material_create(ddraw);
4124     if (!object)
4125     {
4126         ERR("Failed to allocate material memory.\n");
4127         return DDERR_OUTOFMEMORY;
4128     }
4129
4130     TRACE("Created material %p.\n", object);
4131     *material = &object->IDirect3DMaterial_iface;
4132
4133     return D3D_OK;
4134 }
4135
4136 /*****************************************************************************
4137  * IDirect3D3::CreateViewport
4138  *
4139  * Creates an IDirect3DViewport interface. This interface is used
4140  * by Direct3D and earlier versions for Viewport management. In Direct3D7
4141  * it has been replaced by a viewport structure and
4142  * IDirect3DDevice7::*Viewport. Wine's IDirect3DViewport implementation
4143  * uses the IDirect3DDevice7 methods for its functionality
4144  *
4145  * Params:
4146  *  Viewport: Address to store the new interface pointer
4147  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4148  *                 Must be NULL
4149  *
4150  * Returns:
4151  *  D3D_OK on success
4152  *  DDERR_OUTOFMEMORY if memory allocation failed
4153  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4154  *
4155  *****************************************************************************/
4156 static HRESULT WINAPI d3d3_CreateViewport(IDirect3D3 *iface, IDirect3DViewport3 **viewport,
4157         IUnknown *outer_unknown)
4158 {
4159     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4160     struct d3d_viewport *object;
4161
4162     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4163
4164     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4165
4166     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4167     if (!object)
4168     {
4169         ERR("Failed to allocate viewport memory.\n");
4170         return DDERR_OUTOFMEMORY;
4171     }
4172
4173     d3d_viewport_init(object, ddraw);
4174
4175     TRACE("Created viewport %p.\n", object);
4176     *viewport = &object->IDirect3DViewport3_iface;
4177
4178     return D3D_OK;
4179 }
4180
4181 static HRESULT WINAPI d3d2_CreateViewport(IDirect3D2 *iface, IDirect3DViewport2 **viewport, IUnknown *outer_unknown)
4182 {
4183     struct ddraw *ddraw = impl_from_IDirect3D2(iface);
4184
4185     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4186
4187     return d3d3_CreateViewport(&ddraw->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4188             outer_unknown);
4189 }
4190
4191 static HRESULT WINAPI d3d1_CreateViewport(IDirect3D *iface, IDirect3DViewport **viewport, IUnknown *outer_unknown)
4192 {
4193     struct ddraw *ddraw = impl_from_IDirect3D(iface);
4194
4195     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4196
4197     return d3d3_CreateViewport(&ddraw->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4198             outer_unknown);
4199 }
4200
4201 /*****************************************************************************
4202  * IDirect3D3::FindDevice
4203  *
4204  * This method finds a device with the requested properties and returns a
4205  * device description
4206  *
4207  * Verion 1, 2 and 3
4208  * Params:
4209  *  fds: Describes the requested device characteristics
4210  *  fdr: Returns the device description
4211  *
4212  * Returns:
4213  *  D3D_OK on success
4214  *  DDERR_INVALIDPARAMS if no device was found
4215  *
4216  *****************************************************************************/
4217 static HRESULT WINAPI d3d3_FindDevice(IDirect3D3 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4218 {
4219     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4220     D3DDEVICEDESC7 desc7;
4221     D3DDEVICEDESC desc1;
4222     HRESULT hr;
4223
4224     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4225
4226     if (!fds || !fdr) return DDERR_INVALIDPARAMS;
4227
4228     if (fds->dwSize != sizeof(D3DFINDDEVICESEARCH)
4229             || fdr->dwSize != sizeof(D3DFINDDEVICERESULT))
4230         return DDERR_INVALIDPARAMS;
4231
4232     if ((fds->dwFlags & D3DFDS_COLORMODEL)
4233             && fds->dcmColorModel != D3DCOLOR_RGB)
4234     {
4235         WARN("Trying to request a non-RGB D3D color model. Not supported.\n");
4236         return DDERR_INVALIDPARAMS; /* No real idea what to return here :-) */
4237     }
4238
4239     if (fds->dwFlags & D3DFDS_GUID)
4240     {
4241         TRACE("Trying to match guid %s.\n", debugstr_guid(&(fds->guid)));
4242         if (!IsEqualGUID(&IID_D3DDEVICE_WineD3D, &fds->guid)
4243                 && !IsEqualGUID(&IID_IDirect3DHALDevice, &fds->guid)
4244                 && !IsEqualGUID(&IID_IDirect3DRGBDevice, &fds->guid))
4245         {
4246             WARN("No match for this GUID.\n");
4247             return DDERR_NOTFOUND;
4248         }
4249     }
4250
4251     /* Get the caps */
4252     hr = IDirect3DImpl_GetCaps(ddraw->wined3d, &desc1, &desc7);
4253     if (hr != D3D_OK) return hr;
4254
4255     /* Now return our own GUID */
4256     fdr->guid = IID_D3DDEVICE_WineD3D;
4257     fdr->ddHwDesc = desc1;
4258     fdr->ddSwDesc = desc1;
4259
4260     TRACE("Returning Wine's wined3d device with (undumped) capabilities.\n");
4261
4262     return D3D_OK;
4263 }
4264
4265 static HRESULT WINAPI d3d2_FindDevice(IDirect3D2 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4266 {
4267     struct ddraw *ddraw = impl_from_IDirect3D2(iface);
4268
4269     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4270
4271     return d3d3_FindDevice(&ddraw->IDirect3D3_iface, fds, fdr);
4272 }
4273
4274 static HRESULT WINAPI d3d1_FindDevice(IDirect3D *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4275 {
4276     struct ddraw *ddraw = impl_from_IDirect3D(iface);
4277
4278     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4279
4280     return d3d3_FindDevice(&ddraw->IDirect3D3_iface, fds, fdr);
4281 }
4282
4283 /*****************************************************************************
4284  * IDirect3D7::CreateDevice
4285  *
4286  * Creates an IDirect3DDevice7 interface.
4287  *
4288  * Version 2, 3 and 7. IDirect3DDevice 1 interfaces are interfaces to
4289  * DirectDraw surfaces and are created with
4290  * IDirectDrawSurface::QueryInterface. This method uses CreateDevice to
4291  * create the device object and QueryInterfaces for IDirect3DDevice
4292  *
4293  * Params:
4294  *  refiid: IID of the device to create
4295  *  Surface: Initial rendertarget
4296  *  Device: Address to return the interface pointer
4297  *
4298  * Returns:
4299  *  D3D_OK on success
4300  *  DDERR_OUTOFMEMORY if memory allocation failed
4301  *  DDERR_INVALIDPARAMS if a device exists already
4302  *
4303  *****************************************************************************/
4304 static HRESULT WINAPI d3d7_CreateDevice(IDirect3D7 *iface, REFCLSID riid,
4305         IDirectDrawSurface7 *surface, IDirect3DDevice7 **device)
4306 {
4307     struct ddraw_surface *target = unsafe_impl_from_IDirectDrawSurface7(surface);
4308     struct ddraw *ddraw = impl_from_IDirect3D7(iface);
4309     struct d3d_device *object;
4310     HRESULT hr;
4311
4312     TRACE("iface %p, riid %s, surface %p, device %p.\n", iface, debugstr_guid(riid), surface, device);
4313
4314     wined3d_mutex_lock();
4315     hr = d3d_device_create(ddraw, target, 7, &object, NULL);
4316     if (SUCCEEDED(hr))
4317         *device = &object->IDirect3DDevice7_iface;
4318     else
4319     {
4320         WARN("Failed to create device, hr %#x.\n", hr);
4321         *device = NULL;
4322     }
4323     wined3d_mutex_unlock();
4324
4325     return hr;
4326 }
4327
4328 static HRESULT WINAPI d3d3_CreateDevice(IDirect3D3 *iface, REFCLSID riid,
4329         IDirectDrawSurface4 *surface, IDirect3DDevice3 **device, IUnknown *outer_unknown)
4330 {
4331     struct ddraw_surface *surface_impl = unsafe_impl_from_IDirectDrawSurface4(surface);
4332     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4333     struct d3d_device *device_impl;
4334     HRESULT hr;
4335
4336     TRACE("iface %p, riid %s, surface %p, device %p, outer_unknown %p.\n",
4337             iface, debugstr_guid(riid), surface, device, outer_unknown);
4338
4339     if (outer_unknown)
4340         return CLASS_E_NOAGGREGATION;
4341
4342     wined3d_mutex_lock();
4343     hr = d3d_device_create(ddraw, surface_impl, 3, &device_impl, NULL);
4344     if (SUCCEEDED(hr))
4345         *device = &device_impl->IDirect3DDevice3_iface;
4346     else
4347     {
4348         WARN("Failed to create device, hr %#x.\n", hr);
4349         *device = NULL;
4350     }
4351     wined3d_mutex_unlock();
4352
4353     return hr;
4354 }
4355
4356 static HRESULT WINAPI d3d2_CreateDevice(IDirect3D2 *iface, REFCLSID riid,
4357         IDirectDrawSurface *surface, IDirect3DDevice2 **device)
4358 {
4359     struct ddraw_surface *surface_impl = unsafe_impl_from_IDirectDrawSurface(surface);
4360     struct ddraw *ddraw = impl_from_IDirect3D2(iface);
4361     struct d3d_device *device_impl;
4362     HRESULT hr;
4363
4364     TRACE("iface %p, riid %s, surface %p, device %p.\n",
4365             iface, debugstr_guid(riid), surface, device);
4366
4367     wined3d_mutex_lock();
4368     hr = d3d_device_create(ddraw, surface_impl, 2, &device_impl, NULL);
4369     if (SUCCEEDED(hr))
4370         *device = &device_impl->IDirect3DDevice2_iface;
4371     else
4372     {
4373         WARN("Failed to create device, hr %#x.\n", hr);
4374         *device = NULL;
4375     }
4376     wined3d_mutex_unlock();
4377
4378     return hr;
4379 }
4380
4381 /*****************************************************************************
4382  * IDirect3D7::CreateVertexBuffer
4383  *
4384  * Creates a new vertex buffer object and returns a IDirect3DVertexBuffer7
4385  * interface.
4386  *
4387  * Version 3 and 7
4388  *
4389  * Params:
4390  *  desc: Requested Vertex buffer properties
4391  *  vertex_buffer: Address to return the interface pointer at
4392  *  flags: Some flags, should be 0
4393  *
4394  * Returns
4395  *  D3D_OK on success
4396  *  DDERR_OUTOFMEMORY if memory allocation failed
4397  *  The return value of IWineD3DDevice::CreateVertexBuffer if this call fails
4398  *  DDERR_INVALIDPARAMS if desc or vertex_buffer are NULL
4399  *
4400  *****************************************************************************/
4401 static HRESULT WINAPI d3d7_CreateVertexBuffer(IDirect3D7 *iface, D3DVERTEXBUFFERDESC *desc,
4402         IDirect3DVertexBuffer7 **vertex_buffer, DWORD flags)
4403 {
4404     struct ddraw *ddraw = impl_from_IDirect3D7(iface);
4405     struct d3d_vertex_buffer *object;
4406     HRESULT hr;
4407
4408     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x.\n",
4409             iface, desc, vertex_buffer, flags);
4410
4411     if (!vertex_buffer || !desc) return DDERR_INVALIDPARAMS;
4412
4413     hr = d3d_vertex_buffer_create(&object, ddraw, desc);
4414     if (hr == D3D_OK)
4415     {
4416         TRACE("Created vertex buffer %p.\n", object);
4417         *vertex_buffer = &object->IDirect3DVertexBuffer7_iface;
4418     }
4419     else
4420         WARN("Failed to create vertex buffer, hr %#x.\n", hr);
4421
4422     return hr;
4423 }
4424
4425 static HRESULT WINAPI d3d3_CreateVertexBuffer(IDirect3D3 *iface, D3DVERTEXBUFFERDESC *desc,
4426         IDirect3DVertexBuffer **vertex_buffer, DWORD flags, IUnknown *outer_unknown)
4427 {
4428     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4429     struct d3d_vertex_buffer *object;
4430     HRESULT hr;
4431
4432     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x, outer_unknown %p.\n",
4433             iface, desc, vertex_buffer, flags, outer_unknown);
4434
4435     if (outer_unknown)
4436         return CLASS_E_NOAGGREGATION;
4437     if (!vertex_buffer || !desc)
4438         return DDERR_INVALIDPARAMS;
4439
4440     hr = d3d_vertex_buffer_create(&object, ddraw, desc);
4441     if (hr == D3D_OK)
4442     {
4443         TRACE("Created vertex buffer %p.\n", object);
4444         *vertex_buffer = &object->IDirect3DVertexBuffer_iface;
4445     }
4446     else
4447         WARN("Failed to create vertex buffer, hr %#x.\n", hr);
4448
4449     return hr;
4450 }
4451
4452 /*****************************************************************************
4453  * IDirect3D7::EnumZBufferFormats
4454  *
4455  * Enumerates all supported Z buffer pixel formats
4456  *
4457  * Version 3 and 7
4458  *
4459  * Params:
4460  *  device_iid:
4461  *  callback: callback to call for each pixel format
4462  *  context: Pointer to pass back to the callback
4463  *
4464  * Returns:
4465  *  D3D_OK on success
4466  *  DDERR_INVALIDPARAMS if callback is NULL
4467  *  For details, see IWineD3DDevice::EnumZBufferFormats
4468  *
4469  *****************************************************************************/
4470 static HRESULT WINAPI d3d7_EnumZBufferFormats(IDirect3D7 *iface, REFCLSID device_iid,
4471         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4472 {
4473     struct ddraw *ddraw = impl_from_IDirect3D7(iface);
4474     struct wined3d_display_mode mode;
4475     enum wined3d_device_type type;
4476     unsigned int i;
4477     HRESULT hr;
4478
4479     /* Order matters. Specifically, BattleZone II (full version) expects the
4480      * 16-bit depth formats to be listed before the 24 and 32 ones. */
4481     static const enum wined3d_format_id formats[] =
4482     {
4483         WINED3DFMT_S1_UINT_D15_UNORM,
4484         WINED3DFMT_D16_UNORM,
4485         WINED3DFMT_X8D24_UNORM,
4486         WINED3DFMT_S4X4_UINT_D24_UNORM,
4487         WINED3DFMT_D24_UNORM_S8_UINT,
4488         WINED3DFMT_D32_UNORM,
4489     };
4490
4491     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4492             iface, debugstr_guid(device_iid), callback, context);
4493
4494     if (!callback) return DDERR_INVALIDPARAMS;
4495
4496     if (IsEqualGUID(device_iid, &IID_IDirect3DHALDevice)
4497             || IsEqualGUID(device_iid, &IID_IDirect3DTnLHalDevice)
4498             || IsEqualGUID(device_iid, &IID_D3DDEVICE_WineD3D))
4499     {
4500         TRACE("Asked for HAL device.\n");
4501         type = WINED3D_DEVICE_TYPE_HAL;
4502     }
4503     else if (IsEqualGUID(device_iid, &IID_IDirect3DRGBDevice)
4504             || IsEqualGUID(device_iid, &IID_IDirect3DMMXDevice))
4505     {
4506         TRACE("Asked for SW device.\n");
4507         type = WINED3D_DEVICE_TYPE_SW;
4508     }
4509     else if (IsEqualGUID(device_iid, &IID_IDirect3DRefDevice))
4510     {
4511         TRACE("Asked for REF device.\n");
4512         type = WINED3D_DEVICE_TYPE_REF;
4513     }
4514     else if (IsEqualGUID(device_iid, &IID_IDirect3DNullDevice))
4515     {
4516         TRACE("Asked for NULLREF device.\n");
4517         type = WINED3D_DEVICE_TYPE_NULLREF;
4518     }
4519     else
4520     {
4521         FIXME("Unexpected device GUID %s.\n", debugstr_guid(device_iid));
4522         type = WINED3D_DEVICE_TYPE_HAL;
4523     }
4524
4525     wined3d_mutex_lock();
4526     /* We need an adapter format from somewhere to please wined3d and WGL.
4527      * Use the current display mode. So far all cards offer the same depth
4528      * stencil format for all modes, but if some do not and applications do
4529      * not like that we'll have to find some workaround, like iterating over
4530      * all imaginable formats and collecting all the depth stencil formats we
4531      * can get. */
4532     if (FAILED(hr = wined3d_get_adapter_display_mode(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &mode, NULL)))
4533     {
4534         ERR("Failed to get display mode, hr %#x.\n", hr);
4535         wined3d_mutex_unlock();
4536         return hr;
4537     }
4538
4539     for (i = 0; i < (sizeof(formats) / sizeof(*formats)); ++i)
4540     {
4541         hr = wined3d_check_device_format(ddraw->wined3d, WINED3DADAPTER_DEFAULT, type, mode.format_id,
4542                 WINED3DUSAGE_DEPTHSTENCIL, WINED3D_RTYPE_SURFACE, formats[i], WINED3D_SURFACE_TYPE_OPENGL);
4543         if (SUCCEEDED(hr))
4544         {
4545             DDPIXELFORMAT pformat;
4546
4547             memset(&pformat, 0, sizeof(pformat));
4548             pformat.dwSize = sizeof(pformat);
4549             PixelFormat_WineD3DtoDD(&pformat, formats[i]);
4550
4551             TRACE("Enumerating wined3d format %#x.\n", formats[i]);
4552             hr = callback(&pformat, context);
4553             if (hr != DDENUMRET_OK)
4554             {
4555                 TRACE("Format enumeration cancelled by application.\n");
4556                 wined3d_mutex_unlock();
4557                 return D3D_OK;
4558             }
4559         }
4560     }
4561
4562     /* Historically some windows drivers used dwZBufferBitDepth=24 for WINED3DFMT_X8D24_UNORM,
4563      * while others used dwZBufferBitDepth=32. In either case the pitch matches a 32 bits per
4564      * pixel format, so we use dwZBufferBitDepth=32. Some games expect 24. Windows Vista and
4565      * newer enumerate both versions, so we do the same(bug 22434) */
4566     hr = wined3d_check_device_format(ddraw->wined3d, WINED3DADAPTER_DEFAULT, type, mode.format_id,
4567             WINED3DUSAGE_DEPTHSTENCIL, WINED3D_RTYPE_SURFACE, WINED3DFMT_X8D24_UNORM, WINED3D_SURFACE_TYPE_OPENGL);
4568     if (SUCCEEDED(hr))
4569     {
4570         DDPIXELFORMAT x8d24 =
4571         {
4572             sizeof(x8d24), DDPF_ZBUFFER, 0,
4573             {24}, {0x00000000}, {0x00ffffff}, {0x00000000}
4574         };
4575         TRACE("Enumerating WINED3DFMT_X8D24_UNORM, dwZBufferBitDepth=24 version\n");
4576         callback(&x8d24, context);
4577     }
4578
4579     TRACE("End of enumeration.\n");
4580
4581     wined3d_mutex_unlock();
4582
4583     return D3D_OK;
4584 }
4585
4586 static HRESULT WINAPI d3d3_EnumZBufferFormats(IDirect3D3 *iface, REFCLSID device_iid,
4587         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4588 {
4589     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4590
4591     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4592             iface, debugstr_guid(device_iid), callback, context);
4593
4594     return d3d7_EnumZBufferFormats(&ddraw->IDirect3D7_iface, device_iid, callback, context);
4595 }
4596
4597 /*****************************************************************************
4598  * IDirect3D7::EvictManagedTextures
4599  *
4600  * Removes all managed textures (=surfaces with DDSCAPS2_TEXTUREMANAGE or
4601  * DDSCAPS2_D3DTEXTUREMANAGE caps) to be removed from video memory.
4602  *
4603  * Version 3 and 7
4604  *
4605  * Returns:
4606  *  D3D_OK, because it's a stub
4607  *
4608  *****************************************************************************/
4609 static HRESULT WINAPI d3d7_EvictManagedTextures(IDirect3D7 *iface)
4610 {
4611     struct ddraw *ddraw = impl_from_IDirect3D7(iface);
4612
4613     TRACE("iface %p!\n", iface);
4614
4615     wined3d_mutex_lock();
4616     if (ddraw->d3d_initialized)
4617         wined3d_device_evict_managed_resources(ddraw->wined3d_device);
4618     wined3d_mutex_unlock();
4619
4620     return D3D_OK;
4621 }
4622
4623 static HRESULT WINAPI d3d3_EvictManagedTextures(IDirect3D3 *iface)
4624 {
4625     struct ddraw *ddraw = impl_from_IDirect3D3(iface);
4626
4627     TRACE("iface %p.\n", iface);
4628
4629     return d3d7_EvictManagedTextures(&ddraw->IDirect3D7_iface);
4630 }
4631
4632 /*****************************************************************************
4633  * IDirect3DImpl_GetCaps
4634  *
4635  * This function retrieves the device caps from wined3d
4636  * and converts it into a D3D7 and D3D - D3D3 structure
4637  * This is a helper function called from various places in ddraw
4638  *
4639  * Params:
4640  *  wined3d: The interface to get the caps from
4641  *  desc1: Old D3D <3 structure to fill (needed)
4642  *  desc7: D3D7 device desc structure to fill (needed)
4643  *
4644  * Returns
4645  *  D3D_OK on success, or the return value of IWineD3D::GetCaps
4646  *
4647  *****************************************************************************/
4648 HRESULT IDirect3DImpl_GetCaps(const struct wined3d *wined3d, D3DDEVICEDESC *desc1, D3DDEVICEDESC7 *desc7)
4649 {
4650     WINED3DCAPS wined3d_caps;
4651     HRESULT hr;
4652
4653     TRACE("wined3d %p, desc1 %p, desc7 %p.\n", wined3d, desc1, desc7);
4654
4655     memset(&wined3d_caps, 0, sizeof(wined3d_caps));
4656
4657     wined3d_mutex_lock();
4658     hr = wined3d_get_device_caps(wined3d, 0, WINED3D_DEVICE_TYPE_HAL, &wined3d_caps);
4659     wined3d_mutex_unlock();
4660     if (FAILED(hr))
4661     {
4662         WARN("Failed to get device caps, hr %#x.\n", hr);
4663         return hr;
4664     }
4665
4666     /* Copy the results into the d3d7 and d3d3 structures */
4667     desc7->dwDevCaps = wined3d_caps.DevCaps;
4668     desc7->dpcLineCaps.dwMiscCaps = wined3d_caps.PrimitiveMiscCaps;
4669     desc7->dpcLineCaps.dwRasterCaps = wined3d_caps.RasterCaps;
4670     desc7->dpcLineCaps.dwZCmpCaps = wined3d_caps.ZCmpCaps;
4671     desc7->dpcLineCaps.dwSrcBlendCaps = wined3d_caps.SrcBlendCaps;
4672     desc7->dpcLineCaps.dwDestBlendCaps = wined3d_caps.DestBlendCaps;
4673     desc7->dpcLineCaps.dwAlphaCmpCaps = wined3d_caps.AlphaCmpCaps;
4674     desc7->dpcLineCaps.dwShadeCaps = wined3d_caps.ShadeCaps;
4675     desc7->dpcLineCaps.dwTextureCaps = wined3d_caps.TextureCaps;
4676     desc7->dpcLineCaps.dwTextureFilterCaps = wined3d_caps.TextureFilterCaps;
4677     desc7->dpcLineCaps.dwTextureAddressCaps = wined3d_caps.TextureAddressCaps;
4678
4679     desc7->dwMaxTextureWidth = wined3d_caps.MaxTextureWidth;
4680     desc7->dwMaxTextureHeight = wined3d_caps.MaxTextureHeight;
4681
4682     desc7->dwMaxTextureRepeat = wined3d_caps.MaxTextureRepeat;
4683     desc7->dwMaxTextureAspectRatio = wined3d_caps.MaxTextureAspectRatio;
4684     desc7->dwMaxAnisotropy = wined3d_caps.MaxAnisotropy;
4685     desc7->dvMaxVertexW = wined3d_caps.MaxVertexW;
4686
4687     desc7->dvGuardBandLeft = wined3d_caps.GuardBandLeft;
4688     desc7->dvGuardBandTop = wined3d_caps.GuardBandTop;
4689     desc7->dvGuardBandRight = wined3d_caps.GuardBandRight;
4690     desc7->dvGuardBandBottom = wined3d_caps.GuardBandBottom;
4691
4692     desc7->dvExtentsAdjust = wined3d_caps.ExtentsAdjust;
4693     desc7->dwStencilCaps = wined3d_caps.StencilCaps;
4694
4695     desc7->dwFVFCaps = wined3d_caps.FVFCaps;
4696     desc7->dwTextureOpCaps = wined3d_caps.TextureOpCaps;
4697
4698     desc7->dwVertexProcessingCaps = wined3d_caps.VertexProcessingCaps;
4699     desc7->dwMaxActiveLights = wined3d_caps.MaxActiveLights;
4700
4701     /* Remove all non-d3d7 caps */
4702     desc7->dwDevCaps &= (
4703         D3DDEVCAPS_FLOATTLVERTEX         | D3DDEVCAPS_SORTINCREASINGZ          | D3DDEVCAPS_SORTDECREASINGZ          |
4704         D3DDEVCAPS_SORTEXACT             | D3DDEVCAPS_EXECUTESYSTEMMEMORY      | D3DDEVCAPS_EXECUTEVIDEOMEMORY       |
4705         D3DDEVCAPS_TLVERTEXSYSTEMMEMORY  | D3DDEVCAPS_TLVERTEXVIDEOMEMORY      | D3DDEVCAPS_TEXTURESYSTEMMEMORY      |
4706         D3DDEVCAPS_TEXTUREVIDEOMEMORY    | D3DDEVCAPS_DRAWPRIMTLVERTEX         | D3DDEVCAPS_CANRENDERAFTERFLIP       |
4707         D3DDEVCAPS_TEXTURENONLOCALVIDMEM | D3DDEVCAPS_DRAWPRIMITIVES2          | D3DDEVCAPS_SEPARATETEXTUREMEMORIES  |
4708         D3DDEVCAPS_DRAWPRIMITIVES2EX     | D3DDEVCAPS_HWTRANSFORMANDLIGHT      | D3DDEVCAPS_CANBLTSYSTONONLOCAL      |
4709         D3DDEVCAPS_HWRASTERIZATION);
4710
4711     desc7->dwStencilCaps &= (
4712         D3DSTENCILCAPS_KEEP              | D3DSTENCILCAPS_ZERO                 | D3DSTENCILCAPS_REPLACE              |
4713         D3DSTENCILCAPS_INCRSAT           | D3DSTENCILCAPS_DECRSAT              | D3DSTENCILCAPS_INVERT               |
4714         D3DSTENCILCAPS_INCR              | D3DSTENCILCAPS_DECR);
4715
4716     /* FVF caps ?*/
4717
4718     desc7->dwTextureOpCaps &= (
4719         D3DTEXOPCAPS_DISABLE             | D3DTEXOPCAPS_SELECTARG1             | D3DTEXOPCAPS_SELECTARG2             |
4720         D3DTEXOPCAPS_MODULATE            | D3DTEXOPCAPS_MODULATE2X             | D3DTEXOPCAPS_MODULATE4X             |
4721         D3DTEXOPCAPS_ADD                 | D3DTEXOPCAPS_ADDSIGNED              | D3DTEXOPCAPS_ADDSIGNED2X            |
4722         D3DTEXOPCAPS_SUBTRACT            | D3DTEXOPCAPS_ADDSMOOTH              | D3DTEXOPCAPS_BLENDTEXTUREALPHA      |
4723         D3DTEXOPCAPS_BLENDFACTORALPHA    | D3DTEXOPCAPS_BLENDTEXTUREALPHAPM    | D3DTEXOPCAPS_BLENDCURRENTALPHA      |
4724         D3DTEXOPCAPS_PREMODULATE         | D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA |
4725         D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | D3DTEXOPCAPS_BUMPENVMAP    |
4726         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE | D3DTEXOPCAPS_DOTPRODUCT3);
4727
4728     desc7->dwVertexProcessingCaps &= (
4729         D3DVTXPCAPS_TEXGEN               | D3DVTXPCAPS_MATERIALSOURCE7         | D3DVTXPCAPS_VERTEXFOG               |
4730         D3DVTXPCAPS_DIRECTIONALLIGHTS    | D3DVTXPCAPS_POSITIONALLIGHTS        | D3DVTXPCAPS_LOCALVIEWER);
4731
4732     desc7->dpcLineCaps.dwMiscCaps &= (
4733         D3DPMISCCAPS_MASKPLANES          | D3DPMISCCAPS_MASKZ                  | D3DPMISCCAPS_LINEPATTERNREP         |
4734         D3DPMISCCAPS_CONFORMANT          | D3DPMISCCAPS_CULLNONE               | D3DPMISCCAPS_CULLCW                 |
4735         D3DPMISCCAPS_CULLCCW);
4736
4737     desc7->dpcLineCaps.dwRasterCaps &= (
4738         D3DPRASTERCAPS_DITHER            | D3DPRASTERCAPS_ROP2                 | D3DPRASTERCAPS_XOR                  |
4739         D3DPRASTERCAPS_PAT               | D3DPRASTERCAPS_ZTEST                | D3DPRASTERCAPS_SUBPIXEL             |
4740         D3DPRASTERCAPS_SUBPIXELX         | D3DPRASTERCAPS_FOGVERTEX            | D3DPRASTERCAPS_FOGTABLE             |
4741         D3DPRASTERCAPS_STIPPLE           | D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT | D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT |
4742         D3DPRASTERCAPS_ANTIALIASEDGES    | D3DPRASTERCAPS_MIPMAPLODBIAS        | D3DPRASTERCAPS_ZBIAS                |
4743         D3DPRASTERCAPS_ZBUFFERLESSHSR    | D3DPRASTERCAPS_FOGRANGE             | D3DPRASTERCAPS_ANISOTROPY           |
4744         D3DPRASTERCAPS_WBUFFER           | D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT | D3DPRASTERCAPS_WFOG           |
4745         D3DPRASTERCAPS_ZFOG);
4746
4747     desc7->dpcLineCaps.dwZCmpCaps &= (
4748         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4749         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4750         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4751
4752     desc7->dpcLineCaps.dwSrcBlendCaps &= (
4753         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4754         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4755         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4756         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4757         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4758
4759     desc7->dpcLineCaps.dwDestBlendCaps &= (
4760         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4761         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4762         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4763         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4764         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4765
4766     desc7->dpcLineCaps.dwAlphaCmpCaps &= (
4767         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4768         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4769         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4770
4771     desc7->dpcLineCaps.dwShadeCaps &= (
4772         D3DPSHADECAPS_COLORFLATMONO      | D3DPSHADECAPS_COLORFLATRGB          | D3DPSHADECAPS_COLORGOURAUDMONO      |
4773         D3DPSHADECAPS_COLORGOURAUDRGB    | D3DPSHADECAPS_COLORPHONGMONO        | D3DPSHADECAPS_COLORPHONGRGB         |
4774         D3DPSHADECAPS_SPECULARFLATMONO   | D3DPSHADECAPS_SPECULARFLATRGB       | D3DPSHADECAPS_SPECULARGOURAUDMONO   |
4775         D3DPSHADECAPS_SPECULARGOURAUDRGB | D3DPSHADECAPS_SPECULARPHONGMONO     | D3DPSHADECAPS_SPECULARPHONGRGB      |
4776         D3DPSHADECAPS_ALPHAFLATBLEND     | D3DPSHADECAPS_ALPHAFLATSTIPPLED     | D3DPSHADECAPS_ALPHAGOURAUDBLEND     |
4777         D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED | D3DPSHADECAPS_ALPHAPHONGBLEND     | D3DPSHADECAPS_ALPHAPHONGSTIPPLED    |
4778         D3DPSHADECAPS_FOGFLAT            | D3DPSHADECAPS_FOGGOURAUD            | D3DPSHADECAPS_FOGPHONG);
4779
4780     desc7->dpcLineCaps.dwTextureCaps &= (
4781         D3DPTEXTURECAPS_PERSPECTIVE      | D3DPTEXTURECAPS_POW2                | D3DPTEXTURECAPS_ALPHA               |
4782         D3DPTEXTURECAPS_TRANSPARENCY     | D3DPTEXTURECAPS_BORDER              | D3DPTEXTURECAPS_SQUAREONLY          |
4783         D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE | D3DPTEXTURECAPS_ALPHAPALETTE| D3DPTEXTURECAPS_NONPOW2CONDITIONAL  |
4784         D3DPTEXTURECAPS_PROJECTED        | D3DPTEXTURECAPS_CUBEMAP             | D3DPTEXTURECAPS_COLORKEYBLEND);
4785
4786     desc7->dpcLineCaps.dwTextureFilterCaps &= (
4787         D3DPTFILTERCAPS_NEAREST          | D3DPTFILTERCAPS_LINEAR              | D3DPTFILTERCAPS_MIPNEAREST          |
4788         D3DPTFILTERCAPS_MIPLINEAR        | D3DPTFILTERCAPS_LINEARMIPNEAREST    | D3DPTFILTERCAPS_LINEARMIPLINEAR     |
4789         D3DPTFILTERCAPS_MINFPOINT        | D3DPTFILTERCAPS_MINFLINEAR          | D3DPTFILTERCAPS_MINFANISOTROPIC     |
4790         D3DPTFILTERCAPS_MIPFPOINT        | D3DPTFILTERCAPS_MIPFLINEAR          | D3DPTFILTERCAPS_MAGFPOINT           |
4791         D3DPTFILTERCAPS_MAGFLINEAR       | D3DPTFILTERCAPS_MAGFANISOTROPIC     | D3DPTFILTERCAPS_MAGFAFLATCUBIC      |
4792         D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
4793
4794     desc7->dpcLineCaps.dwTextureBlendCaps &= (
4795         D3DPTBLENDCAPS_DECAL             | D3DPTBLENDCAPS_MODULATE             | D3DPTBLENDCAPS_DECALALPHA           |
4796         D3DPTBLENDCAPS_MODULATEALPHA     | D3DPTBLENDCAPS_DECALMASK            | D3DPTBLENDCAPS_MODULATEMASK         |
4797         D3DPTBLENDCAPS_COPY              | D3DPTBLENDCAPS_ADD);
4798
4799     desc7->dpcLineCaps.dwTextureAddressCaps &= (
4800         D3DPTADDRESSCAPS_WRAP            | D3DPTADDRESSCAPS_MIRROR             | D3DPTADDRESSCAPS_CLAMP              |
4801         D3DPTADDRESSCAPS_BORDER          | D3DPTADDRESSCAPS_INDEPENDENTUV);
4802
4803     if (!(desc7->dpcLineCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2))
4804     {
4805         /* DirectX7 always has the np2 flag set, no matter what the card
4806          * supports. Some old games (Rollcage) check the caps incorrectly.
4807          * If wined3d supports nonpow2 textures it also has np2 conditional
4808          * support. */
4809         desc7->dpcLineCaps.dwTextureCaps |= D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL;
4810     }
4811
4812     /* Fill the missing members, and do some fixup */
4813     desc7->dpcLineCaps.dwSize = sizeof(desc7->dpcLineCaps);
4814     desc7->dpcLineCaps.dwTextureBlendCaps = D3DPTBLENDCAPS_ADD | D3DPTBLENDCAPS_MODULATEMASK |
4815                                             D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_DECAL |
4816                                             D3DPTBLENDCAPS_DECALALPHA | D3DPTBLENDCAPS_DECALMASK |
4817                                             D3DPTBLENDCAPS_MODULATE | D3DPTBLENDCAPS_MODULATEALPHA;
4818     desc7->dpcLineCaps.dwStippleWidth = 32;
4819     desc7->dpcLineCaps.dwStippleHeight = 32;
4820     /* Use the same for the TriCaps */
4821     desc7->dpcTriCaps = desc7->dpcLineCaps;
4822
4823     desc7->dwDeviceRenderBitDepth = DDBD_16 | DDBD_24 | DDBD_32;
4824     desc7->dwDeviceZBufferBitDepth = DDBD_16 | DDBD_24;
4825     desc7->dwMinTextureWidth = 1;
4826     desc7->dwMinTextureHeight = 1;
4827
4828     /* Convert DWORDs safely to WORDs */
4829     if (wined3d_caps.MaxTextureBlendStages > 0xffff) desc7->wMaxTextureBlendStages = 0xffff;
4830     else desc7->wMaxTextureBlendStages = (WORD)wined3d_caps.MaxTextureBlendStages;
4831     if (wined3d_caps.MaxSimultaneousTextures > 0xffff) desc7->wMaxSimultaneousTextures = 0xffff;
4832     else desc7->wMaxSimultaneousTextures = (WORD)wined3d_caps.MaxSimultaneousTextures;
4833
4834     if (wined3d_caps.MaxUserClipPlanes > 0xffff) desc7->wMaxUserClipPlanes = 0xffff;
4835     else desc7->wMaxUserClipPlanes = (WORD)wined3d_caps.MaxUserClipPlanes;
4836     if (wined3d_caps.MaxVertexBlendMatrices > 0xffff) desc7->wMaxVertexBlendMatrices = 0xffff;
4837     else desc7->wMaxVertexBlendMatrices = (WORD)wined3d_caps.MaxVertexBlendMatrices;
4838
4839     desc7->deviceGUID = IID_IDirect3DTnLHalDevice;
4840
4841     desc7->dwReserved1 = 0;
4842     desc7->dwReserved2 = 0;
4843     desc7->dwReserved3 = 0;
4844     desc7->dwReserved4 = 0;
4845
4846     /* Fill the old structure */
4847     memset(desc1, 0, sizeof(*desc1));
4848     desc1->dwSize = sizeof(D3DDEVICEDESC);
4849     desc1->dwFlags = D3DDD_COLORMODEL
4850             | D3DDD_DEVCAPS
4851             | D3DDD_TRANSFORMCAPS
4852             | D3DDD_BCLIPPING
4853             | D3DDD_LIGHTINGCAPS
4854             | D3DDD_LINECAPS
4855             | D3DDD_TRICAPS
4856             | D3DDD_DEVICERENDERBITDEPTH
4857             | D3DDD_DEVICEZBUFFERBITDEPTH
4858             | D3DDD_MAXBUFFERSIZE
4859             | D3DDD_MAXVERTEXCOUNT;
4860
4861     desc1->dcmColorModel = D3DCOLOR_RGB;
4862     desc1->dwDevCaps = desc7->dwDevCaps;
4863     desc1->dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
4864     desc1->dtcTransformCaps.dwCaps = D3DTRANSFORMCAPS_CLIP;
4865     desc1->bClipping = TRUE;
4866     desc1->dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
4867     desc1->dlcLightingCaps.dwCaps = D3DLIGHTCAPS_DIRECTIONAL
4868             | D3DLIGHTCAPS_PARALLELPOINT
4869             | D3DLIGHTCAPS_POINT
4870             | D3DLIGHTCAPS_SPOT;
4871
4872     desc1->dlcLightingCaps.dwLightingModel = D3DLIGHTINGMODEL_RGB;
4873     desc1->dlcLightingCaps.dwNumLights = desc7->dwMaxActiveLights;
4874
4875     desc1->dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
4876     desc1->dpcLineCaps.dwMiscCaps = desc7->dpcLineCaps.dwMiscCaps;
4877     desc1->dpcLineCaps.dwRasterCaps = desc7->dpcLineCaps.dwRasterCaps;
4878     desc1->dpcLineCaps.dwZCmpCaps = desc7->dpcLineCaps.dwZCmpCaps;
4879     desc1->dpcLineCaps.dwSrcBlendCaps = desc7->dpcLineCaps.dwSrcBlendCaps;
4880     desc1->dpcLineCaps.dwDestBlendCaps = desc7->dpcLineCaps.dwDestBlendCaps;
4881     desc1->dpcLineCaps.dwShadeCaps = desc7->dpcLineCaps.dwShadeCaps;
4882     desc1->dpcLineCaps.dwTextureCaps = desc7->dpcLineCaps.dwTextureCaps;
4883     desc1->dpcLineCaps.dwTextureFilterCaps = desc7->dpcLineCaps.dwTextureFilterCaps;
4884     desc1->dpcLineCaps.dwTextureBlendCaps = desc7->dpcLineCaps.dwTextureBlendCaps;
4885     desc1->dpcLineCaps.dwTextureAddressCaps = desc7->dpcLineCaps.dwTextureAddressCaps;
4886     desc1->dpcLineCaps.dwStippleWidth = desc7->dpcLineCaps.dwStippleWidth;
4887     desc1->dpcLineCaps.dwAlphaCmpCaps = desc7->dpcLineCaps.dwAlphaCmpCaps;
4888
4889     desc1->dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
4890     desc1->dpcTriCaps.dwMiscCaps = desc7->dpcTriCaps.dwMiscCaps;
4891     desc1->dpcTriCaps.dwRasterCaps = desc7->dpcTriCaps.dwRasterCaps;
4892     desc1->dpcTriCaps.dwZCmpCaps = desc7->dpcTriCaps.dwZCmpCaps;
4893     desc1->dpcTriCaps.dwSrcBlendCaps = desc7->dpcTriCaps.dwSrcBlendCaps;
4894     desc1->dpcTriCaps.dwDestBlendCaps = desc7->dpcTriCaps.dwDestBlendCaps;
4895     desc1->dpcTriCaps.dwShadeCaps = desc7->dpcTriCaps.dwShadeCaps;
4896     desc1->dpcTriCaps.dwTextureCaps = desc7->dpcTriCaps.dwTextureCaps;
4897     desc1->dpcTriCaps.dwTextureFilterCaps = desc7->dpcTriCaps.dwTextureFilterCaps;
4898     desc1->dpcTriCaps.dwTextureBlendCaps = desc7->dpcTriCaps.dwTextureBlendCaps;
4899     desc1->dpcTriCaps.dwTextureAddressCaps = desc7->dpcTriCaps.dwTextureAddressCaps;
4900     desc1->dpcTriCaps.dwStippleWidth = desc7->dpcTriCaps.dwStippleWidth;
4901     desc1->dpcTriCaps.dwAlphaCmpCaps = desc7->dpcTriCaps.dwAlphaCmpCaps;
4902
4903     desc1->dwDeviceRenderBitDepth = desc7->dwDeviceRenderBitDepth;
4904     desc1->dwDeviceZBufferBitDepth = desc7->dwDeviceZBufferBitDepth;
4905     desc1->dwMaxBufferSize = 0;
4906     desc1->dwMaxVertexCount = 65536;
4907     desc1->dwMinTextureWidth  = desc7->dwMinTextureWidth;
4908     desc1->dwMinTextureHeight = desc7->dwMinTextureHeight;
4909     desc1->dwMaxTextureWidth  = desc7->dwMaxTextureWidth;
4910     desc1->dwMaxTextureHeight = desc7->dwMaxTextureHeight;
4911     desc1->dwMinStippleWidth  = 1;
4912     desc1->dwMinStippleHeight = 1;
4913     desc1->dwMaxStippleWidth  = 32;
4914     desc1->dwMaxStippleHeight = 32;
4915     desc1->dwMaxTextureRepeat = desc7->dwMaxTextureRepeat;
4916     desc1->dwMaxTextureAspectRatio = desc7->dwMaxTextureAspectRatio;
4917     desc1->dwMaxAnisotropy = desc7->dwMaxAnisotropy;
4918     desc1->dvGuardBandLeft = desc7->dvGuardBandLeft;
4919     desc1->dvGuardBandRight = desc7->dvGuardBandRight;
4920     desc1->dvGuardBandTop = desc7->dvGuardBandTop;
4921     desc1->dvGuardBandBottom = desc7->dvGuardBandBottom;
4922     desc1->dvExtentsAdjust = desc7->dvExtentsAdjust;
4923     desc1->dwStencilCaps = desc7->dwStencilCaps;
4924     desc1->dwFVFCaps = desc7->dwFVFCaps;
4925     desc1->dwTextureOpCaps = desc7->dwTextureOpCaps;
4926     desc1->wMaxTextureBlendStages = desc7->wMaxTextureBlendStages;
4927     desc1->wMaxSimultaneousTextures = desc7->wMaxSimultaneousTextures;
4928
4929     return DD_OK;
4930 }
4931
4932 /*****************************************************************************
4933  * IDirectDraw7 VTable
4934  *****************************************************************************/
4935 static const struct IDirectDraw7Vtbl ddraw7_vtbl =
4936 {
4937     /* IUnknown */
4938     ddraw7_QueryInterface,
4939     ddraw7_AddRef,
4940     ddraw7_Release,
4941     /* IDirectDraw */
4942     ddraw7_Compact,
4943     ddraw7_CreateClipper,
4944     ddraw7_CreatePalette,
4945     ddraw7_CreateSurface,
4946     ddraw7_DuplicateSurface,
4947     ddraw7_EnumDisplayModes,
4948     ddraw7_EnumSurfaces,
4949     ddraw7_FlipToGDISurface,
4950     ddraw7_GetCaps,
4951     ddraw7_GetDisplayMode,
4952     ddraw7_GetFourCCCodes,
4953     ddraw7_GetGDISurface,
4954     ddraw7_GetMonitorFrequency,
4955     ddraw7_GetScanLine,
4956     ddraw7_GetVerticalBlankStatus,
4957     ddraw7_Initialize,
4958     ddraw7_RestoreDisplayMode,
4959     ddraw7_SetCooperativeLevel,
4960     ddraw7_SetDisplayMode,
4961     ddraw7_WaitForVerticalBlank,
4962     /* IDirectDraw2 */
4963     ddraw7_GetAvailableVidMem,
4964     /* IDirectDraw3 */
4965     ddraw7_GetSurfaceFromDC,
4966     /* IDirectDraw4 */
4967     ddraw7_RestoreAllSurfaces,
4968     ddraw7_TestCooperativeLevel,
4969     ddraw7_GetDeviceIdentifier,
4970     /* IDirectDraw7 */
4971     ddraw7_StartModeTest,
4972     ddraw7_EvaluateMode
4973 };
4974
4975 static const struct IDirectDraw4Vtbl ddraw4_vtbl =
4976 {
4977     /* IUnknown */
4978     ddraw4_QueryInterface,
4979     ddraw4_AddRef,
4980     ddraw4_Release,
4981     /* IDirectDraw */
4982     ddraw4_Compact,
4983     ddraw4_CreateClipper,
4984     ddraw4_CreatePalette,
4985     ddraw4_CreateSurface,
4986     ddraw4_DuplicateSurface,
4987     ddraw4_EnumDisplayModes,
4988     ddraw4_EnumSurfaces,
4989     ddraw4_FlipToGDISurface,
4990     ddraw4_GetCaps,
4991     ddraw4_GetDisplayMode,
4992     ddraw4_GetFourCCCodes,
4993     ddraw4_GetGDISurface,
4994     ddraw4_GetMonitorFrequency,
4995     ddraw4_GetScanLine,
4996     ddraw4_GetVerticalBlankStatus,
4997     ddraw4_Initialize,
4998     ddraw4_RestoreDisplayMode,
4999     ddraw4_SetCooperativeLevel,
5000     ddraw4_SetDisplayMode,
5001     ddraw4_WaitForVerticalBlank,
5002     /* IDirectDraw2 */
5003     ddraw4_GetAvailableVidMem,
5004     /* IDirectDraw3 */
5005     ddraw4_GetSurfaceFromDC,
5006     /* IDirectDraw4 */
5007     ddraw4_RestoreAllSurfaces,
5008     ddraw4_TestCooperativeLevel,
5009     ddraw4_GetDeviceIdentifier,
5010 };
5011
5012 static const struct IDirectDraw2Vtbl ddraw2_vtbl =
5013 {
5014     /* IUnknown */
5015     ddraw2_QueryInterface,
5016     ddraw2_AddRef,
5017     ddraw2_Release,
5018     /* IDirectDraw */
5019     ddraw2_Compact,
5020     ddraw2_CreateClipper,
5021     ddraw2_CreatePalette,
5022     ddraw2_CreateSurface,
5023     ddraw2_DuplicateSurface,
5024     ddraw2_EnumDisplayModes,
5025     ddraw2_EnumSurfaces,
5026     ddraw2_FlipToGDISurface,
5027     ddraw2_GetCaps,
5028     ddraw2_GetDisplayMode,
5029     ddraw2_GetFourCCCodes,
5030     ddraw2_GetGDISurface,
5031     ddraw2_GetMonitorFrequency,
5032     ddraw2_GetScanLine,
5033     ddraw2_GetVerticalBlankStatus,
5034     ddraw2_Initialize,
5035     ddraw2_RestoreDisplayMode,
5036     ddraw2_SetCooperativeLevel,
5037     ddraw2_SetDisplayMode,
5038     ddraw2_WaitForVerticalBlank,
5039     /* IDirectDraw2 */
5040     ddraw2_GetAvailableVidMem,
5041 };
5042
5043 static const struct IDirectDrawVtbl ddraw1_vtbl =
5044 {
5045     /* IUnknown */
5046     ddraw1_QueryInterface,
5047     ddraw1_AddRef,
5048     ddraw1_Release,
5049     /* IDirectDraw */
5050     ddraw1_Compact,
5051     ddraw1_CreateClipper,
5052     ddraw1_CreatePalette,
5053     ddraw1_CreateSurface,
5054     ddraw1_DuplicateSurface,
5055     ddraw1_EnumDisplayModes,
5056     ddraw1_EnumSurfaces,
5057     ddraw1_FlipToGDISurface,
5058     ddraw1_GetCaps,
5059     ddraw1_GetDisplayMode,
5060     ddraw1_GetFourCCCodes,
5061     ddraw1_GetGDISurface,
5062     ddraw1_GetMonitorFrequency,
5063     ddraw1_GetScanLine,
5064     ddraw1_GetVerticalBlankStatus,
5065     ddraw1_Initialize,
5066     ddraw1_RestoreDisplayMode,
5067     ddraw1_SetCooperativeLevel,
5068     ddraw1_SetDisplayMode,
5069     ddraw1_WaitForVerticalBlank,
5070 };
5071
5072 static const struct IDirect3D7Vtbl d3d7_vtbl =
5073 {
5074     /* IUnknown methods */
5075     d3d7_QueryInterface,
5076     d3d7_AddRef,
5077     d3d7_Release,
5078     /* IDirect3D7 methods */
5079     d3d7_EnumDevices,
5080     d3d7_CreateDevice,
5081     d3d7_CreateVertexBuffer,
5082     d3d7_EnumZBufferFormats,
5083     d3d7_EvictManagedTextures
5084 };
5085
5086 static const struct IDirect3D3Vtbl d3d3_vtbl =
5087 {
5088     /* IUnknown methods */
5089     d3d3_QueryInterface,
5090     d3d3_AddRef,
5091     d3d3_Release,
5092     /* IDirect3D3 methods */
5093     d3d3_EnumDevices,
5094     d3d3_CreateLight,
5095     d3d3_CreateMaterial,
5096     d3d3_CreateViewport,
5097     d3d3_FindDevice,
5098     d3d3_CreateDevice,
5099     d3d3_CreateVertexBuffer,
5100     d3d3_EnumZBufferFormats,
5101     d3d3_EvictManagedTextures
5102 };
5103
5104 static const struct IDirect3D2Vtbl d3d2_vtbl =
5105 {
5106     /* IUnknown methods */
5107     d3d2_QueryInterface,
5108     d3d2_AddRef,
5109     d3d2_Release,
5110     /* IDirect3D2 methods */
5111     d3d2_EnumDevices,
5112     d3d2_CreateLight,
5113     d3d2_CreateMaterial,
5114     d3d2_CreateViewport,
5115     d3d2_FindDevice,
5116     d3d2_CreateDevice
5117 };
5118
5119 static const struct IDirect3DVtbl d3d1_vtbl =
5120 {
5121     /* IUnknown methods */
5122     d3d1_QueryInterface,
5123     d3d1_AddRef,
5124     d3d1_Release,
5125     /* IDirect3D methods */
5126     d3d1_Initialize,
5127     d3d1_EnumDevices,
5128     d3d1_CreateLight,
5129     d3d1_CreateMaterial,
5130     d3d1_CreateViewport,
5131     d3d1_FindDevice
5132 };
5133
5134 /*****************************************************************************
5135  * ddraw_find_decl
5136  *
5137  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
5138  * if none was found.
5139  *
5140  * This function is in ddraw.c and the DDraw object space because D3D7
5141  * vertex buffers are created using the IDirect3D interface to the ddraw
5142  * object, so they can be valid across D3D devices(theoretically. The ddraw
5143  * object also owns the wined3d device
5144  *
5145  * Parameters:
5146  *  This: Device
5147  *  fvf: Fvf to find the decl for
5148  *
5149  * Returns:
5150  *  NULL in case of an error, the vertex declaration for the FVF otherwise.
5151  *
5152  *****************************************************************************/
5153 struct wined3d_vertex_declaration *ddraw_find_decl(struct ddraw *This, DWORD fvf)
5154 {
5155     struct wined3d_vertex_declaration *pDecl = NULL;
5156     HRESULT hr;
5157     int p, low, high; /* deliberately signed */
5158     struct FvfToDecl *convertedDecls = This->decls;
5159
5160     TRACE("Searching for declaration for fvf %08x... ", fvf);
5161
5162     low = 0;
5163     high = This->numConvertedDecls - 1;
5164     while(low <= high) {
5165         p = (low + high) >> 1;
5166         TRACE("%d ", p);
5167         if(convertedDecls[p].fvf == fvf) {
5168             TRACE("found %p\n", convertedDecls[p].decl);
5169             return convertedDecls[p].decl;
5170         } else if(convertedDecls[p].fvf < fvf) {
5171             low = p + 1;
5172         } else {
5173             high = p - 1;
5174         }
5175     }
5176     TRACE("not found. Creating and inserting at position %d.\n", low);
5177
5178     hr = wined3d_vertex_declaration_create_from_fvf(This->wined3d_device,
5179             fvf, This, &ddraw_null_wined3d_parent_ops, &pDecl);
5180     if (hr != S_OK) return NULL;
5181
5182     if(This->declArraySize == This->numConvertedDecls) {
5183         int grow = max(This->declArraySize / 2, 8);
5184         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
5185                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
5186         if (!convertedDecls)
5187         {
5188             wined3d_vertex_declaration_decref(pDecl);
5189             return NULL;
5190         }
5191         This->decls = convertedDecls;
5192         This->declArraySize += grow;
5193     }
5194
5195     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
5196     convertedDecls[low].decl = pDecl;
5197     convertedDecls[low].fvf = fvf;
5198     This->numConvertedDecls++;
5199
5200     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
5201     return pDecl;
5202 }
5203
5204 static inline struct ddraw *ddraw_from_device_parent(struct wined3d_device_parent *device_parent)
5205 {
5206     return CONTAINING_RECORD(device_parent, struct ddraw, device_parent);
5207 }
5208
5209 static void CDECL device_parent_wined3d_device_created(struct wined3d_device_parent *device_parent,
5210         struct wined3d_device *device)
5211 {
5212     TRACE("device_parent %p, device %p.\n", device_parent, device);
5213 }
5214
5215 /* This is run from device_process_message() in wined3d, we can't take the
5216  * wined3d mutex. */
5217 static void CDECL device_parent_mode_changed(struct wined3d_device_parent *device_parent)
5218 {
5219     struct ddraw *ddraw = ddraw_from_device_parent(device_parent);
5220     MONITORINFO monitor_info;
5221     HMONITOR monitor;
5222     BOOL ret;
5223     RECT *r;
5224
5225     TRACE("device_parent %p.\n", device_parent);
5226
5227     if (!(ddraw->cooperative_level & DDSCL_EXCLUSIVE) || !ddraw->swapchain_window)
5228     {
5229         TRACE("Nothing to resize.\n");
5230         return;
5231     }
5232
5233     monitor = MonitorFromWindow(ddraw->swapchain_window, MONITOR_DEFAULTTOPRIMARY);
5234     monitor_info.cbSize = sizeof(monitor_info);
5235     if (!(ret = GetMonitorInfoW(monitor, &monitor_info)))
5236     {
5237         ERR("Failed to get monitor info.\n");
5238         return;
5239     }
5240
5241     r = &monitor_info.rcMonitor;
5242     TRACE("Resizing window %p to %s.\n", ddraw->swapchain_window, wine_dbgstr_rect(r));
5243
5244     if (!(ret = SetWindowPos(ddraw->swapchain_window, HWND_TOP, r->left, r->top,
5245             r->right - r->left, r->bottom - r->top, SWP_SHOWWINDOW | SWP_NOACTIVATE)))
5246         ERR("Failed to resize window.\n");
5247 }
5248
5249 static HRESULT CDECL device_parent_create_texture_surface(struct wined3d_device_parent *device_parent,
5250         void *container_parent, UINT width, UINT height, enum wined3d_format_id format, DWORD usage,
5251         enum wined3d_pool pool, UINT level, enum wined3d_cubemap_face face, struct wined3d_surface **surface)
5252 {
5253     struct ddraw *ddraw = ddraw_from_device_parent(device_parent);
5254     struct ddraw_surface *tex_root = container_parent;
5255     DDSURFACEDESC2 desc = tex_root->surface_desc;
5256     struct ddraw_surface *ddraw_surface;
5257     HRESULT hr;
5258
5259     TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, usage %#x,\n"
5260             "\tpool %#x, level %u, face %u, surface %p.\n",
5261             device_parent, container_parent, width, height, format, usage, pool, level, face, surface);
5262
5263     /* The ddraw root surface is created before the wined3d texture. */
5264     if (!level && face == WINED3D_CUBEMAP_FACE_POSITIVE_X)
5265     {
5266         ddraw_surface = tex_root;
5267         goto done;
5268     }
5269
5270     desc.dwWidth = width;
5271     desc.dwHeight = height;
5272     if (level)
5273         desc.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
5274     else
5275         desc.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
5276
5277     if (desc.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
5278     {
5279         desc.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
5280
5281         switch (face)
5282         {
5283             case WINED3D_CUBEMAP_FACE_POSITIVE_X:
5284                 desc.ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
5285                 break;
5286
5287             case WINED3D_CUBEMAP_FACE_NEGATIVE_X:
5288                 desc.ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX;
5289                 break;
5290
5291             case WINED3D_CUBEMAP_FACE_POSITIVE_Y:
5292                 desc.ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY;
5293                 break;
5294
5295             case WINED3D_CUBEMAP_FACE_NEGATIVE_Y:
5296                 desc.ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY;
5297                 break;
5298
5299             case WINED3D_CUBEMAP_FACE_POSITIVE_Z:
5300                 desc.ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ;
5301                 break;
5302
5303             case WINED3D_CUBEMAP_FACE_NEGATIVE_Z:
5304                 desc.ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ;
5305                 break;
5306
5307             default:
5308                 ERR("Unexpected cube face.\n");
5309                 return DDERR_INVALIDPARAMS;
5310         }
5311
5312     }
5313
5314     /* FIXME: Validate that format, usage, pool, etc. really make sense. */
5315     if (FAILED(hr = ddraw_create_surface(ddraw, &desc, &ddraw_surface, level, tex_root->version)))
5316         return hr;
5317
5318 done:
5319     *surface = ddraw_surface->wined3d_surface;
5320     wined3d_surface_incref(*surface);
5321
5322     return DD_OK;
5323 }
5324
5325 static void STDMETHODCALLTYPE ddraw_frontbuffer_destroyed(void *parent)
5326 {
5327     struct ddraw *ddraw = parent;
5328     ddraw->wined3d_frontbuffer = NULL;
5329 }
5330
5331 static const struct wined3d_parent_ops ddraw_frontbuffer_parent_ops =
5332 {
5333     ddraw_frontbuffer_destroyed,
5334 };
5335
5336 static HRESULT CDECL device_parent_create_swapchain_surface(struct wined3d_device_parent *device_parent,
5337         void *container_parent, UINT width, UINT height, enum wined3d_format_id format_id, DWORD usage,
5338         enum wined3d_multisample_type multisample_type, DWORD multisample_quality, struct wined3d_surface **surface)
5339 {
5340     struct ddraw *ddraw = ddraw_from_device_parent(device_parent);
5341     HRESULT hr;
5342
5343     TRACE("device_parent %p, container_parent %p, width %u, height %u, format_id %#x, usage %#x,\n"
5344             "\tmultisample_type %#x, multisample_quality %u, surface %p.\n",
5345             device_parent, container_parent, width, height, format_id, usage,
5346             multisample_type, multisample_quality, surface);
5347
5348     if (ddraw->wined3d_frontbuffer)
5349     {
5350         ERR("Frontbuffer already created.\n");
5351         return E_FAIL;
5352     }
5353
5354     if (SUCCEEDED(hr = wined3d_surface_create(ddraw->wined3d_device, width, height, format_id, 0,
5355             usage, WINED3D_POOL_DEFAULT, multisample_type, multisample_quality, DefaultSurfaceType,
5356             WINED3D_SURFACE_MAPPABLE, ddraw, &ddraw_frontbuffer_parent_ops, surface)))
5357         ddraw->wined3d_frontbuffer = *surface;
5358
5359     return hr;
5360 }
5361
5362 static HRESULT CDECL device_parent_create_volume(struct wined3d_device_parent *device_parent,
5363         void *container_parent, UINT width, UINT height, UINT depth, enum wined3d_format_id format,
5364         enum wined3d_pool pool, DWORD usage, struct wined3d_volume **volume)
5365 {
5366     TRACE("device_parent %p, container_parent %p, width %u, height %u, depth %u, "
5367             "format %#x, pool %#x, usage %#x, volume %p.\n",
5368             device_parent, container_parent, width, height, depth,
5369             format, pool, usage, volume);
5370
5371     ERR("Not implemented!\n");
5372
5373     return E_NOTIMPL;
5374 }
5375
5376 static HRESULT CDECL device_parent_create_swapchain(struct wined3d_device_parent *device_parent,
5377         struct wined3d_swapchain_desc *desc, struct wined3d_swapchain **swapchain)
5378 {
5379     struct ddraw *ddraw = ddraw_from_device_parent(device_parent);
5380     HRESULT hr;
5381
5382     TRACE("device_parent %p, desc %p, swapchain %p.\n", device_parent, desc, swapchain);
5383
5384     if (ddraw->wined3d_swapchain)
5385     {
5386         ERR("Swapchain already created.\n");
5387         return E_FAIL;
5388     }
5389
5390     hr = wined3d_swapchain_create(ddraw->wined3d_device, desc,
5391             DefaultSurfaceType, NULL, &ddraw_null_wined3d_parent_ops, swapchain);
5392     if (FAILED(hr))
5393         WARN("Failed to create swapchain, hr %#x.\n", hr);
5394
5395     return hr;
5396 }
5397
5398 static const struct wined3d_device_parent_ops ddraw_wined3d_device_parent_ops =
5399 {
5400     device_parent_wined3d_device_created,
5401     device_parent_mode_changed,
5402     device_parent_create_swapchain_surface,
5403     device_parent_create_texture_surface,
5404     device_parent_create_volume,
5405     device_parent_create_swapchain,
5406 };
5407
5408 HRESULT ddraw_init(struct ddraw *ddraw, enum wined3d_device_type device_type)
5409 {
5410     HRESULT hr;
5411     HDC hDC;
5412
5413     ddraw->IDirectDraw7_iface.lpVtbl = &ddraw7_vtbl;
5414     ddraw->IDirectDraw_iface.lpVtbl = &ddraw1_vtbl;
5415     ddraw->IDirectDraw2_iface.lpVtbl = &ddraw2_vtbl;
5416     ddraw->IDirectDraw4_iface.lpVtbl = &ddraw4_vtbl;
5417     ddraw->IDirect3D_iface.lpVtbl = &d3d1_vtbl;
5418     ddraw->IDirect3D2_iface.lpVtbl = &d3d2_vtbl;
5419     ddraw->IDirect3D3_iface.lpVtbl = &d3d3_vtbl;
5420     ddraw->IDirect3D7_iface.lpVtbl = &d3d7_vtbl;
5421     ddraw->device_parent.ops = &ddraw_wined3d_device_parent_ops;
5422     ddraw->numIfaces = 1;
5423     ddraw->ref7 = 1;
5424
5425     /* Get the current screen settings. */
5426     hDC = GetDC(0);
5427     ddraw->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
5428     ReleaseDC(0, hDC);
5429     ddraw->orig_width = GetSystemMetrics(SM_CXSCREEN);
5430     ddraw->orig_height = GetSystemMetrics(SM_CYSCREEN);
5431
5432     ddraw->wined3d = wined3d_create(7, WINED3D_LEGACY_DEPTH_BIAS);
5433     if (!ddraw->wined3d)
5434     {
5435         WARN("Failed to create a wined3d object.\n");
5436         return E_OUTOFMEMORY;
5437     }
5438
5439     hr = wined3d_device_create(ddraw->wined3d, WINED3DADAPTER_DEFAULT, device_type,
5440             NULL, 0, 8, &ddraw->device_parent, &ddraw->wined3d_device);
5441     if (FAILED(hr))
5442     {
5443         WARN("Failed to create a wined3d device, hr %#x.\n", hr);
5444         wined3d_decref(ddraw->wined3d);
5445         return hr;
5446     }
5447
5448     list_init(&ddraw->surface_list);
5449
5450     return DD_OK;
5451 }