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