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