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