ddraw: Don't allow SetPalette on mipmap sublevels instead of root surfaces.
[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     /* Use the surface description for the device parameters, not the device
2765      * settings. The application might render to an offscreen surface. */
2766     localParameters.BackBufferWidth = primary->surface_desc.dwWidth;
2767     localParameters.BackBufferHeight = primary->surface_desc.dwHeight;
2768     localParameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2769     localParameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2770             ? primary->surface_desc.dwBackBufferCount : 0;
2771     localParameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2772     localParameters.MultiSampleQuality = 0;
2773     localParameters.SwapEffect = WINED3DSWAPEFFECT_COPY;
2774     localParameters.hDeviceWindow = window;
2775     localParameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2776     localParameters.EnableAutoDepthStencil = FALSE;
2777     localParameters.AutoDepthStencilFormat = WINED3DFMT_UNKNOWN;
2778     localParameters.Flags = 0;
2779     localParameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2780     localParameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2781     localParameters.AutoRestoreDisplayMode = FALSE;
2782
2783     /* Set this NOW, otherwise creating the depth stencil surface will cause a
2784      * recursive loop until ram or emulated video memory is full. */
2785     ddraw->d3d_initialized = TRUE;
2786     hr = wined3d_device_init_3d(ddraw->wined3d_device, &localParameters);
2787     if (FAILED(hr))
2788     {
2789         ddraw->d3d_target = NULL;
2790         ddraw->d3d_initialized = FALSE;
2791         return hr;
2792     }
2793
2794     ddraw->declArraySize = 2;
2795     ddraw->decls = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw->decls) * ddraw->declArraySize);
2796     if (!ddraw->decls)
2797     {
2798         ERR("Error allocating an array for the converted vertex decls.\n");
2799         ddraw->declArraySize = 0;
2800         hr = wined3d_device_uninit_3d(ddraw->wined3d_device);
2801         return E_OUTOFMEMORY;
2802     }
2803
2804     TRACE("Successfully initialized 3D.\n");
2805
2806     return DD_OK;
2807 }
2808
2809 static HRESULT ddraw_create_gdi_swapchain(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2810 {
2811     WINED3DPRESENT_PARAMETERS presentation_parameters;
2812     HWND window;
2813     HRESULT hr;
2814
2815     window = ddraw->dest_window;
2816
2817     memset(&presentation_parameters, 0, sizeof(presentation_parameters));
2818
2819     /* Use the surface description for the device parameters, not the device
2820      * settings. The application might render to an offscreen surface. */
2821     presentation_parameters.BackBufferWidth = primary->surface_desc.dwWidth;
2822     presentation_parameters.BackBufferHeight = primary->surface_desc.dwHeight;
2823     presentation_parameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2824     presentation_parameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2825             ? primary->surface_desc.dwBackBufferCount : 0;
2826     presentation_parameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2827     presentation_parameters.MultiSampleQuality = 0;
2828     presentation_parameters.SwapEffect = WINED3DSWAPEFFECT_FLIP;
2829     presentation_parameters.hDeviceWindow = window;
2830     presentation_parameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2831     presentation_parameters.EnableAutoDepthStencil = FALSE; /* Not on GDI swapchains */
2832     presentation_parameters.AutoDepthStencilFormat = 0;
2833     presentation_parameters.Flags = 0;
2834     presentation_parameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2835     presentation_parameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2836     presentation_parameters.AutoRestoreDisplayMode = FALSE;
2837
2838     ddraw->d3d_target = primary;
2839     hr = wined3d_device_init_gdi(ddraw->wined3d_device, &presentation_parameters);
2840     ddraw->d3d_target = NULL;
2841     if (FAILED(hr))
2842     {
2843         WARN("Failed to initialize GDI ddraw implementation, hr %#x.\n", hr);
2844         primary->wined3d_swapchain = NULL;
2845     }
2846
2847     return hr;
2848 }
2849
2850 /*****************************************************************************
2851  * IDirectDraw7::CreateSurface
2852  *
2853  * Creates a new IDirectDrawSurface object and returns its interface.
2854  *
2855  * The surface connections with wined3d are a bit tricky. Basically it works
2856  * like this:
2857  *
2858  * |------------------------|               |-----------------|
2859  * | DDraw surface          |               | WineD3DSurface  |
2860  * |                        |               |                 |
2861  * |        WineD3DSurface  |-------------->|                 |
2862  * |        Child           |<------------->| Parent          |
2863  * |------------------------|               |-----------------|
2864  *
2865  * The DDraw surface is the parent of the wined3d surface, and it releases
2866  * the WineD3DSurface when the ddraw surface is destroyed.
2867  *
2868  * However, for all surfaces which can be in a container in WineD3D,
2869  * we have to do this. These surfaces are usually complex surfaces,
2870  * so this concerns primary surfaces with a front and a back buffer,
2871  * and textures.
2872  *
2873  * |------------------------|               |-----------------|
2874  * | DDraw surface          |               | Container       |
2875  * |                        |               |                 |
2876  * |                  Child |<------------->| Parent          |
2877  * |                Texture |<------------->|                 |
2878  * |         WineD3DSurface |<----|         |          Levels |<--|
2879  * | Complex connection     |     |         |                 |   |
2880  * |------------------------|     |         |-----------------|   |
2881  *  ^                             |                               |
2882  *  |                             |                               |
2883  *  |                             |                               |
2884  *  |    |------------------|     |         |-----------------|   |
2885  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2886  *  |    |                  |               |                 |   |
2887  *  |    |            Child |<------------->| Parent          |   |
2888  *  |    |                  |               |       Container |<--|
2889  *  |    |------------------|               |-----------------|   |
2890  *  |                                                             |
2891  *  |   |----------------------|                                  |
2892  *  |   | DDraw surface 2      |                                  |
2893  *  |   |                      |                                  |
2894  *  |<->| Complex root   Child |                                  |
2895  *  |   |              Texture |                                  |
2896  *  |   |       WineD3DSurface |<----|                            |
2897  *  |   |----------------------|     |                            |
2898  *  |                                |                            |
2899  *  |    |---------------------|     |      |-----------------|   |
2900  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2901  *  |    |                     |            |                 |   |
2902  *  |    |               Child |<---------->| Parent          |   |
2903  *  |    |---------------------|            |       Container |<--|
2904  *  |                                       |-----------------|   |
2905  *  |                                                             |
2906  *  |             ---More surfaces can follow---                  |
2907  *
2908  * The reason is that the IWineD3DSwapchain(render target container)
2909  * and the IWineD3DTexure(Texture container) release the parents
2910  * of their surface's children, but by releasing the complex root
2911  * the surfaces which are complexly attached to it are destroyed
2912  * too. See IDirectDrawSurface::Release for a more detailed
2913  * explanation.
2914  *
2915  * Params:
2916  *  DDSD: Description of the surface to create
2917  *  Surf: Address to store the interface pointer at
2918  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2919  *            aggregation, so it has to be NULL
2920  *
2921  * Returns:
2922  *  DD_OK on success
2923  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2924  *  DDERR_* if an error occurs
2925  *
2926  *****************************************************************************/
2927 static HRESULT CreateSurface(IDirectDrawImpl *ddraw, DDSURFACEDESC2 *DDSD,
2928         IDirectDrawSurfaceImpl **Surf, IUnknown *UnkOuter, UINT version)
2929 {
2930     IDirectDrawSurfaceImpl *object = NULL;
2931     HRESULT hr;
2932     LONG extra_surfaces = 0;
2933     DDSURFACEDESC2 desc2;
2934     WINED3DDISPLAYMODE Mode;
2935     const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
2936
2937     TRACE("ddraw %p, surface_desc %p, surface %p, outer_unknown %p.\n", ddraw, DDSD, Surf, UnkOuter);
2938
2939     /* Some checks before we start */
2940     if (TRACE_ON(ddraw))
2941     {
2942         TRACE(" (%p) Requesting surface desc :\n", ddraw);
2943         DDRAW_dump_surface_desc(DDSD);
2944     }
2945     EnterCriticalSection(&ddraw_cs);
2946
2947     if (UnkOuter != NULL)
2948     {
2949         FIXME("(%p) : outer != NULL?\n", ddraw);
2950         LeaveCriticalSection(&ddraw_cs);
2951         return CLASS_E_NOAGGREGATION; /* unchecked */
2952     }
2953
2954     if (Surf == NULL)
2955     {
2956         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", ddraw);
2957         LeaveCriticalSection(&ddraw_cs);
2958         return E_POINTER; /* unchecked */
2959     }
2960
2961     if (!(DDSD->dwFlags & DDSD_CAPS))
2962     {
2963         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2964         DDSD->dwFlags |= DDSD_CAPS;
2965     }
2966
2967     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2968     {
2969         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2970         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2971     }
2972
2973     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2974     {
2975         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2976         WARN("(%p) Null surface pointer specified, ignore it!\n", ddraw);
2977         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2978     }
2979
2980     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2981        !(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
2982     {
2983         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n",
2984                 ddraw);
2985         *Surf = NULL;
2986         LeaveCriticalSection(&ddraw_cs);
2987         return DDERR_NOEXCLUSIVEMODE;
2988     }
2989
2990     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE))
2991     {
2992         WARN("Application wanted to create back buffer primary surface\n");
2993         LeaveCriticalSection(&ddraw_cs);
2994         return DDERR_INVALIDCAPS;
2995     }
2996
2997     if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
2998     {
2999         /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
3000         WARN("Application tries to put the surface in both system and video memory\n");
3001         LeaveCriticalSection(&ddraw_cs);
3002         *Surf = NULL;
3003         return DDERR_INVALIDCAPS;
3004     }
3005
3006     /* Check cube maps but only if the size includes them */
3007     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
3008     {
3009         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
3010            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
3011         {
3012             WARN("Cube map faces requested without cube map flag\n");
3013             LeaveCriticalSection(&ddraw_cs);
3014             return DDERR_INVALIDCAPS;
3015         }
3016         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
3017            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
3018         {
3019             WARN("Cube map without faces requested\n");
3020             LeaveCriticalSection(&ddraw_cs);
3021             return DDERR_INVALIDPARAMS;
3022         }
3023
3024         /* Quick tests confirm those can be created, but we don't do that yet */
3025         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
3026            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
3027         {
3028             FIXME("Partial cube maps not supported yet\n");
3029         }
3030     }
3031
3032     /* According to the msdn this flag is ignored by CreateSurface */
3033     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
3034         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
3035
3036     /* Modify some flags */
3037     copy_to_surfacedesc2(&desc2, DDSD);
3038     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
3039
3040     /* Get the video mode from WineD3D - we will need it */
3041     hr = wined3d_device_get_display_mode(ddraw->wined3d_device, 0, &Mode);
3042     if (FAILED(hr))
3043     {
3044         ERR("Failed to read display mode from wined3d\n");
3045         switch(ddraw->orig_bpp)
3046         {
3047             case 8:
3048                 Mode.Format = WINED3DFMT_P8_UINT;
3049                 break;
3050
3051             case 15:
3052                 Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;
3053                 break;
3054
3055             case 16:
3056                 Mode.Format = WINED3DFMT_B5G6R5_UNORM;
3057                 break;
3058
3059             case 24:
3060                 Mode.Format = WINED3DFMT_B8G8R8_UNORM;
3061                 break;
3062
3063             case 32:
3064                 Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;
3065                 break;
3066         }
3067         Mode.Width = ddraw->orig_width;
3068         Mode.Height = ddraw->orig_height;
3069     }
3070
3071     /* No pixelformat given? Use the current screen format */
3072     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
3073     {
3074         desc2.dwFlags |= DDSD_PIXELFORMAT;
3075         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
3076
3077         PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
3078     }
3079
3080     /* No Width or no Height? Use the original screen size
3081      */
3082     if(!(desc2.dwFlags & DDSD_WIDTH) ||
3083        !(desc2.dwFlags & DDSD_HEIGHT) )
3084     {
3085         /* Invalid for non-render targets */
3086         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
3087         {
3088             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
3089             *Surf = NULL;
3090             LeaveCriticalSection(&ddraw_cs);
3091             return DDERR_INVALIDPARAMS;
3092         }
3093
3094         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
3095         desc2.dwWidth = Mode.Width;
3096         desc2.dwHeight = Mode.Height;
3097     }
3098
3099     if (!desc2.dwWidth || !desc2.dwHeight)
3100     {
3101         LeaveCriticalSection(&ddraw_cs);
3102         return DDERR_INVALIDPARAMS;
3103     }
3104
3105     /* Mipmap count fixes */
3106     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
3107     {
3108         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
3109         {
3110             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
3111             {
3112                 /* Mipmap count is given, should not be 0 */
3113                 if( desc2.u2.dwMipMapCount == 0 )
3114                 {
3115                     LeaveCriticalSection(&ddraw_cs);
3116                     return DDERR_INVALIDPARAMS;
3117                 }
3118             }
3119             else
3120             {
3121                 /* Undocumented feature: Create sublevels until
3122                  * either the width or the height is 1
3123                  */
3124                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
3125                             desc2.dwWidth : desc2.dwHeight;
3126                 desc2.u2.dwMipMapCount = 0;
3127                 while( min )
3128                 {
3129                     desc2.u2.dwMipMapCount += 1;
3130                     min >>= 1;
3131                 }
3132             }
3133         }
3134         else
3135         {
3136             /* Not-complex mipmap -> Mipmapcount = 1 */
3137             desc2.u2.dwMipMapCount = 1;
3138         }
3139         extra_surfaces = desc2.u2.dwMipMapCount - 1;
3140
3141         /* There's a mipmap count in the created surface in any case */
3142         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
3143     }
3144     /* If no mipmap is given, the texture has only one level */
3145
3146     /* The first surface is a front buffer, the back buffer is created afterwards */
3147     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
3148     {
3149         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
3150     }
3151
3152     /* The root surface in a cube map is positive x */
3153     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3154     {
3155         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3156         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3157     }
3158
3159     /* Create the first surface */
3160     hr = ddraw_create_surface(ddraw, &desc2, &object, 0, version);
3161     if (FAILED(hr))
3162     {
3163         WARN("ddraw_create_surface failed, hr %#x.\n", hr);
3164         LeaveCriticalSection(&ddraw_cs);
3165         return hr;
3166     }
3167     object->is_complex_root = TRUE;
3168
3169     *Surf = object;
3170
3171     /* Create Additional surfaces if necessary
3172      * This applies to Primary surfaces which have a back buffer count
3173      * set, but not to mipmap textures. In case of Mipmap textures,
3174      * wineD3D takes care of the creation of additional surfaces
3175      */
3176     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
3177     {
3178         extra_surfaces = DDSD->dwBackBufferCount;
3179         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
3180         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
3181         desc2.dwBackBufferCount = 0;
3182     }
3183
3184     hr = DD_OK;
3185     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3186     {
3187         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3188         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
3189         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
3190         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
3191         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
3192         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
3193         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
3194         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
3195         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
3196         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
3197         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
3198         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
3199         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
3200         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
3201         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
3202         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
3203         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3204     }
3205
3206     hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces, desc2, FALSE, version);
3207     if(hr != DD_OK)
3208     {
3209         /* This destroys and possibly created surfaces too */
3210         if (version == 7)
3211         {
3212             IDirectDrawSurface7_Release(&object->IDirectDrawSurface7_iface);
3213         }
3214         else if (version == 4)
3215         {
3216             IDirectDrawSurface4_Release(&object->IDirectDrawSurface4_iface);
3217         }
3218         else
3219         {
3220             IDirectDrawSurface_Release(&object->IDirectDrawSurface_iface);
3221         }
3222         LeaveCriticalSection(&ddraw_cs);
3223         return hr;
3224     }
3225
3226     /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
3227      * But attach the d3ddevice only if the currently created surface was
3228      * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
3229      * The only case I can think of where this doesn't apply is when a
3230      * 2D app was configured by the user to run with OpenGL and it didn't create
3231      * the render target as first surface. In this case the render target creation
3232      * will cause the 3D init. */
3233     if (DefaultSurfaceType == SURFACE_OPENGL && !ddraw->d3d_initialized
3234             && desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE))
3235     {
3236         IDirectDrawSurfaceImpl *target = object, *surface;
3237         struct list *entry;
3238
3239         /* Search for the primary to use as render target */
3240         LIST_FOR_EACH(entry, &ddraw->surface_list)
3241         {
3242             surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3243             if((surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER)) ==
3244                (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER))
3245             {
3246                 /* found */
3247                 target = surface;
3248                 TRACE("Using primary %p as render target\n", target);
3249                 break;
3250             }
3251         }
3252
3253         TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", ddraw, target);
3254         hr = ddraw_attach_d3d_device(ddraw, target);
3255         if (hr != D3D_OK)
3256         {
3257             IDirectDrawSurfaceImpl *release_surf;
3258             ERR("ddraw_attach_d3d_device failed, hr %#x\n", hr);
3259             *Surf = NULL;
3260
3261             /* The before created surface structures are in an incomplete state here.
3262              * WineD3D holds the reference on the IParents, and it released them on the failure
3263              * already. So the regular release method implementation would fail on the attempt
3264              * to destroy either the IParents or the swapchain. So free the surface here.
3265              * The surface structure here is a list, not a tree, because onscreen targets
3266              * cannot be cube textures
3267              */
3268             while(object)
3269             {
3270                 release_surf = object;
3271                 object = object->complex_array[0];
3272                 ddraw_surface_destroy(release_surf);
3273             }
3274             LeaveCriticalSection(&ddraw_cs);
3275             return hr;
3276         }
3277     }
3278     else if(!(ddraw->d3d_initialized) && desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
3279     {
3280         ddraw_create_gdi_swapchain(ddraw, object);
3281     }
3282
3283     /* Create a WineD3DTexture if a texture was requested */
3284     if (desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
3285     {
3286         ddraw->tex_root = object;
3287         ddraw_surface_create_texture(object);
3288         ddraw->tex_root = NULL;
3289     }
3290
3291     LeaveCriticalSection(&ddraw_cs);
3292     return hr;
3293 }
3294
3295 static HRESULT WINAPI ddraw7_CreateSurface(IDirectDraw7 *iface, DDSURFACEDESC2 *surface_desc,
3296         IDirectDrawSurface7 **surface, IUnknown *outer_unknown)
3297 {
3298     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3299     IDirectDrawSurfaceImpl *impl;
3300     HRESULT hr;
3301
3302     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3303             iface, surface_desc, surface, outer_unknown);
3304
3305     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3306     {
3307         WARN("Application supplied invalid surface descriptor\n");
3308         return DDERR_INVALIDPARAMS;
3309     }
3310
3311     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3312     {
3313         if (TRACE_ON(ddraw))
3314         {
3315             TRACE(" (%p) Requesting surface desc :\n", iface);
3316             DDRAW_dump_surface_desc(surface_desc);
3317         }
3318
3319         WARN("Application tried to create an explicit front or back buffer\n");
3320         return DDERR_INVALIDCAPS;
3321     }
3322
3323     hr = CreateSurface(This, surface_desc, &impl, outer_unknown, 7);
3324     if (FAILED(hr))
3325     {
3326         *surface = NULL;
3327         return hr;
3328     }
3329
3330     *surface = &impl->IDirectDrawSurface7_iface;
3331     IDirectDraw7_AddRef(iface);
3332     impl->ifaceToRelease = (IUnknown *)iface;
3333
3334     return hr;
3335 }
3336
3337 static HRESULT WINAPI ddraw4_CreateSurface(IDirectDraw4 *iface,
3338         DDSURFACEDESC2 *surface_desc, IDirectDrawSurface4 **surface, IUnknown *outer_unknown)
3339 {
3340     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3341     IDirectDrawSurfaceImpl *impl;
3342     HRESULT hr;
3343
3344     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3345             iface, surface_desc, surface, outer_unknown);
3346
3347     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3348     {
3349         WARN("Application supplied invalid surface descriptor\n");
3350         return DDERR_INVALIDPARAMS;
3351     }
3352
3353     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3354     {
3355         if (TRACE_ON(ddraw))
3356         {
3357             TRACE(" (%p) Requesting surface desc :\n", iface);
3358             DDRAW_dump_surface_desc(surface_desc);
3359         }
3360
3361         WARN("Application tried to create an explicit front or back buffer\n");
3362         return DDERR_INVALIDCAPS;
3363     }
3364
3365     hr = CreateSurface(This, surface_desc, &impl, outer_unknown, 4);
3366     if (FAILED(hr))
3367     {
3368         *surface = NULL;
3369         return hr;
3370     }
3371
3372     *surface = &impl->IDirectDrawSurface4_iface;
3373     IDirectDraw4_AddRef(iface);
3374     impl->ifaceToRelease = (IUnknown *)iface;
3375
3376     return hr;
3377 }
3378
3379 static HRESULT WINAPI ddraw3_CreateSurface(IDirectDraw3 *iface, DDSURFACEDESC *surface_desc,
3380         IDirectDrawSurface **surface, IUnknown *outer_unknown)
3381 {
3382     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3383     IDirectDrawSurfaceImpl *impl;
3384     HRESULT hr;
3385     DDSURFACEDESC2 surface_desc2;
3386
3387     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3388             iface, surface_desc, surface, outer_unknown);
3389
3390     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3391     {
3392         WARN("Application supplied invalid surface descriptor\n");
3393         return DDERR_INVALIDPARAMS;
3394     }
3395     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3396
3397     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3398     {
3399         if (TRACE_ON(ddraw))
3400         {
3401             TRACE(" (%p) Requesting surface desc :\n", iface);
3402             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3403         }
3404
3405         WARN("Application tried to create an explicit front or back buffer\n");
3406         return DDERR_INVALIDCAPS;
3407     }
3408
3409     hr = CreateSurface(This, &surface_desc2, &impl, outer_unknown, 3);
3410     if (FAILED(hr))
3411     {
3412         *surface = NULL;
3413         return hr;
3414     }
3415
3416     *surface = &impl->IDirectDrawSurface_iface;
3417     IDirectDraw3_AddRef(iface);
3418     impl->ifaceToRelease = (IUnknown *)iface;
3419
3420     return hr;
3421 }
3422
3423 static HRESULT WINAPI ddraw2_CreateSurface(IDirectDraw2 *iface,
3424         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3425 {
3426     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3427     IDirectDrawSurfaceImpl *impl;
3428     HRESULT hr;
3429     DDSURFACEDESC2 surface_desc2;
3430
3431     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3432             iface, surface_desc, surface, outer_unknown);
3433
3434     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3435     {
3436         WARN("Application supplied invalid surface descriptor\n");
3437         return DDERR_INVALIDPARAMS;
3438     }
3439
3440     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3441     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3442     {
3443         if (TRACE_ON(ddraw))
3444         {
3445             TRACE(" (%p) Requesting surface desc :\n", iface);
3446             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3447         }
3448
3449         WARN("Application tried to create an explicit front or back buffer\n");
3450         return DDERR_INVALIDCAPS;
3451     }
3452
3453     hr = CreateSurface(This, &surface_desc2, &impl, outer_unknown, 2);
3454     if (FAILED(hr))
3455     {
3456         *surface = NULL;
3457         return hr;
3458     }
3459
3460     *surface = &impl->IDirectDrawSurface_iface;
3461     impl->ifaceToRelease = NULL;
3462
3463     return hr;
3464 }
3465
3466 static HRESULT WINAPI ddraw1_CreateSurface(IDirectDraw *iface,
3467         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3468 {
3469     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3470     IDirectDrawSurfaceImpl *impl;
3471     HRESULT hr;
3472     DDSURFACEDESC2 surface_desc2;
3473
3474     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3475             iface, surface_desc, surface, outer_unknown);
3476
3477     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3478     {
3479         WARN("Application supplied invalid surface descriptor\n");
3480         return DDERR_INVALIDPARAMS;
3481     }
3482
3483     /* Remove front buffer flag, this causes failure in v7, and its added to normal
3484      * primaries anyway. */
3485     surface_desc->ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER;
3486     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3487     hr = CreateSurface(This, &surface_desc2, &impl, outer_unknown, 1);
3488     if (FAILED(hr))
3489     {
3490         *surface = NULL;
3491         return hr;
3492     }
3493
3494     *surface = &impl->IDirectDrawSurface_iface;
3495     impl->ifaceToRelease = NULL;
3496
3497     return hr;
3498 }
3499
3500 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
3501 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
3502
3503 static BOOL
3504 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
3505                                     const DDPIXELFORMAT *provided)
3506 {
3507     /* Some flags must be present in both or neither for a match. */
3508     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
3509         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
3510         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
3511
3512     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3513         return FALSE;
3514
3515     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
3516         return FALSE;
3517
3518     if (requested->dwFlags & DDPF_FOURCC)
3519         if (requested->dwFourCC != provided->dwFourCC)
3520             return FALSE;
3521
3522     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
3523                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3524         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
3525             return FALSE;
3526
3527     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3528                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3529         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
3530             return FALSE;
3531
3532     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
3533         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
3534             return FALSE;
3535
3536     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
3537     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3538                               |DDPF_BUMPDUDV))
3539         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
3540             return FALSE;
3541
3542     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
3543         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
3544             return FALSE;
3545
3546     return TRUE;
3547 }
3548
3549 static BOOL ddraw_match_surface_desc(const DDSURFACEDESC2 *requested, const DDSURFACEDESC2 *provided)
3550 {
3551     struct compare_info
3552     {
3553         DWORD flag;
3554         ptrdiff_t offset;
3555         size_t size;
3556     };
3557
3558 #define CMP(FLAG, FIELD)                                \
3559         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
3560           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
3561
3562     static const struct compare_info compare[] =
3563     {
3564         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
3565         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
3566         CMP(CAPS, ddsCaps),
3567         CMP(CKDESTBLT, ddckCKDestBlt),
3568         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
3569         CMP(CKSRCBLT, ddckCKSrcBlt),
3570         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
3571         CMP(HEIGHT, dwHeight),
3572         CMP(LINEARSIZE, u1 /* dwLinearSize */),
3573         CMP(LPSURFACE, lpSurface),
3574         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
3575         CMP(PITCH, u1 /* lPitch */),
3576         /* PIXELFORMAT: manual */
3577         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
3578         CMP(TEXTURESTAGE, dwTextureStage),
3579         CMP(WIDTH, dwWidth),
3580         /* ZBUFFERBITDEPTH: "obsolete" */
3581     };
3582
3583 #undef CMP
3584
3585     unsigned int i;
3586
3587     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3588         return FALSE;
3589
3590     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
3591     {
3592         if (requested->dwFlags & compare[i].flag
3593             && memcmp((const char *)provided + compare[i].offset,
3594                       (const char *)requested + compare[i].offset,
3595                       compare[i].size) != 0)
3596             return FALSE;
3597     }
3598
3599     if (requested->dwFlags & DDSD_PIXELFORMAT)
3600     {
3601         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
3602                                                 &provided->u4.ddpfPixelFormat))
3603             return FALSE;
3604     }
3605
3606     return TRUE;
3607 }
3608
3609 #undef DDENUMSURFACES_SEARCHTYPE
3610 #undef DDENUMSURFACES_MATCHTYPE
3611
3612 struct surfacescallback2_context
3613 {
3614     LPDDENUMSURFACESCALLBACK2 func;
3615     void *context;
3616 };
3617
3618 struct surfacescallback_context
3619 {
3620     LPDDENUMSURFACESCALLBACK func;
3621     void *context;
3622 };
3623
3624 static HRESULT CALLBACK EnumSurfacesCallback2Thunk(IDirectDrawSurface7 *surface,
3625         DDSURFACEDESC2 *surface_desc, void *context)
3626 {
3627     IDirectDrawSurfaceImpl *surface_impl = impl_from_IDirectDrawSurface7(surface);
3628     struct surfacescallback2_context *cbcontext = context;
3629
3630     IDirectDrawSurface4_AddRef(&surface_impl->IDirectDrawSurface4_iface);
3631     IDirectDrawSurface7_Release(surface);
3632
3633     return cbcontext->func(&surface_impl->IDirectDrawSurface4_iface,
3634             surface_desc, cbcontext->context);
3635 }
3636
3637 static HRESULT CALLBACK EnumSurfacesCallbackThunk(IDirectDrawSurface7 *surface,
3638         DDSURFACEDESC2 *surface_desc, void *context)
3639 {
3640     IDirectDrawSurfaceImpl *surface_impl = impl_from_IDirectDrawSurface7(surface);
3641     struct surfacescallback_context *cbcontext = context;
3642
3643     IDirectDrawSurface_AddRef(&surface_impl->IDirectDrawSurface_iface);
3644     IDirectDrawSurface7_Release(surface);
3645
3646     return cbcontext->func(&surface_impl->IDirectDrawSurface_iface,
3647             (DDSURFACEDESC *)surface_desc, cbcontext->context);
3648 }
3649
3650 /*****************************************************************************
3651  * IDirectDraw7::EnumSurfaces
3652  *
3653  * Loops through all surfaces attached to this device and calls the
3654  * application callback. This can't be relayed to WineD3DDevice,
3655  * because some WineD3DSurfaces' parents are IParent objects
3656  *
3657  * Params:
3658  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
3659  *  DDSD: Description to filter for
3660  *  Context: Application-provided pointer, it's passed unmodified to the
3661  *           Callback function
3662  *  Callback: Address to call for each surface
3663  *
3664  * Returns:
3665  *  DDERR_INVALIDPARAMS if the callback is NULL
3666  *  DD_OK on success
3667  *
3668  *****************************************************************************/
3669 static HRESULT WINAPI ddraw7_EnumSurfaces(IDirectDraw7 *iface, DWORD Flags,
3670         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMSURFACESCALLBACK7 Callback)
3671 {
3672     /* The surface enumeration is handled by WineDDraw,
3673      * because it keeps track of all surfaces attached to
3674      * it. The filtering is done by our callback function,
3675      * because WineDDraw doesn't handle ddraw-like surface
3676      * caps structures
3677      */
3678     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3679     IDirectDrawSurfaceImpl *surf;
3680     BOOL all, nomatch;
3681     DDSURFACEDESC2 desc;
3682     struct list *entry, *entry2;
3683
3684     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3685             iface, Flags, DDSD, Context, Callback);
3686
3687     all = Flags & DDENUMSURFACES_ALL;
3688     nomatch = Flags & DDENUMSURFACES_NOMATCH;
3689
3690     EnterCriticalSection(&ddraw_cs);
3691
3692     if(!Callback)
3693     {
3694         LeaveCriticalSection(&ddraw_cs);
3695         return DDERR_INVALIDPARAMS;
3696     }
3697
3698     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
3699     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
3700     {
3701         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3702         if (all || (nomatch != ddraw_match_surface_desc(DDSD, &surf->surface_desc)))
3703         {
3704             TRACE("Enumerating surface %p.\n", surf);
3705             desc = surf->surface_desc;
3706             IDirectDrawSurface7_AddRef(&surf->IDirectDrawSurface7_iface);
3707             if (Callback(&surf->IDirectDrawSurface7_iface, &desc, Context) != DDENUMRET_OK)
3708             {
3709                 LeaveCriticalSection(&ddraw_cs);
3710                 return DD_OK;
3711             }
3712         }
3713     }
3714     LeaveCriticalSection(&ddraw_cs);
3715     return DD_OK;
3716 }
3717
3718 static HRESULT WINAPI ddraw4_EnumSurfaces(IDirectDraw4 *iface, DWORD flags,
3719         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMSURFACESCALLBACK2 callback)
3720 {
3721     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3722     struct surfacescallback2_context cbcontext;
3723
3724     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3725             iface, flags, surface_desc, context, callback);
3726
3727     cbcontext.func = callback;
3728     cbcontext.context = context;
3729
3730     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, surface_desc,
3731             &cbcontext, EnumSurfacesCallback2Thunk);
3732 }
3733
3734 static HRESULT WINAPI ddraw3_EnumSurfaces(IDirectDraw3 *iface, DWORD flags,
3735         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3736 {
3737     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3738     struct surfacescallback_context cbcontext;
3739     DDSURFACEDESC2 surface_desc2;
3740
3741     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3742             iface, flags, surface_desc, context, callback);
3743
3744     cbcontext.func = callback;
3745     cbcontext.context = context;
3746
3747     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3748     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, &surface_desc2,
3749             &cbcontext, EnumSurfacesCallbackThunk);
3750 }
3751
3752 static HRESULT WINAPI ddraw2_EnumSurfaces(IDirectDraw2 *iface, DWORD flags,
3753         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3754 {
3755     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3756     struct surfacescallback_context cbcontext;
3757     DDSURFACEDESC2 surface_desc2;
3758
3759     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3760             iface, flags, surface_desc, context, callback);
3761
3762     cbcontext.func = callback;
3763     cbcontext.context = context;
3764
3765     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3766     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, &surface_desc2,
3767             &cbcontext, EnumSurfacesCallbackThunk);
3768 }
3769
3770 static HRESULT WINAPI ddraw1_EnumSurfaces(IDirectDraw *iface, DWORD flags,
3771         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3772 {
3773     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3774     struct surfacescallback_context cbcontext;
3775     DDSURFACEDESC2 surface_desc2;
3776
3777     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3778             iface, flags, surface_desc, context, callback);
3779
3780     cbcontext.func = callback;
3781     cbcontext.context = context;
3782
3783     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3784     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, &surface_desc2,
3785             &cbcontext, EnumSurfacesCallbackThunk);
3786 }
3787
3788 /*****************************************************************************
3789  * DirectDrawCreateClipper (DDRAW.@)
3790  *
3791  * Creates a new IDirectDrawClipper object.
3792  *
3793  * Params:
3794  *  Clipper: Address to write the interface pointer to
3795  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3796  *            NULL
3797  *
3798  * Returns:
3799  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3800  *  E_OUTOFMEMORY if allocating the object failed
3801  *
3802  *****************************************************************************/
3803 HRESULT WINAPI
3804 DirectDrawCreateClipper(DWORD Flags,
3805                         LPDIRECTDRAWCLIPPER *Clipper,
3806                         IUnknown *UnkOuter)
3807 {
3808     IDirectDrawClipperImpl* object;
3809     HRESULT hr;
3810
3811     TRACE("flags %#x, clipper %p, outer_unknown %p.\n",
3812             Flags, Clipper, UnkOuter);
3813
3814     EnterCriticalSection(&ddraw_cs);
3815     if (UnkOuter != NULL)
3816     {
3817         LeaveCriticalSection(&ddraw_cs);
3818         return CLASS_E_NOAGGREGATION;
3819     }
3820
3821     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3822                      sizeof(IDirectDrawClipperImpl));
3823     if (object == NULL)
3824     {
3825         LeaveCriticalSection(&ddraw_cs);
3826         return E_OUTOFMEMORY;
3827     }
3828
3829     hr = ddraw_clipper_init(object);
3830     if (FAILED(hr))
3831     {
3832         WARN("Failed to initialize clipper, hr %#x.\n", hr);
3833         HeapFree(GetProcessHeap(), 0, object);
3834         LeaveCriticalSection(&ddraw_cs);
3835         return hr;
3836     }
3837
3838     TRACE("Created clipper %p.\n", object);
3839     *Clipper = &object->IDirectDrawClipper_iface;
3840     LeaveCriticalSection(&ddraw_cs);
3841     return DD_OK;
3842 }
3843
3844 /*****************************************************************************
3845  * IDirectDraw7::CreateClipper
3846  *
3847  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3848  *
3849  *****************************************************************************/
3850 static HRESULT WINAPI ddraw7_CreateClipper(IDirectDraw7 *iface, DWORD Flags,
3851         IDirectDrawClipper **Clipper, IUnknown *UnkOuter)
3852 {
3853     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3854             iface, Flags, Clipper, UnkOuter);
3855
3856     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3857 }
3858
3859 static HRESULT WINAPI ddraw4_CreateClipper(IDirectDraw4 *iface, DWORD flags,
3860         IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3861 {
3862     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3863
3864     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3865             iface, flags, clipper, outer_unknown);
3866
3867     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3868 }
3869
3870 static HRESULT WINAPI ddraw3_CreateClipper(IDirectDraw3 *iface, DWORD flags,
3871         IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3872 {
3873     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3874
3875     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3876             iface, flags, clipper, outer_unknown);
3877
3878     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3879 }
3880
3881 static HRESULT WINAPI ddraw2_CreateClipper(IDirectDraw2 *iface,
3882         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3883 {
3884     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3885
3886     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3887             iface, flags, clipper, outer_unknown);
3888
3889     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3890 }
3891
3892 static HRESULT WINAPI ddraw1_CreateClipper(IDirectDraw *iface,
3893         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3894 {
3895     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3896
3897     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3898             iface, flags, clipper, outer_unknown);
3899
3900     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3901 }
3902
3903 /*****************************************************************************
3904  * IDirectDraw7::CreatePalette
3905  *
3906  * Creates a new IDirectDrawPalette object
3907  *
3908  * Params:
3909  *  Flags: The flags for the new clipper
3910  *  ColorTable: Color table to assign to the new clipper
3911  *  Palette: Address to write the interface pointer to
3912  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3913  *            NULL
3914  *
3915  * Returns:
3916  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3917  *  E_OUTOFMEMORY if allocating the object failed
3918  *
3919  *****************************************************************************/
3920 static HRESULT WINAPI ddraw7_CreatePalette(IDirectDraw7 *iface, DWORD Flags,
3921         PALETTEENTRY *ColorTable, IDirectDrawPalette **Palette, IUnknown *pUnkOuter)
3922 {
3923     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3924     IDirectDrawPaletteImpl *object;
3925     HRESULT hr;
3926
3927     TRACE("iface %p, flags %#x, color_table %p, palette %p, outer_unknown %p.\n",
3928             iface, Flags, ColorTable, Palette, pUnkOuter);
3929
3930     EnterCriticalSection(&ddraw_cs);
3931     if(pUnkOuter != NULL)
3932     {
3933         WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
3934         LeaveCriticalSection(&ddraw_cs);
3935         return CLASS_E_NOAGGREGATION;
3936     }
3937
3938     /* The refcount test shows that a cooplevel is required for this */
3939     if(!This->cooperative_level)
3940     {
3941         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
3942         LeaveCriticalSection(&ddraw_cs);
3943         return DDERR_NOCOOPERATIVELEVELSET;
3944     }
3945
3946     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
3947     if(!object)
3948     {
3949         ERR("Out of memory when allocating memory for a palette implementation\n");
3950         LeaveCriticalSection(&ddraw_cs);
3951         return E_OUTOFMEMORY;
3952     }
3953
3954     hr = ddraw_palette_init(object, This, Flags, ColorTable);
3955     if (FAILED(hr))
3956     {
3957         WARN("Failed to initialize palette, hr %#x.\n", hr);
3958         HeapFree(GetProcessHeap(), 0, object);
3959         LeaveCriticalSection(&ddraw_cs);
3960         return hr;
3961     }
3962
3963     TRACE("Created palette %p.\n", object);
3964     *Palette = (IDirectDrawPalette *)object;
3965     LeaveCriticalSection(&ddraw_cs);
3966     return DD_OK;
3967 }
3968
3969 static HRESULT WINAPI ddraw4_CreatePalette(IDirectDraw4 *iface, DWORD flags, PALETTEENTRY *entries,
3970         IDirectDrawPalette **palette, IUnknown *outer_unknown)
3971 {
3972     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3973     HRESULT hr;
3974
3975     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3976             iface, flags, entries, palette, outer_unknown);
3977
3978     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3979     if (SUCCEEDED(hr) && *palette)
3980     {
3981         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3982         IDirectDraw7_Release(&This->IDirectDraw7_iface);
3983         IDirectDraw4_AddRef(iface);
3984         impl->ifaceToRelease = (IUnknown *)iface;
3985     }
3986     return hr;
3987 }
3988
3989 static HRESULT WINAPI ddraw3_CreatePalette(IDirectDraw3 *iface, DWORD flags,
3990         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3991 {
3992     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3993     HRESULT hr;
3994
3995     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3996             iface, flags, entries, palette, outer_unknown);
3997
3998     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3999     if (SUCCEEDED(hr) && *palette)
4000     {
4001         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4002         IDirectDraw7_Release(&This->IDirectDraw7_iface);
4003         IDirectDraw4_AddRef(iface);
4004         impl->ifaceToRelease = (IUnknown *)iface;
4005     }
4006
4007     return hr;
4008 }
4009
4010 static HRESULT WINAPI ddraw2_CreatePalette(IDirectDraw2 *iface, DWORD flags,
4011         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
4012 {
4013     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
4014     HRESULT hr;
4015
4016     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
4017             iface, flags, entries, palette, outer_unknown);
4018
4019     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4020     if (SUCCEEDED(hr) && *palette)
4021     {
4022         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4023         IDirectDraw7_Release(&This->IDirectDraw7_iface);
4024         impl->ifaceToRelease = NULL;
4025     }
4026
4027     return hr;
4028 }
4029
4030 static HRESULT WINAPI ddraw1_CreatePalette(IDirectDraw *iface, DWORD flags,
4031         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
4032 {
4033     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
4034     HRESULT hr;
4035
4036     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
4037             iface, flags, entries, palette, outer_unknown);
4038
4039     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4040     if (SUCCEEDED(hr) && *palette)
4041     {
4042         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4043         IDirectDraw7_Release(&This->IDirectDraw7_iface);
4044         impl->ifaceToRelease = NULL;
4045     }
4046
4047     return hr;
4048 }
4049
4050 /*****************************************************************************
4051  * IDirectDraw7::DuplicateSurface
4052  *
4053  * Duplicates a surface. The surface memory points to the same memory as
4054  * the original surface, and it's released when the last surface referencing
4055  * it is released. I guess that's beyond Wine's surface management right now
4056  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
4057  * test application to implement this)
4058  *
4059  * Params:
4060  *  Src: Address of the source surface
4061  *  Dest: Address to write the new surface pointer to
4062  *
4063  * Returns:
4064  *  See IDirectDraw7::CreateSurface
4065  *
4066  *****************************************************************************/
4067 static HRESULT WINAPI ddraw7_DuplicateSurface(IDirectDraw7 *iface,
4068         IDirectDrawSurface7 *Src, IDirectDrawSurface7 **Dest)
4069 {
4070     IDirectDrawSurfaceImpl *Surf = unsafe_impl_from_IDirectDrawSurface7(Src);
4071
4072     FIXME("iface %p, src %p, dst %p partial stub!\n", iface, Src, Dest);
4073
4074     /* For now, simply create a new, independent surface */
4075     return IDirectDraw7_CreateSurface(iface,
4076                                       &Surf->surface_desc,
4077                                       Dest,
4078                                       NULL);
4079 }
4080
4081 static HRESULT WINAPI ddraw4_DuplicateSurface(IDirectDraw4 *iface, IDirectDrawSurface4 *src,
4082         IDirectDrawSurface4 **dst)
4083 {
4084     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
4085     IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface4(src);
4086     IDirectDrawSurface7 *dst7;
4087     IDirectDrawSurfaceImpl *dst_impl;
4088     HRESULT hr;
4089
4090     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4091     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
4092             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4093     if (FAILED(hr))
4094     {
4095         *dst = NULL;
4096         return hr;
4097     }
4098     dst_impl = impl_from_IDirectDrawSurface7(dst7);
4099     *dst = &dst_impl->IDirectDrawSurface4_iface;
4100     IDirectDrawSurface4_AddRef(*dst);
4101     IDirectDrawSurface7_Release(dst7);
4102
4103     return hr;
4104 }
4105
4106 static HRESULT WINAPI ddraw3_DuplicateSurface(IDirectDraw3 *iface, IDirectDrawSurface *src,
4107         IDirectDrawSurface **dst)
4108 {
4109     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
4110     IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface(src);
4111     IDirectDrawSurface7 *dst7;
4112     IDirectDrawSurfaceImpl *dst_impl;
4113     HRESULT hr;
4114
4115     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4116     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
4117             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4118     if (FAILED(hr))
4119         return hr;
4120     dst_impl = impl_from_IDirectDrawSurface7(dst7);
4121     *dst = &dst_impl->IDirectDrawSurface_iface;
4122     IDirectDrawSurface_AddRef(*dst);
4123     IDirectDrawSurface7_Release(dst7);
4124
4125     return hr;
4126 }
4127
4128 static HRESULT WINAPI ddraw2_DuplicateSurface(IDirectDraw2 *iface,
4129         IDirectDrawSurface *src, IDirectDrawSurface **dst)
4130 {
4131     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
4132     IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface(src);
4133     IDirectDrawSurface7 *dst7;
4134     IDirectDrawSurfaceImpl *dst_impl;
4135     HRESULT hr;
4136
4137     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4138     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
4139             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4140     if (FAILED(hr))
4141         return hr;
4142     dst_impl = impl_from_IDirectDrawSurface7(dst7);
4143     *dst = &dst_impl->IDirectDrawSurface_iface;
4144     IDirectDrawSurface_AddRef(*dst);
4145     IDirectDrawSurface7_Release(dst7);
4146
4147     return hr;
4148 }
4149
4150 static HRESULT WINAPI ddraw1_DuplicateSurface(IDirectDraw *iface, IDirectDrawSurface *src,
4151         IDirectDrawSurface **dst)
4152 {
4153     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
4154     IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface(src);
4155     IDirectDrawSurface7 *dst7;
4156     IDirectDrawSurfaceImpl *dst_impl;
4157     HRESULT hr;
4158
4159     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4160     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
4161             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4162     if (FAILED(hr))
4163         return hr;
4164     dst_impl = impl_from_IDirectDrawSurface7(dst7);
4165     *dst = &dst_impl->IDirectDrawSurface_iface;
4166     IDirectDrawSurface_AddRef(*dst);
4167     IDirectDrawSurface7_Release(dst7);
4168
4169     return hr;
4170 }
4171
4172 /*****************************************************************************
4173  * IDirect3D7::EnumDevices
4174  *
4175  * The EnumDevices method for IDirect3D7. It enumerates all supported
4176  * D3D7 devices. Currently the T&L, HAL and RGB devices are enumerated.
4177  *
4178  * Params:
4179  *  callback: Function to call for each enumerated device
4180  *  context: Pointer to pass back to the app
4181  *
4182  * Returns:
4183  *  D3D_OK, or the return value of the GetCaps call
4184  *
4185  *****************************************************************************/
4186 static HRESULT WINAPI d3d7_EnumDevices(IDirect3D7 *iface, LPD3DENUMDEVICESCALLBACK7 callback, void *context)
4187 {
4188     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4189     D3DDEVICEDESC7 device_desc7;
4190     D3DDEVICEDESC device_desc1;
4191     HRESULT hr;
4192     size_t i;
4193
4194     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4195
4196     if (!callback)
4197         return DDERR_INVALIDPARAMS;
4198
4199     EnterCriticalSection(&ddraw_cs);
4200
4201     hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
4202     if (hr != D3D_OK)
4203     {
4204         LeaveCriticalSection(&ddraw_cs);
4205         return hr;
4206     }
4207
4208     for (i = 0; i < sizeof(device_list7)/sizeof(device_list7[0]); i++)
4209     {
4210         HRESULT ret;
4211
4212         device_desc7.deviceGUID = *device_list7[i].device_guid;
4213         ret = callback(device_list7[i].interface_name, device_list7[i].device_name, &device_desc7, context);
4214         if (ret != DDENUMRET_OK)
4215         {
4216             TRACE("Application cancelled the enumeration.\n");
4217             LeaveCriticalSection(&ddraw_cs);
4218             return D3D_OK;
4219         }
4220     }
4221
4222     TRACE("End of enumeration.\n");
4223
4224     LeaveCriticalSection(&ddraw_cs);
4225
4226     return D3D_OK;
4227 }
4228
4229 /*****************************************************************************
4230  * IDirect3D3::EnumDevices
4231  *
4232  * Enumerates all supported Direct3DDevice interfaces. This is the
4233  * implementation for Direct3D 1 to Direc3D 3, Version 7 has its own.
4234  *
4235  * Version 1, 2 and 3
4236  *
4237  * Params:
4238  *  callback: Application-provided routine to call for each enumerated device
4239  *  Context: Pointer to pass to the callback
4240  *
4241  * Returns:
4242  *  D3D_OK on success,
4243  *  The result of IDirect3DImpl_GetCaps if it failed
4244  *
4245  *****************************************************************************/
4246 static HRESULT WINAPI d3d3_EnumDevices(IDirect3D3 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4247 {
4248     static CHAR wined3d_description[] = "Wine D3DDevice using WineD3D and OpenGL";
4249
4250     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4251     D3DDEVICEDESC device_desc1, hal_desc, hel_desc;
4252     D3DDEVICEDESC7 device_desc7;
4253     HRESULT hr;
4254
4255     /* Some games (Motoracer 2 demo) have the bad idea to modify the device
4256      * name string. Let's put the string in a sufficiently sized array in
4257      * writable memory. */
4258     char device_name[50];
4259     strcpy(device_name,"Direct3D HEL");
4260
4261     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4262
4263     if (!callback)
4264         return DDERR_INVALIDPARAMS;
4265
4266     EnterCriticalSection(&ddraw_cs);
4267
4268     hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
4269     if (hr != D3D_OK)
4270     {
4271         LeaveCriticalSection(&ddraw_cs);
4272         return hr;
4273     }
4274
4275     /* Do I have to enumerate the reference id? Note from old d3d7:
4276      * "It seems that enumerating the reference IID on Direct3D 1 games
4277      * (AvP / Motoracer2) breaks them". So do not enumerate this iid in V1
4278      *
4279      * There's a registry key HKLM\Software\Microsoft\Direct3D\Drivers,
4280      * EnumReference which enables / disables enumerating the reference
4281      * rasterizer. It's a DWORD, 0 means disabled, 2 means enabled. The
4282      * enablerefrast.reg and disablerefrast.reg files in the DirectX 7.0 sdk
4283      * demo directory suggest this.
4284      *
4285      * Some games(GTA 2) seem to use the second enumerated device, so I have
4286      * to enumerate at least 2 devices. So enumerate the reference device to
4287      * have 2 devices.
4288      *
4289      * Other games (Rollcage) tell emulation and hal device apart by certain
4290      * flags. Rollcage expects D3DPTEXTURECAPS_POW2 to be set (yeah, it is a
4291      * limitation flag), and it refuses all devices that have the perspective
4292      * flag set. This way it refuses the emulation device, and HAL devices
4293      * never have POW2 unset in d3d7 on windows. */
4294     if (This->d3dversion != 1)
4295     {
4296         static CHAR reference_description[] = "RGB Direct3D emulation";
4297
4298         TRACE("Enumerating WineD3D D3DDevice interface.\n");
4299         hal_desc = device_desc1;
4300         hel_desc = device_desc1;
4301         /* The rgb device has the pow2 flag set in the hel caps, but not in the hal caps. */
4302         hal_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4303                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4304         hal_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4305                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4306         hr = callback((GUID *)&IID_IDirect3DRGBDevice, reference_description,
4307                 device_name, &hal_desc, &hel_desc, context);
4308         if (hr != D3DENUMRET_OK)
4309         {
4310             TRACE("Application cancelled the enumeration.\n");
4311             LeaveCriticalSection(&ddraw_cs);
4312             return D3D_OK;
4313         }
4314     }
4315
4316     strcpy(device_name,"Direct3D HAL");
4317
4318     TRACE("Enumerating HAL Direct3D device.\n");
4319     hal_desc = device_desc1;
4320     hel_desc = device_desc1;
4321     /* The hal device does not have the pow2 flag set in hel, but in hal. */
4322     hel_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4323             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4324     hel_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4325             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4326     hr = callback((GUID *)&IID_IDirect3DHALDevice, wined3d_description,
4327             device_name, &hal_desc, &hel_desc, context);
4328     if (hr != D3DENUMRET_OK)
4329     {
4330         TRACE("Application cancelled the enumeration.\n");
4331         LeaveCriticalSection(&ddraw_cs);
4332         return D3D_OK;
4333     }
4334
4335     TRACE("End of enumeration.\n");
4336
4337     LeaveCriticalSection(&ddraw_cs);
4338     return D3D_OK;
4339 }
4340
4341 static HRESULT WINAPI d3d2_EnumDevices(IDirect3D2 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4342 {
4343     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4344
4345     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4346
4347     return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4348 }
4349
4350 static HRESULT WINAPI d3d1_EnumDevices(IDirect3D *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4351 {
4352     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4353
4354     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4355
4356     return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4357 }
4358
4359 /*****************************************************************************
4360  * IDirect3D3::CreateLight
4361  *
4362  * Creates an IDirect3DLight interface. This interface is used in
4363  * Direct3D3 or earlier for lighting. In Direct3D7 it has been replaced
4364  * by the DIRECT3DLIGHT7 structure. Wine's Direct3DLight implementation
4365  * uses the IDirect3DDevice7 interface with D3D7 lights.
4366  *
4367  * Version 1, 2 and 3
4368  *
4369  * Params:
4370  *  light: Address to store the new interface pointer
4371  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4372  *                 Must be NULL
4373  *
4374  * Returns:
4375  *  D3D_OK on success
4376  *  DDERR_OUTOFMEMORY if memory allocation failed
4377  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4378  *
4379  *****************************************************************************/
4380 static HRESULT WINAPI d3d3_CreateLight(IDirect3D3 *iface, IDirect3DLight **light,
4381         IUnknown *outer_unknown)
4382 {
4383     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4384     IDirect3DLightImpl *object;
4385
4386     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4387
4388     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4389
4390     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4391     if (!object)
4392     {
4393         ERR("Failed to allocate light memory.\n");
4394         return DDERR_OUTOFMEMORY;
4395     }
4396
4397     d3d_light_init(object, This);
4398
4399     TRACE("Created light %p.\n", object);
4400     *light = &object->IDirect3DLight_iface;
4401
4402     return D3D_OK;
4403 }
4404
4405 static HRESULT WINAPI d3d2_CreateLight(IDirect3D2 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4406 {
4407     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4408
4409     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4410
4411     return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4412 }
4413
4414 static HRESULT WINAPI d3d1_CreateLight(IDirect3D *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4415 {
4416     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4417
4418     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4419
4420     return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4421 }
4422
4423 /*****************************************************************************
4424  * IDirect3D3::CreateMaterial
4425  *
4426  * Creates an IDirect3DMaterial interface. This interface is used by Direct3D3
4427  * and older versions. The IDirect3DMaterial implementation wraps its
4428  * functionality to IDirect3DDevice7::SetMaterial and friends.
4429  *
4430  * Version 1, 2 and 3
4431  *
4432  * Params:
4433  *  material: Address to store the new interface's pointer to
4434  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4435  *                 Must be NULL
4436  *
4437  * Returns:
4438  *  D3D_OK on success
4439  *  DDERR_OUTOFMEMORY if memory allocation failed
4440  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4441  *
4442  *****************************************************************************/
4443 static HRESULT WINAPI d3d3_CreateMaterial(IDirect3D3 *iface, IDirect3DMaterial3 **material,
4444         IUnknown *outer_unknown)
4445 {
4446     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4447     IDirect3DMaterialImpl *object;
4448
4449     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4450
4451     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4452
4453     object = d3d_material_create(This);
4454     if (!object)
4455     {
4456         ERR("Failed to allocate material memory.\n");
4457         return DDERR_OUTOFMEMORY;
4458     }
4459
4460     TRACE("Created material %p.\n", object);
4461     *material = &object->IDirect3DMaterial3_iface;
4462
4463     return D3D_OK;
4464 }
4465
4466 static HRESULT WINAPI d3d2_CreateMaterial(IDirect3D2 *iface, IDirect3DMaterial2 **material,
4467         IUnknown *outer_unknown)
4468 {
4469     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4470     IDirect3DMaterialImpl *object;
4471
4472     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4473
4474     object = d3d_material_create(This);
4475     if (!object)
4476     {
4477         ERR("Failed to allocate material memory.\n");
4478         return DDERR_OUTOFMEMORY;
4479     }
4480
4481     TRACE("Created material %p.\n", object);
4482     *material = &object->IDirect3DMaterial2_iface;
4483
4484     return D3D_OK;
4485 }
4486
4487 static HRESULT WINAPI d3d1_CreateMaterial(IDirect3D *iface, IDirect3DMaterial **material,
4488         IUnknown *outer_unknown)
4489 {
4490     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4491     IDirect3DMaterialImpl *object;
4492
4493     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4494
4495     object = d3d_material_create(This);
4496     if (!object)
4497     {
4498         ERR("Failed to allocate material memory.\n");
4499         return DDERR_OUTOFMEMORY;
4500     }
4501
4502     TRACE("Created material %p.\n", object);
4503     *material = &object->IDirect3DMaterial_iface;
4504
4505     return D3D_OK;
4506 }
4507
4508 /*****************************************************************************
4509  * IDirect3D3::CreateViewport
4510  *
4511  * Creates an IDirect3DViewport interface. This interface is used
4512  * by Direct3D and earlier versions for Viewport management. In Direct3D7
4513  * it has been replaced by a viewport structure and
4514  * IDirect3DDevice7::*Viewport. Wine's IDirect3DViewport implementation
4515  * uses the IDirect3DDevice7 methods for its functionality
4516  *
4517  * Params:
4518  *  Viewport: Address to store the new interface pointer
4519  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4520  *                 Must be NULL
4521  *
4522  * Returns:
4523  *  D3D_OK on success
4524  *  DDERR_OUTOFMEMORY if memory allocation failed
4525  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4526  *
4527  *****************************************************************************/
4528 static HRESULT WINAPI d3d3_CreateViewport(IDirect3D3 *iface, IDirect3DViewport3 **viewport,
4529         IUnknown *outer_unknown)
4530 {
4531     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4532     IDirect3DViewportImpl *object;
4533
4534     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4535
4536     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4537
4538     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4539     if (!object)
4540     {
4541         ERR("Failed to allocate viewport memory.\n");
4542         return DDERR_OUTOFMEMORY;
4543     }
4544
4545     d3d_viewport_init(object, This);
4546
4547     TRACE("Created viewport %p.\n", object);
4548     *viewport = (IDirect3DViewport3 *)object;
4549
4550     return D3D_OK;
4551 }
4552
4553 static HRESULT WINAPI d3d2_CreateViewport(IDirect3D2 *iface, IDirect3DViewport2 **viewport, IUnknown *outer_unknown)
4554 {
4555     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4556
4557     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4558
4559     return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4560             outer_unknown);
4561 }
4562
4563 static HRESULT WINAPI d3d1_CreateViewport(IDirect3D *iface, IDirect3DViewport **viewport, IUnknown *outer_unknown)
4564 {
4565     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4566
4567     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4568
4569     return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4570             outer_unknown);
4571 }
4572
4573 /*****************************************************************************
4574  * IDirect3D3::FindDevice
4575  *
4576  * This method finds a device with the requested properties and returns a
4577  * device description
4578  *
4579  * Verion 1, 2 and 3
4580  * Params:
4581  *  fds: Describes the requested device characteristics
4582  *  fdr: Returns the device description
4583  *
4584  * Returns:
4585  *  D3D_OK on success
4586  *  DDERR_INVALIDPARAMS if no device was found
4587  *
4588  *****************************************************************************/
4589 static HRESULT WINAPI d3d3_FindDevice(IDirect3D3 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4590 {
4591     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4592     D3DDEVICEDESC7 desc7;
4593     D3DDEVICEDESC desc1;
4594     HRESULT hr;
4595
4596     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4597
4598     if (!fds || !fdr) return DDERR_INVALIDPARAMS;
4599
4600     if (fds->dwSize != sizeof(D3DFINDDEVICESEARCH)
4601             || fdr->dwSize != sizeof(D3DFINDDEVICERESULT))
4602         return DDERR_INVALIDPARAMS;
4603
4604     if ((fds->dwFlags & D3DFDS_COLORMODEL)
4605             && fds->dcmColorModel != D3DCOLOR_RGB)
4606     {
4607         WARN("Trying to request a non-RGB D3D color model. Not supported.\n");
4608         return DDERR_INVALIDPARAMS; /* No real idea what to return here :-) */
4609     }
4610
4611     if (fds->dwFlags & D3DFDS_GUID)
4612     {
4613         TRACE("Trying to match guid %s.\n", debugstr_guid(&(fds->guid)));
4614         if (!IsEqualGUID(&IID_D3DDEVICE_WineD3D, &fds->guid)
4615                 && !IsEqualGUID(&IID_IDirect3DHALDevice, &fds->guid)
4616                 && !IsEqualGUID(&IID_IDirect3DRGBDevice, &fds->guid))
4617         {
4618             WARN("No match for this GUID.\n");
4619             return DDERR_NOTFOUND;
4620         }
4621     }
4622
4623     /* Get the caps */
4624     hr = IDirect3DImpl_GetCaps(This->wineD3D, &desc1, &desc7);
4625     if (hr != D3D_OK) return hr;
4626
4627     /* Now return our own GUID */
4628     fdr->guid = IID_D3DDEVICE_WineD3D;
4629     fdr->ddHwDesc = desc1;
4630     fdr->ddSwDesc = desc1;
4631
4632     TRACE("Returning Wine's wined3d device with (undumped) capabilities.\n");
4633
4634     return D3D_OK;
4635 }
4636
4637 static HRESULT WINAPI d3d2_FindDevice(IDirect3D2 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4638 {
4639     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4640
4641     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4642
4643     return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4644 }
4645
4646 static HRESULT WINAPI d3d1_FindDevice(IDirect3D *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4647 {
4648     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4649
4650     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4651
4652     return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4653 }
4654
4655 /*****************************************************************************
4656  * IDirect3D7::CreateDevice
4657  *
4658  * Creates an IDirect3DDevice7 interface.
4659  *
4660  * Version 2, 3 and 7. IDirect3DDevice 1 interfaces are interfaces to
4661  * DirectDraw surfaces and are created with
4662  * IDirectDrawSurface::QueryInterface. This method uses CreateDevice to
4663  * create the device object and QueryInterfaces for IDirect3DDevice
4664  *
4665  * Params:
4666  *  refiid: IID of the device to create
4667  *  Surface: Initial rendertarget
4668  *  Device: Address to return the interface pointer
4669  *
4670  * Returns:
4671  *  D3D_OK on success
4672  *  DDERR_OUTOFMEMORY if memory allocation failed
4673  *  DDERR_INVALIDPARAMS if a device exists already
4674  *
4675  *****************************************************************************/
4676 static HRESULT WINAPI d3d7_CreateDevice(IDirect3D7 *iface, REFCLSID riid,
4677         IDirectDrawSurface7 *surface, IDirect3DDevice7 **device)
4678 {
4679     IDirectDrawSurfaceImpl *target = unsafe_impl_from_IDirectDrawSurface7(surface);
4680     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4681     IDirect3DDeviceImpl *object;
4682     HRESULT hr;
4683
4684     TRACE("iface %p, riid %s, surface %p, device %p.\n", iface, debugstr_guid(riid), surface, device);
4685
4686     EnterCriticalSection(&ddraw_cs);
4687     *device = NULL;
4688
4689     /* Fail device creation if non-opengl surfaces are used. */
4690     if (DefaultSurfaceType != SURFACE_OPENGL)
4691     {
4692         ERR("The application wants to create a Direct3D device, but non-opengl surfaces are set in the registry.\n");
4693         ERR("Please set the surface implementation to opengl or autodetection to allow 3D rendering.\n");
4694
4695         /* We only hit this path if a default surface is set in the registry. Incorrect autodetection
4696          * is caught in CreateSurface or QueryInterface. */
4697         LeaveCriticalSection(&ddraw_cs);
4698         return DDERR_NO3D;
4699     }
4700
4701     if (This->d3ddevice)
4702     {
4703         FIXME("Only one Direct3D device per DirectDraw object supported.\n");
4704         LeaveCriticalSection(&ddraw_cs);
4705         return DDERR_INVALIDPARAMS;
4706     }
4707
4708     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4709     if (!object)
4710     {
4711         ERR("Failed to allocate device memory.\n");
4712         LeaveCriticalSection(&ddraw_cs);
4713         return DDERR_OUTOFMEMORY;
4714     }
4715
4716     hr = d3d_device_init(object, This, target);
4717     if (FAILED(hr))
4718     {
4719         WARN("Failed to initialize device, hr %#x.\n", hr);
4720         HeapFree(GetProcessHeap(), 0, object);
4721         LeaveCriticalSection(&ddraw_cs);
4722         return hr;
4723     }
4724
4725     TRACE("Created device %p.\n", object);
4726     *device = (IDirect3DDevice7 *)object;
4727
4728     LeaveCriticalSection(&ddraw_cs);
4729     return D3D_OK;
4730 }
4731
4732 static HRESULT WINAPI d3d3_CreateDevice(IDirect3D3 *iface, REFCLSID riid,
4733         IDirectDrawSurface4 *surface, IDirect3DDevice3 **device, IUnknown *outer_unknown)
4734 {
4735     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4736     IDirectDrawSurfaceImpl *surface_impl = unsafe_impl_from_IDirectDrawSurface4(surface);
4737     HRESULT hr;
4738
4739     TRACE("iface %p, riid %s, surface %p, device %p, outer_unknown %p.\n",
4740             iface, debugstr_guid(riid), surface, device, outer_unknown);
4741
4742     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4743
4744     hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid,
4745             surface_impl ? &surface_impl->IDirectDrawSurface7_iface : NULL,
4746             (IDirect3DDevice7 **)device);
4747     if (*device) *device = (IDirect3DDevice3 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice3_vtbl;
4748
4749     return hr;
4750 }
4751
4752 static HRESULT WINAPI d3d2_CreateDevice(IDirect3D2 *iface, REFCLSID riid,
4753         IDirectDrawSurface *surface, IDirect3DDevice2 **device)
4754 {
4755     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4756     IDirectDrawSurfaceImpl *surface_impl = unsafe_impl_from_IDirectDrawSurface(surface);
4757     HRESULT hr;
4758
4759     TRACE("iface %p, riid %s, surface %p, device %p.\n",
4760             iface, debugstr_guid(riid), surface, device);
4761
4762     hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid,
4763             surface_impl ? &surface_impl->IDirectDrawSurface7_iface : NULL,
4764             (IDirect3DDevice7 **)device);
4765     if (*device) *device = (IDirect3DDevice2 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice2_vtbl;
4766
4767     return hr;
4768 }
4769
4770 /*****************************************************************************
4771  * IDirect3D7::CreateVertexBuffer
4772  *
4773  * Creates a new vertex buffer object and returns a IDirect3DVertexBuffer7
4774  * interface.
4775  *
4776  * Version 3 and 7
4777  *
4778  * Params:
4779  *  desc: Requested Vertex buffer properties
4780  *  vertex_buffer: Address to return the interface pointer at
4781  *  flags: Some flags, should be 0
4782  *
4783  * Returns
4784  *  D3D_OK on success
4785  *  DDERR_OUTOFMEMORY if memory allocation failed
4786  *  The return value of IWineD3DDevice::CreateVertexBuffer if this call fails
4787  *  DDERR_INVALIDPARAMS if desc or vertex_buffer are NULL
4788  *
4789  *****************************************************************************/
4790 static HRESULT WINAPI d3d7_CreateVertexBuffer(IDirect3D7 *iface, D3DVERTEXBUFFERDESC *desc,
4791         IDirect3DVertexBuffer7 **vertex_buffer, DWORD flags)
4792 {
4793     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4794     IDirect3DVertexBufferImpl *object;
4795     HRESULT hr;
4796
4797     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x.\n",
4798             iface, desc, vertex_buffer, flags);
4799
4800     if (!vertex_buffer || !desc) return DDERR_INVALIDPARAMS;
4801
4802     hr = d3d_vertex_buffer_create(&object, This, desc);
4803     if (hr == D3D_OK)
4804     {
4805         TRACE("Created vertex buffer %p.\n", object);
4806         *vertex_buffer = &object->IDirect3DVertexBuffer7_iface;
4807     }
4808     else
4809         WARN("Failed to create vertex buffer, hr %#x.\n", hr);
4810
4811     return hr;
4812 }
4813
4814 static HRESULT WINAPI d3d3_CreateVertexBuffer(IDirect3D3 *iface, D3DVERTEXBUFFERDESC *desc,
4815         IDirect3DVertexBuffer **vertex_buffer, DWORD flags, IUnknown *outer_unknown)
4816 {
4817     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4818     IDirect3DVertexBufferImpl *object;
4819     HRESULT hr;
4820
4821     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x, outer_unknown %p.\n",
4822             iface, desc, vertex_buffer, flags, outer_unknown);
4823
4824     if (outer_unknown)
4825         return CLASS_E_NOAGGREGATION;
4826     if (!vertex_buffer || !desc)
4827         return DDERR_INVALIDPARAMS;
4828
4829     hr = d3d_vertex_buffer_create(&object, This, desc);
4830     if (hr == D3D_OK)
4831     {
4832         TRACE("Created vertex buffer %p.\n", object);
4833         *vertex_buffer = &object->IDirect3DVertexBuffer_iface;
4834     }
4835     else
4836         WARN("Failed to create vertex buffer, hr %#x.\n", hr);
4837
4838     return hr;
4839 }
4840
4841 /*****************************************************************************
4842  * IDirect3D7::EnumZBufferFormats
4843  *
4844  * Enumerates all supported Z buffer pixel formats
4845  *
4846  * Version 3 and 7
4847  *
4848  * Params:
4849  *  device_iid:
4850  *  callback: callback to call for each pixel format
4851  *  context: Pointer to pass back to the callback
4852  *
4853  * Returns:
4854  *  D3D_OK on success
4855  *  DDERR_INVALIDPARAMS if callback is NULL
4856  *  For details, see IWineD3DDevice::EnumZBufferFormats
4857  *
4858  *****************************************************************************/
4859 static HRESULT WINAPI d3d7_EnumZBufferFormats(IDirect3D7 *iface, REFCLSID device_iid,
4860         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4861 {
4862     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4863     WINED3DDISPLAYMODE d3ddm;
4864     WINED3DDEVTYPE type;
4865     unsigned int i;
4866     HRESULT hr;
4867
4868     /* Order matters. Specifically, BattleZone II (full version) expects the
4869      * 16-bit depth formats to be listed before the 24 and 32 ones. */
4870     static const enum wined3d_format_id formats[] =
4871     {
4872         WINED3DFMT_S1_UINT_D15_UNORM,
4873         WINED3DFMT_D16_UNORM,
4874         WINED3DFMT_X8D24_UNORM,
4875         WINED3DFMT_S4X4_UINT_D24_UNORM,
4876         WINED3DFMT_D24_UNORM_S8_UINT,
4877         WINED3DFMT_D32_UNORM,
4878     };
4879
4880     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4881             iface, debugstr_guid(device_iid), callback, context);
4882
4883     if (!callback) return DDERR_INVALIDPARAMS;
4884
4885     if (IsEqualGUID(device_iid, &IID_IDirect3DHALDevice)
4886             || IsEqualGUID(device_iid, &IID_IDirect3DTnLHalDevice)
4887             || IsEqualGUID(device_iid, &IID_D3DDEVICE_WineD3D))
4888     {
4889         TRACE("Asked for HAL device.\n");
4890         type = WINED3DDEVTYPE_HAL;
4891     }
4892     else if (IsEqualGUID(device_iid, &IID_IDirect3DRGBDevice)
4893             || IsEqualGUID(device_iid, &IID_IDirect3DMMXDevice))
4894     {
4895         TRACE("Asked for SW device.\n");
4896         type = WINED3DDEVTYPE_SW;
4897     }
4898     else if (IsEqualGUID(device_iid, &IID_IDirect3DRefDevice))
4899     {
4900         TRACE("Asked for REF device.\n");
4901         type = WINED3DDEVTYPE_REF;
4902     }
4903     else if (IsEqualGUID(device_iid, &IID_IDirect3DNullDevice))
4904     {
4905         TRACE("Asked for NULLREF device.\n");
4906         type = WINED3DDEVTYPE_NULLREF;
4907     }
4908     else
4909     {
4910         FIXME("Unexpected device GUID %s.\n", debugstr_guid(device_iid));
4911         type = WINED3DDEVTYPE_HAL;
4912     }
4913
4914     EnterCriticalSection(&ddraw_cs);
4915     /* We need an adapter format from somewhere to please wined3d and WGL.
4916      * Use the current display mode. So far all cards offer the same depth
4917      * stencil format for all modes, but if some do not and applications do
4918      * not like that we'll have to find some workaround, like iterating over
4919      * all imaginable formats and collecting all the depth stencil formats we
4920      * can get. */
4921     hr = wined3d_device_get_display_mode(This->wined3d_device, 0, &d3ddm);
4922
4923     for (i = 0; i < (sizeof(formats) / sizeof(*formats)); ++i)
4924     {
4925         hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, type, d3ddm.Format,
4926                 WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, formats[i], SURFACE_OPENGL);
4927         if (SUCCEEDED(hr))
4928         {
4929             DDPIXELFORMAT pformat;
4930
4931             memset(&pformat, 0, sizeof(pformat));
4932             pformat.dwSize = sizeof(pformat);
4933             PixelFormat_WineD3DtoDD(&pformat, formats[i]);
4934
4935             TRACE("Enumerating wined3d format %#x.\n", formats[i]);
4936             hr = callback(&pformat, context);
4937             if (hr != DDENUMRET_OK)
4938             {
4939                 TRACE("Format enumeration cancelled by application.\n");
4940                 LeaveCriticalSection(&ddraw_cs);
4941                 return D3D_OK;
4942             }
4943         }
4944     }
4945
4946     /* Historically some windows drivers used dwZBufferBitDepth=24 for WINED3DFMT_X8D24_UNORM,
4947      * while others used dwZBufferBitDepth=32. In either case the pitch matches a 32 bits per
4948      * pixel format, so we use dwZBufferBitDepth=32. Some games expect 24. Windows Vista and
4949      * newer enumerate both versions, so we do the same(bug 22434) */
4950     hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, type, d3ddm.Format,
4951             WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, WINED3DFMT_X8D24_UNORM, SURFACE_OPENGL);
4952     if (SUCCEEDED(hr))
4953     {
4954         DDPIXELFORMAT x8d24 =
4955         {
4956             sizeof(x8d24), DDPF_ZBUFFER, 0,
4957             {24}, {0x00000000}, {0x00ffffff}, {0x00000000}
4958         };
4959         TRACE("Enumerating WINED3DFMT_X8D24_UNORM, dwZBufferBitDepth=24 version\n");
4960         callback(&x8d24, context);
4961     }
4962
4963     TRACE("End of enumeration.\n");
4964
4965     LeaveCriticalSection(&ddraw_cs);
4966     return D3D_OK;
4967 }
4968
4969 static HRESULT WINAPI d3d3_EnumZBufferFormats(IDirect3D3 *iface, REFCLSID device_iid,
4970         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4971 {
4972     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4973
4974     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4975             iface, debugstr_guid(device_iid), callback, context);
4976
4977     return d3d7_EnumZBufferFormats(&This->IDirect3D7_iface, device_iid, callback, context);
4978 }
4979
4980 /*****************************************************************************
4981  * IDirect3D7::EvictManagedTextures
4982  *
4983  * Removes all managed textures (=surfaces with DDSCAPS2_TEXTUREMANAGE or
4984  * DDSCAPS2_D3DTEXTUREMANAGE caps) to be removed from video memory.
4985  *
4986  * Version 3 and 7
4987  *
4988  * Returns:
4989  *  D3D_OK, because it's a stub
4990  *
4991  *****************************************************************************/
4992 static HRESULT WINAPI d3d7_EvictManagedTextures(IDirect3D7 *iface)
4993 {
4994     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4995
4996     TRACE("iface %p!\n", iface);
4997
4998     EnterCriticalSection(&ddraw_cs);
4999     if (This->d3d_initialized)
5000         wined3d_device_evict_managed_resources(This->wined3d_device);
5001     LeaveCriticalSection(&ddraw_cs);
5002
5003     return D3D_OK;
5004 }
5005
5006 static HRESULT WINAPI d3d3_EvictManagedTextures(IDirect3D3 *iface)
5007 {
5008     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
5009
5010     TRACE("iface %p.\n", iface);
5011
5012     return d3d7_EvictManagedTextures(&This->IDirect3D7_iface);
5013 }
5014
5015 /*****************************************************************************
5016  * IDirect3DImpl_GetCaps
5017  *
5018  * This function retrieves the device caps from wined3d
5019  * and converts it into a D3D7 and D3D - D3D3 structure
5020  * This is a helper function called from various places in ddraw
5021  *
5022  * Params:
5023  *  wined3d: The interface to get the caps from
5024  *  desc1: Old D3D <3 structure to fill (needed)
5025  *  desc7: D3D7 device desc structure to fill (needed)
5026  *
5027  * Returns
5028  *  D3D_OK on success, or the return value of IWineD3D::GetCaps
5029  *
5030  *****************************************************************************/
5031 HRESULT IDirect3DImpl_GetCaps(const struct wined3d *wined3d, D3DDEVICEDESC *desc1, D3DDEVICEDESC7 *desc7)
5032 {
5033     WINED3DCAPS wined3d_caps;
5034     HRESULT hr;
5035
5036     TRACE("wined3d %p, desc1 %p, desc7 %p.\n", wined3d, desc1, desc7);
5037
5038     memset(&wined3d_caps, 0, sizeof(wined3d_caps));
5039
5040     EnterCriticalSection(&ddraw_cs);
5041     hr = wined3d_get_device_caps(wined3d, 0, WINED3DDEVTYPE_HAL, &wined3d_caps);
5042     LeaveCriticalSection(&ddraw_cs);
5043     if (FAILED(hr))
5044     {
5045         WARN("Failed to get device caps, hr %#x.\n", hr);
5046         return hr;
5047     }
5048
5049     /* Copy the results into the d3d7 and d3d3 structures */
5050     desc7->dwDevCaps = wined3d_caps.DevCaps;
5051     desc7->dpcLineCaps.dwMiscCaps = wined3d_caps.PrimitiveMiscCaps;
5052     desc7->dpcLineCaps.dwRasterCaps = wined3d_caps.RasterCaps;
5053     desc7->dpcLineCaps.dwZCmpCaps = wined3d_caps.ZCmpCaps;
5054     desc7->dpcLineCaps.dwSrcBlendCaps = wined3d_caps.SrcBlendCaps;
5055     desc7->dpcLineCaps.dwDestBlendCaps = wined3d_caps.DestBlendCaps;
5056     desc7->dpcLineCaps.dwAlphaCmpCaps = wined3d_caps.AlphaCmpCaps;
5057     desc7->dpcLineCaps.dwShadeCaps = wined3d_caps.ShadeCaps;
5058     desc7->dpcLineCaps.dwTextureCaps = wined3d_caps.TextureCaps;
5059     desc7->dpcLineCaps.dwTextureFilterCaps = wined3d_caps.TextureFilterCaps;
5060     desc7->dpcLineCaps.dwTextureAddressCaps = wined3d_caps.TextureAddressCaps;
5061
5062     desc7->dwMaxTextureWidth = wined3d_caps.MaxTextureWidth;
5063     desc7->dwMaxTextureHeight = wined3d_caps.MaxTextureHeight;
5064
5065     desc7->dwMaxTextureRepeat = wined3d_caps.MaxTextureRepeat;
5066     desc7->dwMaxTextureAspectRatio = wined3d_caps.MaxTextureAspectRatio;
5067     desc7->dwMaxAnisotropy = wined3d_caps.MaxAnisotropy;
5068     desc7->dvMaxVertexW = wined3d_caps.MaxVertexW;
5069
5070     desc7->dvGuardBandLeft = wined3d_caps.GuardBandLeft;
5071     desc7->dvGuardBandTop = wined3d_caps.GuardBandTop;
5072     desc7->dvGuardBandRight = wined3d_caps.GuardBandRight;
5073     desc7->dvGuardBandBottom = wined3d_caps.GuardBandBottom;
5074
5075     desc7->dvExtentsAdjust = wined3d_caps.ExtentsAdjust;
5076     desc7->dwStencilCaps = wined3d_caps.StencilCaps;
5077
5078     desc7->dwFVFCaps = wined3d_caps.FVFCaps;
5079     desc7->dwTextureOpCaps = wined3d_caps.TextureOpCaps;
5080
5081     desc7->dwVertexProcessingCaps = wined3d_caps.VertexProcessingCaps;
5082     desc7->dwMaxActiveLights = wined3d_caps.MaxActiveLights;
5083
5084     /* Remove all non-d3d7 caps */
5085     desc7->dwDevCaps &= (
5086         D3DDEVCAPS_FLOATTLVERTEX         | D3DDEVCAPS_SORTINCREASINGZ          | D3DDEVCAPS_SORTDECREASINGZ          |
5087         D3DDEVCAPS_SORTEXACT             | D3DDEVCAPS_EXECUTESYSTEMMEMORY      | D3DDEVCAPS_EXECUTEVIDEOMEMORY       |
5088         D3DDEVCAPS_TLVERTEXSYSTEMMEMORY  | D3DDEVCAPS_TLVERTEXVIDEOMEMORY      | D3DDEVCAPS_TEXTURESYSTEMMEMORY      |
5089         D3DDEVCAPS_TEXTUREVIDEOMEMORY    | D3DDEVCAPS_DRAWPRIMTLVERTEX         | D3DDEVCAPS_CANRENDERAFTERFLIP       |
5090         D3DDEVCAPS_TEXTURENONLOCALVIDMEM | D3DDEVCAPS_DRAWPRIMITIVES2          | D3DDEVCAPS_SEPARATETEXTUREMEMORIES  |
5091         D3DDEVCAPS_DRAWPRIMITIVES2EX     | D3DDEVCAPS_HWTRANSFORMANDLIGHT      | D3DDEVCAPS_CANBLTSYSTONONLOCAL      |
5092         D3DDEVCAPS_HWRASTERIZATION);
5093
5094     desc7->dwStencilCaps &= (
5095         D3DSTENCILCAPS_KEEP              | D3DSTENCILCAPS_ZERO                 | D3DSTENCILCAPS_REPLACE              |
5096         D3DSTENCILCAPS_INCRSAT           | D3DSTENCILCAPS_DECRSAT              | D3DSTENCILCAPS_INVERT               |
5097         D3DSTENCILCAPS_INCR              | D3DSTENCILCAPS_DECR);
5098
5099     /* FVF caps ?*/
5100
5101     desc7->dwTextureOpCaps &= (
5102         D3DTEXOPCAPS_DISABLE             | D3DTEXOPCAPS_SELECTARG1             | D3DTEXOPCAPS_SELECTARG2             |
5103         D3DTEXOPCAPS_MODULATE            | D3DTEXOPCAPS_MODULATE2X             | D3DTEXOPCAPS_MODULATE4X             |
5104         D3DTEXOPCAPS_ADD                 | D3DTEXOPCAPS_ADDSIGNED              | D3DTEXOPCAPS_ADDSIGNED2X            |
5105         D3DTEXOPCAPS_SUBTRACT            | D3DTEXOPCAPS_ADDSMOOTH              | D3DTEXOPCAPS_BLENDTEXTUREALPHA      |
5106         D3DTEXOPCAPS_BLENDFACTORALPHA    | D3DTEXOPCAPS_BLENDTEXTUREALPHAPM    | D3DTEXOPCAPS_BLENDCURRENTALPHA      |
5107         D3DTEXOPCAPS_PREMODULATE         | D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA |
5108         D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | D3DTEXOPCAPS_BUMPENVMAP    |
5109         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE | D3DTEXOPCAPS_DOTPRODUCT3);
5110
5111     desc7->dwVertexProcessingCaps &= (
5112         D3DVTXPCAPS_TEXGEN               | D3DVTXPCAPS_MATERIALSOURCE7         | D3DVTXPCAPS_VERTEXFOG               |
5113         D3DVTXPCAPS_DIRECTIONALLIGHTS    | D3DVTXPCAPS_POSITIONALLIGHTS        | D3DVTXPCAPS_LOCALVIEWER);
5114
5115     desc7->dpcLineCaps.dwMiscCaps &= (
5116         D3DPMISCCAPS_MASKPLANES          | D3DPMISCCAPS_MASKZ                  | D3DPMISCCAPS_LINEPATTERNREP         |
5117         D3DPMISCCAPS_CONFORMANT          | D3DPMISCCAPS_CULLNONE               | D3DPMISCCAPS_CULLCW                 |
5118         D3DPMISCCAPS_CULLCCW);
5119
5120     desc7->dpcLineCaps.dwRasterCaps &= (
5121         D3DPRASTERCAPS_DITHER            | D3DPRASTERCAPS_ROP2                 | D3DPRASTERCAPS_XOR                  |
5122         D3DPRASTERCAPS_PAT               | D3DPRASTERCAPS_ZTEST                | D3DPRASTERCAPS_SUBPIXEL             |
5123         D3DPRASTERCAPS_SUBPIXELX         | D3DPRASTERCAPS_FOGVERTEX            | D3DPRASTERCAPS_FOGTABLE             |
5124         D3DPRASTERCAPS_STIPPLE           | D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT | D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT |
5125         D3DPRASTERCAPS_ANTIALIASEDGES    | D3DPRASTERCAPS_MIPMAPLODBIAS        | D3DPRASTERCAPS_ZBIAS                |
5126         D3DPRASTERCAPS_ZBUFFERLESSHSR    | D3DPRASTERCAPS_FOGRANGE             | D3DPRASTERCAPS_ANISOTROPY           |
5127         D3DPRASTERCAPS_WBUFFER           | D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT | D3DPRASTERCAPS_WFOG           |
5128         D3DPRASTERCAPS_ZFOG);
5129
5130     desc7->dpcLineCaps.dwZCmpCaps &= (
5131         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
5132         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
5133         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
5134
5135     desc7->dpcLineCaps.dwSrcBlendCaps &= (
5136         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
5137         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
5138         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
5139         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
5140         D3DPBLENDCAPS_BOTHINVSRCALPHA);
5141
5142     desc7->dpcLineCaps.dwDestBlendCaps &= (
5143         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
5144         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
5145         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
5146         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
5147         D3DPBLENDCAPS_BOTHINVSRCALPHA);
5148
5149     desc7->dpcLineCaps.dwAlphaCmpCaps &= (
5150         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
5151         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
5152         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
5153
5154     desc7->dpcLineCaps.dwShadeCaps &= (
5155         D3DPSHADECAPS_COLORFLATMONO      | D3DPSHADECAPS_COLORFLATRGB          | D3DPSHADECAPS_COLORGOURAUDMONO      |
5156         D3DPSHADECAPS_COLORGOURAUDRGB    | D3DPSHADECAPS_COLORPHONGMONO        | D3DPSHADECAPS_COLORPHONGRGB         |
5157         D3DPSHADECAPS_SPECULARFLATMONO   | D3DPSHADECAPS_SPECULARFLATRGB       | D3DPSHADECAPS_SPECULARGOURAUDMONO   |
5158         D3DPSHADECAPS_SPECULARGOURAUDRGB | D3DPSHADECAPS_SPECULARPHONGMONO     | D3DPSHADECAPS_SPECULARPHONGRGB      |
5159         D3DPSHADECAPS_ALPHAFLATBLEND     | D3DPSHADECAPS_ALPHAFLATSTIPPLED     | D3DPSHADECAPS_ALPHAGOURAUDBLEND     |
5160         D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED | D3DPSHADECAPS_ALPHAPHONGBLEND     | D3DPSHADECAPS_ALPHAPHONGSTIPPLED    |
5161         D3DPSHADECAPS_FOGFLAT            | D3DPSHADECAPS_FOGGOURAUD            | D3DPSHADECAPS_FOGPHONG);
5162
5163     desc7->dpcLineCaps.dwTextureCaps &= (
5164         D3DPTEXTURECAPS_PERSPECTIVE      | D3DPTEXTURECAPS_POW2                | D3DPTEXTURECAPS_ALPHA               |
5165         D3DPTEXTURECAPS_TRANSPARENCY     | D3DPTEXTURECAPS_BORDER              | D3DPTEXTURECAPS_SQUAREONLY          |
5166         D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE | D3DPTEXTURECAPS_ALPHAPALETTE| D3DPTEXTURECAPS_NONPOW2CONDITIONAL  |
5167         D3DPTEXTURECAPS_PROJECTED        | D3DPTEXTURECAPS_CUBEMAP             | D3DPTEXTURECAPS_COLORKEYBLEND);
5168
5169     desc7->dpcLineCaps.dwTextureFilterCaps &= (
5170         D3DPTFILTERCAPS_NEAREST          | D3DPTFILTERCAPS_LINEAR              | D3DPTFILTERCAPS_MIPNEAREST          |
5171         D3DPTFILTERCAPS_MIPLINEAR        | D3DPTFILTERCAPS_LINEARMIPNEAREST    | D3DPTFILTERCAPS_LINEARMIPLINEAR     |
5172         D3DPTFILTERCAPS_MINFPOINT        | D3DPTFILTERCAPS_MINFLINEAR          | D3DPTFILTERCAPS_MINFANISOTROPIC     |
5173         D3DPTFILTERCAPS_MIPFPOINT        | D3DPTFILTERCAPS_MIPFLINEAR          | D3DPTFILTERCAPS_MAGFPOINT           |
5174         D3DPTFILTERCAPS_MAGFLINEAR       | D3DPTFILTERCAPS_MAGFANISOTROPIC     | D3DPTFILTERCAPS_MAGFAFLATCUBIC      |
5175         D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
5176
5177     desc7->dpcLineCaps.dwTextureBlendCaps &= (
5178         D3DPTBLENDCAPS_DECAL             | D3DPTBLENDCAPS_MODULATE             | D3DPTBLENDCAPS_DECALALPHA           |
5179         D3DPTBLENDCAPS_MODULATEALPHA     | D3DPTBLENDCAPS_DECALMASK            | D3DPTBLENDCAPS_MODULATEMASK         |
5180         D3DPTBLENDCAPS_COPY              | D3DPTBLENDCAPS_ADD);
5181
5182     desc7->dpcLineCaps.dwTextureAddressCaps &= (
5183         D3DPTADDRESSCAPS_WRAP            | D3DPTADDRESSCAPS_MIRROR             | D3DPTADDRESSCAPS_CLAMP              |
5184         D3DPTADDRESSCAPS_BORDER          | D3DPTADDRESSCAPS_INDEPENDENTUV);
5185
5186     if (!(desc7->dpcLineCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2))
5187     {
5188         /* DirectX7 always has the np2 flag set, no matter what the card
5189          * supports. Some old games (Rollcage) check the caps incorrectly.
5190          * If wined3d supports nonpow2 textures it also has np2 conditional
5191          * support. */
5192         desc7->dpcLineCaps.dwTextureCaps |= D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL;
5193     }
5194
5195     /* Fill the missing members, and do some fixup */
5196     desc7->dpcLineCaps.dwSize = sizeof(desc7->dpcLineCaps);
5197     desc7->dpcLineCaps.dwTextureBlendCaps = D3DPTBLENDCAPS_ADD | D3DPTBLENDCAPS_MODULATEMASK |
5198                                             D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_DECAL |
5199                                             D3DPTBLENDCAPS_DECALALPHA | D3DPTBLENDCAPS_DECALMASK |
5200                                             D3DPTBLENDCAPS_MODULATE | D3DPTBLENDCAPS_MODULATEALPHA;
5201     desc7->dpcLineCaps.dwStippleWidth = 32;
5202     desc7->dpcLineCaps.dwStippleHeight = 32;
5203     /* Use the same for the TriCaps */
5204     desc7->dpcTriCaps = desc7->dpcLineCaps;
5205
5206     desc7->dwDeviceRenderBitDepth = DDBD_16 | DDBD_24 | DDBD_32;
5207     desc7->dwDeviceZBufferBitDepth = DDBD_16 | DDBD_24;
5208     desc7->dwMinTextureWidth = 1;
5209     desc7->dwMinTextureHeight = 1;
5210
5211     /* Convert DWORDs safely to WORDs */
5212     if (wined3d_caps.MaxTextureBlendStages > 0xffff) desc7->wMaxTextureBlendStages = 0xffff;
5213     else desc7->wMaxTextureBlendStages = (WORD)wined3d_caps.MaxTextureBlendStages;
5214     if (wined3d_caps.MaxSimultaneousTextures > 0xffff) desc7->wMaxSimultaneousTextures = 0xffff;
5215     else desc7->wMaxSimultaneousTextures = (WORD)wined3d_caps.MaxSimultaneousTextures;
5216
5217     if (wined3d_caps.MaxUserClipPlanes > 0xffff) desc7->wMaxUserClipPlanes = 0xffff;
5218     else desc7->wMaxUserClipPlanes = (WORD)wined3d_caps.MaxUserClipPlanes;
5219     if (wined3d_caps.MaxVertexBlendMatrices > 0xffff) desc7->wMaxVertexBlendMatrices = 0xffff;
5220     else desc7->wMaxVertexBlendMatrices = (WORD)wined3d_caps.MaxVertexBlendMatrices;
5221
5222     desc7->deviceGUID = IID_IDirect3DTnLHalDevice;
5223
5224     desc7->dwReserved1 = 0;
5225     desc7->dwReserved2 = 0;
5226     desc7->dwReserved3 = 0;
5227     desc7->dwReserved4 = 0;
5228
5229     /* Fill the old structure */
5230     memset(desc1, 0, sizeof(*desc1));
5231     desc1->dwSize = sizeof(D3DDEVICEDESC);
5232     desc1->dwFlags = D3DDD_COLORMODEL
5233             | D3DDD_DEVCAPS
5234             | D3DDD_TRANSFORMCAPS
5235             | D3DDD_BCLIPPING
5236             | D3DDD_LIGHTINGCAPS
5237             | D3DDD_LINECAPS
5238             | D3DDD_TRICAPS
5239             | D3DDD_DEVICERENDERBITDEPTH
5240             | D3DDD_DEVICEZBUFFERBITDEPTH
5241             | D3DDD_MAXBUFFERSIZE
5242             | D3DDD_MAXVERTEXCOUNT;
5243
5244     desc1->dcmColorModel = D3DCOLOR_RGB;
5245     desc1->dwDevCaps = desc7->dwDevCaps;
5246     desc1->dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
5247     desc1->dtcTransformCaps.dwCaps = D3DTRANSFORMCAPS_CLIP;
5248     desc1->bClipping = TRUE;
5249     desc1->dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
5250     desc1->dlcLightingCaps.dwCaps = D3DLIGHTCAPS_DIRECTIONAL
5251             | D3DLIGHTCAPS_PARALLELPOINT
5252             | D3DLIGHTCAPS_POINT
5253             | D3DLIGHTCAPS_SPOT;
5254
5255     desc1->dlcLightingCaps.dwLightingModel = D3DLIGHTINGMODEL_RGB;
5256     desc1->dlcLightingCaps.dwNumLights = desc7->dwMaxActiveLights;
5257
5258     desc1->dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
5259     desc1->dpcLineCaps.dwMiscCaps = desc7->dpcLineCaps.dwMiscCaps;
5260     desc1->dpcLineCaps.dwRasterCaps = desc7->dpcLineCaps.dwRasterCaps;
5261     desc1->dpcLineCaps.dwZCmpCaps = desc7->dpcLineCaps.dwZCmpCaps;
5262     desc1->dpcLineCaps.dwSrcBlendCaps = desc7->dpcLineCaps.dwSrcBlendCaps;
5263     desc1->dpcLineCaps.dwDestBlendCaps = desc7->dpcLineCaps.dwDestBlendCaps;
5264     desc1->dpcLineCaps.dwShadeCaps = desc7->dpcLineCaps.dwShadeCaps;
5265     desc1->dpcLineCaps.dwTextureCaps = desc7->dpcLineCaps.dwTextureCaps;
5266     desc1->dpcLineCaps.dwTextureFilterCaps = desc7->dpcLineCaps.dwTextureFilterCaps;
5267     desc1->dpcLineCaps.dwTextureBlendCaps = desc7->dpcLineCaps.dwTextureBlendCaps;
5268     desc1->dpcLineCaps.dwTextureAddressCaps = desc7->dpcLineCaps.dwTextureAddressCaps;
5269     desc1->dpcLineCaps.dwStippleWidth = desc7->dpcLineCaps.dwStippleWidth;
5270     desc1->dpcLineCaps.dwAlphaCmpCaps = desc7->dpcLineCaps.dwAlphaCmpCaps;
5271
5272     desc1->dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
5273     desc1->dpcTriCaps.dwMiscCaps = desc7->dpcTriCaps.dwMiscCaps;
5274     desc1->dpcTriCaps.dwRasterCaps = desc7->dpcTriCaps.dwRasterCaps;
5275     desc1->dpcTriCaps.dwZCmpCaps = desc7->dpcTriCaps.dwZCmpCaps;
5276     desc1->dpcTriCaps.dwSrcBlendCaps = desc7->dpcTriCaps.dwSrcBlendCaps;
5277     desc1->dpcTriCaps.dwDestBlendCaps = desc7->dpcTriCaps.dwDestBlendCaps;
5278     desc1->dpcTriCaps.dwShadeCaps = desc7->dpcTriCaps.dwShadeCaps;
5279     desc1->dpcTriCaps.dwTextureCaps = desc7->dpcTriCaps.dwTextureCaps;
5280     desc1->dpcTriCaps.dwTextureFilterCaps = desc7->dpcTriCaps.dwTextureFilterCaps;
5281     desc1->dpcTriCaps.dwTextureBlendCaps = desc7->dpcTriCaps.dwTextureBlendCaps;
5282     desc1->dpcTriCaps.dwTextureAddressCaps = desc7->dpcTriCaps.dwTextureAddressCaps;
5283     desc1->dpcTriCaps.dwStippleWidth = desc7->dpcTriCaps.dwStippleWidth;
5284     desc1->dpcTriCaps.dwAlphaCmpCaps = desc7->dpcTriCaps.dwAlphaCmpCaps;
5285
5286     desc1->dwDeviceRenderBitDepth = desc7->dwDeviceRenderBitDepth;
5287     desc1->dwDeviceZBufferBitDepth = desc7->dwDeviceZBufferBitDepth;
5288     desc1->dwMaxBufferSize = 0;
5289     desc1->dwMaxVertexCount = 65536;
5290     desc1->dwMinTextureWidth  = desc7->dwMinTextureWidth;
5291     desc1->dwMinTextureHeight = desc7->dwMinTextureHeight;
5292     desc1->dwMaxTextureWidth  = desc7->dwMaxTextureWidth;
5293     desc1->dwMaxTextureHeight = desc7->dwMaxTextureHeight;
5294     desc1->dwMinStippleWidth  = 1;
5295     desc1->dwMinStippleHeight = 1;
5296     desc1->dwMaxStippleWidth  = 32;
5297     desc1->dwMaxStippleHeight = 32;
5298     desc1->dwMaxTextureRepeat = desc7->dwMaxTextureRepeat;
5299     desc1->dwMaxTextureAspectRatio = desc7->dwMaxTextureAspectRatio;
5300     desc1->dwMaxAnisotropy = desc7->dwMaxAnisotropy;
5301     desc1->dvGuardBandLeft = desc7->dvGuardBandLeft;
5302     desc1->dvGuardBandRight = desc7->dvGuardBandRight;
5303     desc1->dvGuardBandTop = desc7->dvGuardBandTop;
5304     desc1->dvGuardBandBottom = desc7->dvGuardBandBottom;
5305     desc1->dvExtentsAdjust = desc7->dvExtentsAdjust;
5306     desc1->dwStencilCaps = desc7->dwStencilCaps;
5307     desc1->dwFVFCaps = desc7->dwFVFCaps;
5308     desc1->dwTextureOpCaps = desc7->dwTextureOpCaps;
5309     desc1->wMaxTextureBlendStages = desc7->wMaxTextureBlendStages;
5310     desc1->wMaxSimultaneousTextures = desc7->wMaxSimultaneousTextures;
5311
5312     return DD_OK;
5313 }
5314
5315 /*****************************************************************************
5316  * IDirectDraw7 VTable
5317  *****************************************************************************/
5318 static const struct IDirectDraw7Vtbl ddraw7_vtbl =
5319 {
5320     /* IUnknown */
5321     ddraw7_QueryInterface,
5322     ddraw7_AddRef,
5323     ddraw7_Release,
5324     /* IDirectDraw */
5325     ddraw7_Compact,
5326     ddraw7_CreateClipper,
5327     ddraw7_CreatePalette,
5328     ddraw7_CreateSurface,
5329     ddraw7_DuplicateSurface,
5330     ddraw7_EnumDisplayModes,
5331     ddraw7_EnumSurfaces,
5332     ddraw7_FlipToGDISurface,
5333     ddraw7_GetCaps,
5334     ddraw7_GetDisplayMode,
5335     ddraw7_GetFourCCCodes,
5336     ddraw7_GetGDISurface,
5337     ddraw7_GetMonitorFrequency,
5338     ddraw7_GetScanLine,
5339     ddraw7_GetVerticalBlankStatus,
5340     ddraw7_Initialize,
5341     ddraw7_RestoreDisplayMode,
5342     ddraw7_SetCooperativeLevel,
5343     ddraw7_SetDisplayMode,
5344     ddraw7_WaitForVerticalBlank,
5345     /* IDirectDraw2 */
5346     ddraw7_GetAvailableVidMem,
5347     /* IDirectDraw3 */
5348     ddraw7_GetSurfaceFromDC,
5349     /* IDirectDraw4 */
5350     ddraw7_RestoreAllSurfaces,
5351     ddraw7_TestCooperativeLevel,
5352     ddraw7_GetDeviceIdentifier,
5353     /* IDirectDraw7 */
5354     ddraw7_StartModeTest,
5355     ddraw7_EvaluateMode
5356 };
5357
5358 static const struct IDirectDraw4Vtbl ddraw4_vtbl =
5359 {
5360     /* IUnknown */
5361     ddraw4_QueryInterface,
5362     ddraw4_AddRef,
5363     ddraw4_Release,
5364     /* IDirectDraw */
5365     ddraw4_Compact,
5366     ddraw4_CreateClipper,
5367     ddraw4_CreatePalette,
5368     ddraw4_CreateSurface,
5369     ddraw4_DuplicateSurface,
5370     ddraw4_EnumDisplayModes,
5371     ddraw4_EnumSurfaces,
5372     ddraw4_FlipToGDISurface,
5373     ddraw4_GetCaps,
5374     ddraw4_GetDisplayMode,
5375     ddraw4_GetFourCCCodes,
5376     ddraw4_GetGDISurface,
5377     ddraw4_GetMonitorFrequency,
5378     ddraw4_GetScanLine,
5379     ddraw4_GetVerticalBlankStatus,
5380     ddraw4_Initialize,
5381     ddraw4_RestoreDisplayMode,
5382     ddraw4_SetCooperativeLevel,
5383     ddraw4_SetDisplayMode,
5384     ddraw4_WaitForVerticalBlank,
5385     /* IDirectDraw2 */
5386     ddraw4_GetAvailableVidMem,
5387     /* IDirectDraw3 */
5388     ddraw4_GetSurfaceFromDC,
5389     /* IDirectDraw4 */
5390     ddraw4_RestoreAllSurfaces,
5391     ddraw4_TestCooperativeLevel,
5392     ddraw4_GetDeviceIdentifier,
5393 };
5394
5395 static const struct IDirectDraw3Vtbl ddraw3_vtbl =
5396 {
5397     /* IUnknown */
5398     ddraw3_QueryInterface,
5399     ddraw3_AddRef,
5400     ddraw3_Release,
5401     /* IDirectDraw */
5402     ddraw3_Compact,
5403     ddraw3_CreateClipper,
5404     ddraw3_CreatePalette,
5405     ddraw3_CreateSurface,
5406     ddraw3_DuplicateSurface,
5407     ddraw3_EnumDisplayModes,
5408     ddraw3_EnumSurfaces,
5409     ddraw3_FlipToGDISurface,
5410     ddraw3_GetCaps,
5411     ddraw3_GetDisplayMode,
5412     ddraw3_GetFourCCCodes,
5413     ddraw3_GetGDISurface,
5414     ddraw3_GetMonitorFrequency,
5415     ddraw3_GetScanLine,
5416     ddraw3_GetVerticalBlankStatus,
5417     ddraw3_Initialize,
5418     ddraw3_RestoreDisplayMode,
5419     ddraw3_SetCooperativeLevel,
5420     ddraw3_SetDisplayMode,
5421     ddraw3_WaitForVerticalBlank,
5422     /* IDirectDraw2 */
5423     ddraw3_GetAvailableVidMem,
5424     /* IDirectDraw3 */
5425     ddraw3_GetSurfaceFromDC,
5426 };
5427
5428 static const struct IDirectDraw2Vtbl ddraw2_vtbl =
5429 {
5430     /* IUnknown */
5431     ddraw2_QueryInterface,
5432     ddraw2_AddRef,
5433     ddraw2_Release,
5434     /* IDirectDraw */
5435     ddraw2_Compact,
5436     ddraw2_CreateClipper,
5437     ddraw2_CreatePalette,
5438     ddraw2_CreateSurface,
5439     ddraw2_DuplicateSurface,
5440     ddraw2_EnumDisplayModes,
5441     ddraw2_EnumSurfaces,
5442     ddraw2_FlipToGDISurface,
5443     ddraw2_GetCaps,
5444     ddraw2_GetDisplayMode,
5445     ddraw2_GetFourCCCodes,
5446     ddraw2_GetGDISurface,
5447     ddraw2_GetMonitorFrequency,
5448     ddraw2_GetScanLine,
5449     ddraw2_GetVerticalBlankStatus,
5450     ddraw2_Initialize,
5451     ddraw2_RestoreDisplayMode,
5452     ddraw2_SetCooperativeLevel,
5453     ddraw2_SetDisplayMode,
5454     ddraw2_WaitForVerticalBlank,
5455     /* IDirectDraw2 */
5456     ddraw2_GetAvailableVidMem,
5457 };
5458
5459 static const struct IDirectDrawVtbl ddraw1_vtbl =
5460 {
5461     /* IUnknown */
5462     ddraw1_QueryInterface,
5463     ddraw1_AddRef,
5464     ddraw1_Release,
5465     /* IDirectDraw */
5466     ddraw1_Compact,
5467     ddraw1_CreateClipper,
5468     ddraw1_CreatePalette,
5469     ddraw1_CreateSurface,
5470     ddraw1_DuplicateSurface,
5471     ddraw1_EnumDisplayModes,
5472     ddraw1_EnumSurfaces,
5473     ddraw1_FlipToGDISurface,
5474     ddraw1_GetCaps,
5475     ddraw1_GetDisplayMode,
5476     ddraw1_GetFourCCCodes,
5477     ddraw1_GetGDISurface,
5478     ddraw1_GetMonitorFrequency,
5479     ddraw1_GetScanLine,
5480     ddraw1_GetVerticalBlankStatus,
5481     ddraw1_Initialize,
5482     ddraw1_RestoreDisplayMode,
5483     ddraw1_SetCooperativeLevel,
5484     ddraw1_SetDisplayMode,
5485     ddraw1_WaitForVerticalBlank,
5486 };
5487
5488 static const struct IDirect3D7Vtbl d3d7_vtbl =
5489 {
5490     /* IUnknown methods */
5491     d3d7_QueryInterface,
5492     d3d7_AddRef,
5493     d3d7_Release,
5494     /* IDirect3D7 methods */
5495     d3d7_EnumDevices,
5496     d3d7_CreateDevice,
5497     d3d7_CreateVertexBuffer,
5498     d3d7_EnumZBufferFormats,
5499     d3d7_EvictManagedTextures
5500 };
5501
5502 static const struct IDirect3D3Vtbl d3d3_vtbl =
5503 {
5504     /* IUnknown methods */
5505     d3d3_QueryInterface,
5506     d3d3_AddRef,
5507     d3d3_Release,
5508     /* IDirect3D3 methods */
5509     d3d3_EnumDevices,
5510     d3d3_CreateLight,
5511     d3d3_CreateMaterial,
5512     d3d3_CreateViewport,
5513     d3d3_FindDevice,
5514     d3d3_CreateDevice,
5515     d3d3_CreateVertexBuffer,
5516     d3d3_EnumZBufferFormats,
5517     d3d3_EvictManagedTextures
5518 };
5519
5520 static const struct IDirect3D2Vtbl d3d2_vtbl =
5521 {
5522     /* IUnknown methods */
5523     d3d2_QueryInterface,
5524     d3d2_AddRef,
5525     d3d2_Release,
5526     /* IDirect3D2 methods */
5527     d3d2_EnumDevices,
5528     d3d2_CreateLight,
5529     d3d2_CreateMaterial,
5530     d3d2_CreateViewport,
5531     d3d2_FindDevice,
5532     d3d2_CreateDevice
5533 };
5534
5535 static const struct IDirect3DVtbl d3d1_vtbl =
5536 {
5537     /* IUnknown methods */
5538     d3d1_QueryInterface,
5539     d3d1_AddRef,
5540     d3d1_Release,
5541     /* IDirect3D methods */
5542     d3d1_Initialize,
5543     d3d1_EnumDevices,
5544     d3d1_CreateLight,
5545     d3d1_CreateMaterial,
5546     d3d1_CreateViewport,
5547     d3d1_FindDevice
5548 };
5549
5550 /*****************************************************************************
5551  * ddraw_find_decl
5552  *
5553  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
5554  * if none was found.
5555  *
5556  * This function is in ddraw.c and the DDraw object space because D3D7
5557  * vertex buffers are created using the IDirect3D interface to the ddraw
5558  * object, so they can be valid across D3D devices(theoretically. The ddraw
5559  * object also owns the wined3d device
5560  *
5561  * Parameters:
5562  *  This: Device
5563  *  fvf: Fvf to find the decl for
5564  *
5565  * Returns:
5566  *  NULL in case of an error, the vertex declaration for the FVF otherwise.
5567  *
5568  *****************************************************************************/
5569 struct wined3d_vertex_declaration *ddraw_find_decl(IDirectDrawImpl *This, DWORD fvf)
5570 {
5571     struct wined3d_vertex_declaration *pDecl = NULL;
5572     HRESULT hr;
5573     int p, low, high; /* deliberately signed */
5574     struct FvfToDecl *convertedDecls = This->decls;
5575
5576     TRACE("Searching for declaration for fvf %08x... ", fvf);
5577
5578     low = 0;
5579     high = This->numConvertedDecls - 1;
5580     while(low <= high) {
5581         p = (low + high) >> 1;
5582         TRACE("%d ", p);
5583         if(convertedDecls[p].fvf == fvf) {
5584             TRACE("found %p\n", convertedDecls[p].decl);
5585             return convertedDecls[p].decl;
5586         } else if(convertedDecls[p].fvf < fvf) {
5587             low = p + 1;
5588         } else {
5589             high = p - 1;
5590         }
5591     }
5592     TRACE("not found. Creating and inserting at position %d.\n", low);
5593
5594     hr = wined3d_vertex_declaration_create_from_fvf(This->wined3d_device,
5595             fvf, This, &ddraw_null_wined3d_parent_ops, &pDecl);
5596     if (hr != S_OK) return NULL;
5597
5598     if(This->declArraySize == This->numConvertedDecls) {
5599         int grow = max(This->declArraySize / 2, 8);
5600         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
5601                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
5602         if (!convertedDecls)
5603         {
5604             wined3d_vertex_declaration_decref(pDecl);
5605             return NULL;
5606         }
5607         This->decls = convertedDecls;
5608         This->declArraySize += grow;
5609     }
5610
5611     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
5612     convertedDecls[low].decl = pDecl;
5613     convertedDecls[low].fvf = fvf;
5614     This->numConvertedDecls++;
5615
5616     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
5617     return pDecl;
5618 }
5619
5620 static inline struct IDirectDrawImpl *ddraw_from_device_parent(struct wined3d_device_parent *device_parent)
5621 {
5622     return CONTAINING_RECORD(device_parent, struct IDirectDrawImpl, device_parent);
5623 }
5624
5625 static void CDECL device_parent_wined3d_device_created(struct wined3d_device_parent *device_parent,
5626         struct wined3d_device *device)
5627 {
5628     TRACE("device_parent %p, device %p.\n", device_parent, device);
5629 }
5630
5631 static HRESULT CDECL device_parent_create_surface(struct wined3d_device_parent *device_parent,
5632         void *container_parent, UINT width, UINT height, enum wined3d_format_id format, DWORD usage,
5633         WINED3DPOOL pool, UINT level, WINED3DCUBEMAP_FACES face, struct wined3d_surface **surface)
5634 {
5635     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5636     IDirectDrawSurfaceImpl *surf = NULL;
5637     UINT i = 0;
5638     DDSCAPS2 searchcaps = ddraw->tex_root->surface_desc.ddsCaps;
5639
5640     TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, usage %#x,\n"
5641             "\tpool %#x, level %u, face %u, surface %p.\n",
5642             device_parent, container_parent, width, height, format, usage, pool, level, face, surface);
5643
5644     searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
5645     switch(face)
5646     {
5647         case WINED3DCUBEMAP_FACE_POSITIVE_X:
5648             TRACE("Asked for positive x\n");
5649             if (searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP)
5650             {
5651                 searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
5652             }
5653             surf = ddraw->tex_root; break;
5654         case WINED3DCUBEMAP_FACE_NEGATIVE_X:
5655             TRACE("Asked for negative x\n");
5656             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
5657         case WINED3DCUBEMAP_FACE_POSITIVE_Y:
5658             TRACE("Asked for positive y\n");
5659             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
5660         case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
5661             TRACE("Asked for negative y\n");
5662             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
5663         case WINED3DCUBEMAP_FACE_POSITIVE_Z:
5664             TRACE("Asked for positive z\n");
5665             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
5666         case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
5667             TRACE("Asked for negative z\n");
5668             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
5669         default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
5670     }
5671
5672     if (!surf)
5673     {
5674         IDirectDrawSurface7 *attached;
5675         IDirectDrawSurface7_GetAttachedSurface(&ddraw->tex_root->IDirectDrawSurface7_iface, &searchcaps, &attached);
5676         surf = unsafe_impl_from_IDirectDrawSurface7(attached);
5677         IDirectDrawSurface7_Release(attached);
5678     }
5679     if (!surf) ERR("root search surface not found\n");
5680
5681     /* Find the wanted mipmap. There are enough mipmaps in the chain */
5682     while (i < level)
5683     {
5684         IDirectDrawSurface7 *attached;
5685         IDirectDrawSurface7_GetAttachedSurface(&surf->IDirectDrawSurface7_iface, &searchcaps, &attached);
5686         if(!attached) ERR("Surface not found\n");
5687         surf = impl_from_IDirectDrawSurface7(attached);
5688         IDirectDrawSurface7_Release(attached);
5689         ++i;
5690     }
5691
5692     /* Return the surface */
5693     *surface = surf->wined3d_surface;
5694     wined3d_surface_incref(*surface);
5695
5696     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, surf);
5697
5698     return D3D_OK;
5699 }
5700
5701 static HRESULT WINAPI findRenderTarget(IDirectDrawSurface7 *surface, DDSURFACEDESC2 *surface_desc, void *ctx)
5702 {
5703     IDirectDrawSurfaceImpl *s = impl_from_IDirectDrawSurface7(surface);
5704     IDirectDrawSurfaceImpl **target = ctx;
5705
5706     if (!s->isRenderTarget)
5707     {
5708         *target = s;
5709         IDirectDrawSurface7_Release(surface);
5710         return DDENUMRET_CANCEL;
5711     }
5712
5713     /* Recurse into the surface tree */
5714     IDirectDrawSurface7_EnumAttachedSurfaces(surface, ctx, findRenderTarget);
5715
5716     IDirectDrawSurface7_Release(surface);
5717     if (*target) return DDENUMRET_CANCEL;
5718
5719     return DDENUMRET_OK;
5720 }
5721
5722 static HRESULT CDECL device_parent_create_rendertarget(struct wined3d_device_parent *device_parent,
5723         void *container_parent, UINT width, UINT height, enum wined3d_format_id format,
5724         WINED3DMULTISAMPLE_TYPE multisample_type, DWORD multisample_quality, BOOL lockable,
5725         struct wined3d_surface **surface)
5726 {
5727     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5728     IDirectDrawSurfaceImpl *d3d_surface = ddraw->d3d_target;
5729     IDirectDrawSurfaceImpl *target = NULL;
5730
5731     TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5732             "\tmultisample_quality %u, lockable %u, surface %p.\n",
5733             device_parent, container_parent, width, height, format, multisample_type,
5734             multisample_quality, lockable, surface);
5735
5736     if (d3d_surface->isRenderTarget)
5737     {
5738         IDirectDrawSurface7_EnumAttachedSurfaces(&d3d_surface->IDirectDrawSurface7_iface, &target, findRenderTarget);
5739     }
5740     else
5741     {
5742         target = d3d_surface;
5743     }
5744
5745     if (!target)
5746     {
5747         target = ddraw->d3d_target;
5748         ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", ddraw);
5749     }
5750
5751     /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */
5752
5753     *surface = target->wined3d_surface;
5754     wined3d_surface_incref(*surface);
5755     target->isRenderTarget = TRUE;
5756
5757     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, d3d_surface);
5758
5759     return D3D_OK;
5760 }
5761
5762 static HRESULT CDECL device_parent_create_depth_stencil(struct wined3d_device_parent *device_parent,
5763         UINT width, UINT height, enum wined3d_format_id format, WINED3DMULTISAMPLE_TYPE multisample_type,
5764         DWORD multisample_quality, BOOL discard, struct wined3d_surface **surface)
5765 {
5766     ERR("DirectDraw doesn't have and shoudn't try creating implicit depth buffers.\n");
5767     return E_NOTIMPL;
5768 }
5769
5770 static HRESULT CDECL device_parent_create_volume(struct wined3d_device_parent *device_parent,
5771         void *container_parent, UINT width, UINT height, UINT depth, enum wined3d_format_id format,
5772         WINED3DPOOL pool, DWORD usage, struct wined3d_volume **volume)
5773 {
5774     TRACE("device_parent %p, container_parent %p, width %u, height %u, depth %u, "
5775             "format %#x, pool %#x, usage %#x, volume %p.\n",
5776             device_parent, container_parent, width, height, depth,
5777             format, pool, usage, volume);
5778
5779     ERR("Not implemented!\n");
5780
5781     return E_NOTIMPL;
5782 }
5783
5784 static HRESULT CDECL device_parent_create_swapchain(struct wined3d_device_parent *device_parent,
5785         WINED3DPRESENT_PARAMETERS *present_parameters, struct wined3d_swapchain **swapchain)
5786 {
5787     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5788     IDirectDrawSurfaceImpl *iterator;
5789     HRESULT hr;
5790
5791     TRACE("device_parent %p, present_parameters %p, swapchain %p.\n", device_parent, present_parameters, swapchain);
5792
5793     hr = wined3d_swapchain_create(ddraw->wined3d_device, present_parameters,
5794             DefaultSurfaceType, NULL, &ddraw_null_wined3d_parent_ops, swapchain);
5795     if (FAILED(hr))
5796     {
5797         WARN("Failed to create swapchain, hr %#x.\n", hr);
5798         *swapchain = NULL;
5799         return hr;
5800     }
5801
5802     ddraw->d3d_target->wined3d_swapchain = *swapchain;
5803     iterator = ddraw->d3d_target->complex_array[0];
5804     while (iterator)
5805     {
5806         iterator->wined3d_swapchain = *swapchain;
5807         iterator = iterator->complex_array[0];
5808     }
5809
5810     return hr;
5811 }
5812
5813 static const struct wined3d_device_parent_ops ddraw_wined3d_device_parent_ops =
5814 {
5815     device_parent_wined3d_device_created,
5816     device_parent_create_surface,
5817     device_parent_create_rendertarget,
5818     device_parent_create_depth_stencil,
5819     device_parent_create_volume,
5820     device_parent_create_swapchain,
5821 };
5822
5823 HRESULT ddraw_init(IDirectDrawImpl *ddraw, WINED3DDEVTYPE device_type)
5824 {
5825     HRESULT hr;
5826     HDC hDC;
5827
5828     ddraw->IDirectDraw7_iface.lpVtbl = &ddraw7_vtbl;
5829     ddraw->IDirectDraw_iface.lpVtbl = &ddraw1_vtbl;
5830     ddraw->IDirectDraw2_iface.lpVtbl = &ddraw2_vtbl;
5831     ddraw->IDirectDraw3_iface.lpVtbl = &ddraw3_vtbl;
5832     ddraw->IDirectDraw4_iface.lpVtbl = &ddraw4_vtbl;
5833     ddraw->IDirect3D_iface.lpVtbl = &d3d1_vtbl;
5834     ddraw->IDirect3D2_iface.lpVtbl = &d3d2_vtbl;
5835     ddraw->IDirect3D3_iface.lpVtbl = &d3d3_vtbl;
5836     ddraw->IDirect3D7_iface.lpVtbl = &d3d7_vtbl;
5837     ddraw->device_parent.ops = &ddraw_wined3d_device_parent_ops;
5838     ddraw->numIfaces = 1;
5839     ddraw->ref7 = 1;
5840
5841     /* Get the current screen settings. */
5842     hDC = GetDC(0);
5843     ddraw->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
5844     ReleaseDC(0, hDC);
5845     ddraw->orig_width = GetSystemMetrics(SM_CXSCREEN);
5846     ddraw->orig_height = GetSystemMetrics(SM_CYSCREEN);
5847
5848     ddraw->wineD3D = wined3d_create(7, WINED3D_PALETTE_PER_SURFACE | WINED3D_LEGACY_DEPTH_BIAS,
5849             &ddraw->IDirectDraw7_iface);
5850     if (!ddraw->wineD3D)
5851     {
5852         WARN("Failed to create a wined3d object.\n");
5853         return E_OUTOFMEMORY;
5854     }
5855
5856     hr = wined3d_device_create(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, device_type,
5857             NULL, 0, 8, &ddraw->device_parent, &ddraw->wined3d_device);
5858     if (FAILED(hr))
5859     {
5860         WARN("Failed to create a wined3d device, hr %#x.\n", hr);
5861         wined3d_decref(ddraw->wineD3D);
5862         return hr;
5863     }
5864
5865     /* Get the amount of video memory */
5866     ddraw->total_vidmem = wined3d_device_get_available_texture_mem(ddraw->wined3d_device);
5867
5868     list_init(&ddraw->surface_list);
5869
5870     return DD_OK;
5871 }