wined3d: Get rid of the WINED3DADAPTER_IDENTIFIER typedef.
[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_set_swapchain_window(ddraw, 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             struct wined3d_display_mode 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     struct wined3d_display_mode mode;
851     enum wined3d_format_id format;
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_id == format
883             && mode.refresh_rate == 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.refresh_rate = RefreshRate;
902     mode.format_id = 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     struct wined3d_display_mode mode;
1243     HRESULT hr;
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_id);
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     struct wined3d_display_mode mode;
1346     DWORD count = 0, i, outsize;
1347     HRESULT hr;
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, &mode);
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                 mode.format_id, 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         struct wined3d_adapter_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     struct wined3d_display_mode mode;
1780     static DWORD cur_scanline;
1781     static BOOL hide = FALSE;
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     struct wined3d_display_mode *enum_modes = NULL;
2003     struct wined3d_display_mode mode;
2004     unsigned int modenum, fmt;
2005     DDSURFACEDESC2 callback_sd;
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(*enum_modes) * 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_id);
2043             if (DDSD)
2044             {
2045                 if (DDSD->dwFlags & DDSD_WIDTH && mode.width != DDSD->dwWidth)
2046                     continue;
2047                 if (DDSD->dwFlags & DDSD_HEIGHT && mode.height != DDSD->dwHeight)
2048                     continue;
2049                 if (DDSD->dwFlags & DDSD_REFRESHRATE && mode.refresh_rate != DDSD->u2.dwRefreshRate)
2050                     continue;
2051                 if (DDSD->dwFlags & DDSD_PIXELFORMAT
2052                         && pixelformat.u1.dwRGBBitCount != DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount)
2053                     continue;
2054             }
2055
2056             if(!(Flags & DDEDM_REFRESHRATES))
2057             {
2058                 /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
2059                  * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
2060                  * to be reduced to a single unique result in such case.
2061                  */
2062                 BOOL found = FALSE;
2063                 unsigned i;
2064
2065                 for (i = 0; i < enum_mode_count; i++)
2066                 {
2067                     if (enum_modes[i].width == mode.width && enum_modes[i].height == mode.height
2068                             && enum_modes[i].format_id == mode.format_id)
2069                     {
2070                         found = TRUE;
2071                         break;
2072                     }
2073                 }
2074
2075                 if(found) continue;
2076             }
2077
2078             memset(&callback_sd, 0, sizeof(callback_sd));
2079             callback_sd.dwSize = sizeof(callback_sd);
2080             callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2081
2082             callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH|DDSD_REFRESHRATE;
2083             if (Flags & DDEDM_REFRESHRATES)
2084                 callback_sd.u2.dwRefreshRate = mode.refresh_rate;
2085
2086             callback_sd.dwWidth = mode.width;
2087             callback_sd.dwHeight = mode.height;
2088
2089             callback_sd.u4.ddpfPixelFormat=pixelformat;
2090
2091             /* Calc pitch and DWORD align like MSDN says */
2092             callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.width;
2093             callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;
2094
2095             TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
2096               callback_sd.u2.dwRefreshRate);
2097
2098             if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
2099             {
2100                 TRACE("Application asked to terminate the enumeration\n");
2101                 HeapFree(GetProcessHeap(), 0, enum_modes);
2102                 wined3d_mutex_unlock();
2103                 return DD_OK;
2104             }
2105
2106             if(!(Flags & DDEDM_REFRESHRATES))
2107             {
2108                 if (enum_mode_count == enum_mode_array_size)
2109                 {
2110                     struct wined3d_display_mode *new_enum_modes;
2111
2112                     enum_mode_array_size *= 2;
2113                     new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes,
2114                             sizeof(*new_enum_modes) * enum_mode_array_size);
2115                     if (!new_enum_modes)
2116                     {
2117                         ERR("Out of memory\n");
2118                         HeapFree(GetProcessHeap(), 0, enum_modes);
2119                         wined3d_mutex_unlock();
2120                         return DDERR_OUTOFMEMORY;
2121                     }
2122
2123                     enum_modes = new_enum_modes;
2124                 }
2125
2126                 enum_modes[enum_mode_count++] = mode;
2127             }
2128         }
2129     }
2130
2131     TRACE("End of enumeration\n");
2132     HeapFree(GetProcessHeap(), 0, enum_modes);
2133     wined3d_mutex_unlock();
2134
2135     return DD_OK;
2136 }
2137
2138 static HRESULT WINAPI ddraw4_EnumDisplayModes(IDirectDraw4 *iface, DWORD flags,
2139         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMMODESCALLBACK2 callback)
2140 {
2141     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2142
2143     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2144             iface, flags, surface_desc, context, callback);
2145
2146     return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, surface_desc, context, callback);
2147 }
2148
2149 static HRESULT WINAPI ddraw2_EnumDisplayModes(IDirectDraw2 *iface, DWORD flags,
2150         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2151 {
2152     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
2153     struct displaymodescallback_context cbcontext;
2154     DDSURFACEDESC2 surface_desc2;
2155
2156     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2157             iface, flags, surface_desc, context, callback);
2158
2159     cbcontext.func = callback;
2160     cbcontext.context = context;
2161
2162     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
2163     return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags,
2164             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumDisplayModesCallbackThunk);
2165 }
2166
2167 static HRESULT WINAPI ddraw1_EnumDisplayModes(IDirectDraw *iface, DWORD flags,
2168         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2169 {
2170     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
2171     struct displaymodescallback_context cbcontext;
2172     DDSURFACEDESC2 surface_desc2;
2173
2174     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2175             iface, flags, surface_desc, context, callback);
2176
2177     cbcontext.func = callback;
2178     cbcontext.context = context;
2179
2180     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
2181     return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags,
2182             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumDisplayModesCallbackThunk);
2183 }
2184
2185 /*****************************************************************************
2186  * IDirectDraw7::EvaluateMode
2187  *
2188  * Used with IDirectDraw7::StartModeTest to test video modes.
2189  * EvaluateMode is used to pass or fail a mode, and continue with the next
2190  * mode
2191  *
2192  * Params:
2193  *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
2194  *  Timeout: Returns the amount of seconds left before the mode would have
2195  *           been failed automatically
2196  *
2197  * Returns:
2198  *  This implementation always DD_OK, because it's a stub
2199  *
2200  *****************************************************************************/
2201 static HRESULT WINAPI ddraw7_EvaluateMode(IDirectDraw7 *iface, DWORD Flags, DWORD *Timeout)
2202 {
2203     FIXME("iface %p, flags %#x, timeout %p stub!\n", iface, Flags, Timeout);
2204
2205     /* When implementing this, implement it in WineD3D */
2206
2207     return DD_OK;
2208 }
2209
2210 /*****************************************************************************
2211  * IDirectDraw7::GetDeviceIdentifier
2212  *
2213  * Returns the device identifier, which gives information about the driver
2214  * Our device identifier is defined at the beginning of this file.
2215  *
2216  * Params:
2217  *  DDDI: Address for the returned structure
2218  *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
2219  *
2220  * Returns:
2221  *  On success it returns DD_OK
2222  *  DDERR_INVALIDPARAMS if DDDI is NULL
2223  *
2224  *****************************************************************************/
2225 static HRESULT WINAPI ddraw7_GetDeviceIdentifier(IDirectDraw7 *iface,
2226         DDDEVICEIDENTIFIER2 *DDDI, DWORD Flags)
2227 {
2228     TRACE("iface %p, device_identifier %p, flags %#x.\n", iface, DDDI, Flags);
2229
2230     if(!DDDI)
2231         return DDERR_INVALIDPARAMS;
2232
2233     /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
2234      * host adapter, if there's a secondary 3D adapter. This doesn't apply
2235      * to any modern hardware, nor is it interesting for Wine, so ignore it.
2236      * Size of DDDEVICEIDENTIFIER2 may be aligned to 8 bytes and thus 4
2237      * bytes too long. So only copy the relevant part of the structure
2238      */
2239
2240     memcpy(DDDI, &deviceidentifier, FIELD_OFFSET(DDDEVICEIDENTIFIER2, dwWHQLLevel) + sizeof(DWORD));
2241     return DD_OK;
2242 }
2243
2244 static HRESULT WINAPI ddraw4_GetDeviceIdentifier(IDirectDraw4 *iface,
2245         DDDEVICEIDENTIFIER *identifier, DWORD flags)
2246 {
2247     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2248     DDDEVICEIDENTIFIER2 identifier2;
2249     HRESULT hr;
2250
2251     TRACE("iface %p, identifier %p, flags %#x.\n", iface, identifier, flags);
2252
2253     hr = ddraw7_GetDeviceIdentifier(&This->IDirectDraw7_iface, &identifier2, flags);
2254     DDRAW_Convert_DDDEVICEIDENTIFIER_2_To_1(&identifier2, identifier);
2255
2256     return hr;
2257 }
2258
2259 /*****************************************************************************
2260  * IDirectDraw7::GetSurfaceFromDC
2261  *
2262  * Returns the Surface for a GDI device context handle.
2263  * Is this related to IDirectDrawSurface::GetDC ???
2264  *
2265  * Params:
2266  *  hdc: hdc to return the surface for
2267  *  Surface: Address to write the surface pointer to
2268  *
2269  * Returns:
2270  *  Always returns DD_OK because it's a stub
2271  *
2272  *****************************************************************************/
2273 static HRESULT WINAPI ddraw7_GetSurfaceFromDC(IDirectDraw7 *iface, HDC hdc,
2274         IDirectDrawSurface7 **Surface)
2275 {
2276     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
2277     struct wined3d_surface *wined3d_surface;
2278     HRESULT hr;
2279
2280     TRACE("iface %p, dc %p, surface %p.\n", iface, hdc, Surface);
2281
2282     if (!Surface) return E_INVALIDARG;
2283
2284     hr = wined3d_device_get_surface_from_dc(This->wined3d_device, hdc, &wined3d_surface);
2285     if (FAILED(hr))
2286     {
2287         TRACE("No surface found for dc %p.\n", hdc);
2288         *Surface = NULL;
2289         return DDERR_NOTFOUND;
2290     }
2291
2292     *Surface = wined3d_surface_get_parent(wined3d_surface);
2293     IDirectDrawSurface7_AddRef(*Surface);
2294     TRACE("Returning surface %p.\n", Surface);
2295     return DD_OK;
2296 }
2297
2298 static HRESULT WINAPI ddraw4_GetSurfaceFromDC(IDirectDraw4 *iface, HDC dc,
2299         IDirectDrawSurface4 **surface)
2300 {
2301     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2302     IDirectDrawSurface7 *surface7;
2303     IDirectDrawSurfaceImpl *surface_impl;
2304     HRESULT hr;
2305
2306     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2307
2308     if (!surface) return E_INVALIDARG;
2309
2310     hr = ddraw7_GetSurfaceFromDC(&This->IDirectDraw7_iface, dc, &surface7);
2311     if (FAILED(hr))
2312     {
2313         *surface = NULL;
2314         return hr;
2315     }
2316     surface_impl = impl_from_IDirectDrawSurface7(surface7);
2317     /* Tests say this is true */
2318     *surface = (IDirectDrawSurface4 *)&surface_impl->IDirectDrawSurface_iface;
2319     IDirectDrawSurface_AddRef(&surface_impl->IDirectDrawSurface_iface);
2320     IDirectDrawSurface7_Release(surface7);
2321
2322     return hr;
2323 }
2324
2325 /*****************************************************************************
2326  * IDirectDraw7::RestoreAllSurfaces
2327  *
2328  * Calls the restore method of all surfaces
2329  *
2330  * Params:
2331  *
2332  * Returns:
2333  *  Always returns DD_OK because it's a stub
2334  *
2335  *****************************************************************************/
2336 static HRESULT WINAPI ddraw7_RestoreAllSurfaces(IDirectDraw7 *iface)
2337 {
2338     FIXME("iface %p stub!\n", iface);
2339
2340     /* This isn't hard to implement: Enumerate all WineD3D surfaces,
2341      * get their parent and call their restore method. Do not implement
2342      * it in WineD3D, as restoring a surface means re-creating the
2343      * WineD3DDSurface
2344      */
2345     return DD_OK;
2346 }
2347
2348 static HRESULT WINAPI ddraw4_RestoreAllSurfaces(IDirectDraw4 *iface)
2349 {
2350     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2351
2352     TRACE("iface %p.\n", iface);
2353
2354     return ddraw7_RestoreAllSurfaces(&This->IDirectDraw7_iface);
2355 }
2356
2357 /*****************************************************************************
2358  * IDirectDraw7::StartModeTest
2359  *
2360  * Tests the specified video modes to update the system registry with
2361  * refresh rate information. StartModeTest starts the mode test,
2362  * EvaluateMode is used to fail or pass a mode. If EvaluateMode
2363  * isn't called within 15 seconds, the mode is failed automatically
2364  *
2365  * As refresh rates are handled by the X server, I don't think this
2366  * Method is important
2367  *
2368  * Params:
2369  *  Modes: An array of mode specifications
2370  *  NumModes: The number of modes in Modes
2371  *  Flags: Some flags...
2372  *
2373  * Returns:
2374  *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
2375  *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
2376  *  otherwise DD_OK
2377  *
2378  *****************************************************************************/
2379 static HRESULT WINAPI ddraw7_StartModeTest(IDirectDraw7 *iface, SIZE *Modes, DWORD NumModes, DWORD Flags)
2380 {
2381     FIXME("iface %p, modes %p, mode_count %u, flags %#x partial stub!\n",
2382             iface, Modes, NumModes, Flags);
2383
2384     /* This looks sane */
2385     if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;
2386
2387     /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
2388      * As it is not, DDERR_TESTFINISHED is returned
2389      * (hopefully that's correct
2390      *
2391     if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
2392      * well, that value doesn't (yet) exist in the wine headers, so ignore it
2393      */
2394
2395     return DD_OK;
2396 }
2397
2398 /*****************************************************************************
2399  * ddraw_create_surface
2400  *
2401  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
2402  * with the passed parameters.
2403  *
2404  * Params:
2405  *  DDSD: Description of the surface to create
2406  *  Surf: Address to store the interface pointer at
2407  *
2408  * Returns:
2409  *  DD_OK on success
2410  *
2411  *****************************************************************************/
2412 static HRESULT ddraw_create_surface(IDirectDrawImpl *This, DDSURFACEDESC2 *pDDSD,
2413         IDirectDrawSurfaceImpl **ppSurf, UINT level, UINT version)
2414 {
2415     HRESULT hr;
2416
2417     TRACE("ddraw %p, surface_desc %p, surface %p, level %u.\n",
2418             This, pDDSD, ppSurf, level);
2419
2420     if (TRACE_ON(ddraw))
2421     {
2422         TRACE(" (%p) Requesting surface desc :\n", This);
2423         DDRAW_dump_surface_desc(pDDSD);
2424     }
2425
2426     if ((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE) && DefaultSurfaceType != SURFACE_OPENGL)
2427     {
2428         WARN("The application requests a 3D capable surface, but a non-OpenGL surface type was set in the registry.\n");
2429         /* Do not fail surface creation, only fail 3D device creation. */
2430     }
2431
2432     /* Create the Surface object */
2433     *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
2434     if(!*ppSurf)
2435     {
2436         ERR("(%p) Error allocating memory for a surface\n", This);
2437         return DDERR_OUTOFVIDEOMEMORY;
2438     }
2439
2440     hr = ddraw_surface_init(*ppSurf, This, pDDSD, level, version);
2441     if (FAILED(hr))
2442     {
2443         WARN("Failed to initialize surface, hr %#x.\n", hr);
2444         HeapFree(GetProcessHeap(), 0, *ppSurf);
2445         return hr;
2446     }
2447
2448     /* Increase the surface counter, and attach the surface */
2449     list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
2450
2451     TRACE("Created surface %p.\n", *ppSurf);
2452
2453     return DD_OK;
2454 }
2455 /*****************************************************************************
2456  * CreateAdditionalSurfaces
2457  *
2458  * Creates a new mipmap chain.
2459  *
2460  * Params:
2461  *  root: Root surface to attach the newly created chain to
2462  *  count: number of surfaces to create
2463  *  DDSD: Description of the surface. Intentionally not a pointer to avoid side
2464  *        effects on the caller
2465  *  CubeFaceRoot: Whether the new surface is a root of a cube map face. This
2466  *                creates an additional surface without the mipmapping flags
2467  *
2468  *****************************************************************************/
2469 static HRESULT
2470 CreateAdditionalSurfaces(IDirectDrawImpl *This,
2471                          IDirectDrawSurfaceImpl *root,
2472                          UINT count,
2473                          DDSURFACEDESC2 DDSD,
2474                          BOOL CubeFaceRoot, UINT version)
2475 {
2476     UINT i, j, level = 0;
2477     HRESULT hr;
2478     IDirectDrawSurfaceImpl *last = root;
2479
2480     for(i = 0; i < count; i++)
2481     {
2482         IDirectDrawSurfaceImpl *object2 = NULL;
2483
2484         /* increase the mipmap level, but only if a mipmap is created
2485          * In this case, also halve the size
2486          */
2487         if(DDSD.ddsCaps.dwCaps & DDSCAPS_MIPMAP && !CubeFaceRoot)
2488         {
2489             level++;
2490             if(DDSD.dwWidth > 1) DDSD.dwWidth /= 2;
2491             if(DDSD.dwHeight > 1) DDSD.dwHeight /= 2;
2492             /* Set the mipmap sublevel flag according to msdn */
2493             DDSD.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2494         }
2495         else
2496         {
2497             DDSD.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2498         }
2499         CubeFaceRoot = FALSE;
2500
2501         hr = ddraw_create_surface(This, &DDSD, &object2, level, version);
2502         if(hr != DD_OK)
2503         {
2504             return hr;
2505         }
2506
2507         /* Add the new surface to the complex attachment array */
2508         for(j = 0; j < MAX_COMPLEX_ATTACHED; j++)
2509         {
2510             if(last->complex_array[j]) continue;
2511             last->complex_array[j] = object2;
2512             break;
2513         }
2514         last = object2;
2515
2516         /* Remove the (possible) back buffer cap from the new surface description,
2517          * because only one surface in the flipping chain is a back buffer, one
2518          * is a front buffer, the others are just primary surfaces.
2519          */
2520         DDSD.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2521     }
2522     return DD_OK;
2523 }
2524
2525 static HRESULT ddraw_attach_d3d_device(IDirectDrawImpl *ddraw,
2526         WINED3DPRESENT_PARAMETERS *presentation_parameters)
2527 {
2528     HWND window = presentation_parameters->hDeviceWindow;
2529     HRESULT hr;
2530
2531     TRACE("ddraw %p.\n", ddraw);
2532
2533     if (!window || window == GetDesktopWindow())
2534     {
2535         window = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "Hidden D3D Window",
2536                 WS_DISABLED, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
2537                 NULL, NULL, NULL, NULL);
2538         if (!window)
2539         {
2540             ERR("Failed to create window, last error %#x.\n", GetLastError());
2541             return E_FAIL;
2542         }
2543
2544         ShowWindow(window, SW_HIDE);   /* Just to be sure */
2545         WARN("No window for the Direct3DDevice, created hidden window %p.\n", window);
2546
2547         presentation_parameters->hDeviceWindow = window;
2548     }
2549     else
2550     {
2551         TRACE("Using existing window %p for Direct3D rendering.\n", window);
2552     }
2553     ddraw->d3d_window = window;
2554
2555     /* Set this NOW, otherwise creating the depth stencil surface will cause a
2556      * recursive loop until ram or emulated video memory is full. */
2557     ddraw->d3d_initialized = TRUE;
2558     hr = wined3d_device_init_3d(ddraw->wined3d_device, presentation_parameters);
2559     if (FAILED(hr))
2560     {
2561         ddraw->d3d_target = NULL;
2562         ddraw->d3d_initialized = FALSE;
2563         return hr;
2564     }
2565
2566     ddraw->declArraySize = 2;
2567     ddraw->decls = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw->decls) * ddraw->declArraySize);
2568     if (!ddraw->decls)
2569     {
2570         ERR("Error allocating an array for the converted vertex decls.\n");
2571         ddraw->declArraySize = 0;
2572         hr = wined3d_device_uninit_3d(ddraw->wined3d_device);
2573         return E_OUTOFMEMORY;
2574     }
2575
2576     TRACE("Successfully initialized 3D.\n");
2577
2578     return DD_OK;
2579 }
2580
2581 static HRESULT ddraw_create_swapchain(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *surface)
2582 {
2583     WINED3DPRESENT_PARAMETERS presentation_parameters;
2584     struct wined3d_display_mode mode;
2585     HRESULT hr = WINED3D_OK;
2586
2587     /* FIXME: wined3d_get_adapter_display_mode() would be more appropriate
2588      * here, since we don't actually have a swapchain yet, but
2589      * wined3d_device_get_display_mode() has some special handling for color
2590      * depth changes. */
2591     hr = wined3d_device_get_display_mode(ddraw->wined3d_device, 0, &mode);
2592     if (FAILED(hr))
2593     {
2594         ERR("Failed to get display mode.\n");
2595         return hr;
2596     }
2597
2598     memset(&presentation_parameters, 0, sizeof(presentation_parameters));
2599     presentation_parameters.BackBufferWidth = mode.width;
2600     presentation_parameters.BackBufferHeight = mode.height;
2601     presentation_parameters.BackBufferFormat = mode.format_id;
2602     presentation_parameters.SwapEffect = WINED3DSWAPEFFECT_COPY;
2603     presentation_parameters.hDeviceWindow = ddraw->dest_window;
2604     presentation_parameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2605
2606     /* If the implementation is OpenGL and there's no d3ddevice, attach a
2607      * d3ddevice. But attach the d3ddevice only if the currently created
2608      * surface was a primary surface (2D app in 3D mode) or a 3DDEVICE surface
2609      * (3D app). The only case I can think of where this doesn't apply is when
2610      * a 2D app was configured by the user to run with OpenGL and it didn't
2611      * create the render target as first surface. In this case the render
2612      * target creation will cause the 3D init. */
2613     if (DefaultSurfaceType == SURFACE_OPENGL)
2614     {
2615         hr = ddraw_attach_d3d_device(ddraw, &presentation_parameters);
2616     }
2617     else if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
2618     {
2619         hr = wined3d_device_init_gdi(ddraw->wined3d_device, &presentation_parameters);
2620         if (FAILED(hr))
2621             WARN("Failed to initialize GDI ddraw implementation, hr %#x.\n", hr);
2622     }
2623
2624     if (SUCCEEDED(hr))
2625     {
2626         if (FAILED(hr = wined3d_device_get_swapchain(ddraw->wined3d_device, 0, &ddraw->wined3d_swapchain)))
2627         {
2628             ERR("Failed to get swapchain, hr %#x.\n", hr);
2629             ddraw->wined3d_swapchain = NULL;
2630         }
2631     }
2632
2633     if (SUCCEEDED(hr))
2634         ddraw_set_swapchain_window(ddraw, ddraw->dest_window);
2635
2636     return hr;
2637 }
2638
2639 /*****************************************************************************
2640  * IDirectDraw7::CreateSurface
2641  *
2642  * Creates a new IDirectDrawSurface object and returns its interface.
2643  *
2644  * The surface connections with wined3d are a bit tricky. Basically it works
2645  * like this:
2646  *
2647  * |------------------------|               |-----------------|
2648  * | DDraw surface          |               | WineD3DSurface  |
2649  * |                        |               |                 |
2650  * |        WineD3DSurface  |-------------->|                 |
2651  * |        Child           |<------------->| Parent          |
2652  * |------------------------|               |-----------------|
2653  *
2654  * The DDraw surface is the parent of the wined3d surface, and it releases
2655  * the WineD3DSurface when the ddraw surface is destroyed.
2656  *
2657  * However, for all surfaces which can be in a container in WineD3D,
2658  * we have to do this. These surfaces are usually complex surfaces,
2659  * so this concerns primary surfaces with a front and a back buffer,
2660  * and textures.
2661  *
2662  * |------------------------|               |-----------------|
2663  * | DDraw surface          |               | Container       |
2664  * |                        |               |                 |
2665  * |                  Child |<------------->| Parent          |
2666  * |                Texture |<------------->|                 |
2667  * |         WineD3DSurface |<----|         |          Levels |<--|
2668  * | Complex connection     |     |         |                 |   |
2669  * |------------------------|     |         |-----------------|   |
2670  *  ^                             |                               |
2671  *  |                             |                               |
2672  *  |                             |                               |
2673  *  |    |------------------|     |         |-----------------|   |
2674  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2675  *  |    |                  |               |                 |   |
2676  *  |    |            Child |<------------->| Parent          |   |
2677  *  |    |                  |               |       Container |<--|
2678  *  |    |------------------|               |-----------------|   |
2679  *  |                                                             |
2680  *  |   |----------------------|                                  |
2681  *  |   | DDraw surface 2      |                                  |
2682  *  |   |                      |                                  |
2683  *  |<->| Complex root   Child |                                  |
2684  *  |   |              Texture |                                  |
2685  *  |   |       WineD3DSurface |<----|                            |
2686  *  |   |----------------------|     |                            |
2687  *  |                                |                            |
2688  *  |    |---------------------|     |      |-----------------|   |
2689  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2690  *  |    |                     |            |                 |   |
2691  *  |    |               Child |<---------->| Parent          |   |
2692  *  |    |---------------------|            |       Container |<--|
2693  *  |                                       |-----------------|   |
2694  *  |                                                             |
2695  *  |             ---More surfaces can follow---                  |
2696  *
2697  * The reason is that the IWineD3DSwapchain(render target container)
2698  * and the IWineD3DTexure(Texture container) release the parents
2699  * of their surface's children, but by releasing the complex root
2700  * the surfaces which are complexly attached to it are destroyed
2701  * too. See IDirectDrawSurface::Release for a more detailed
2702  * explanation.
2703  *
2704  * Params:
2705  *  DDSD: Description of the surface to create
2706  *  Surf: Address to store the interface pointer at
2707  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2708  *            aggregation, so it has to be NULL
2709  *
2710  * Returns:
2711  *  DD_OK on success
2712  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2713  *  DDERR_* if an error occurs
2714  *
2715  *****************************************************************************/
2716 static HRESULT CreateSurface(IDirectDrawImpl *ddraw, DDSURFACEDESC2 *DDSD,
2717         IDirectDrawSurfaceImpl **Surf, IUnknown *UnkOuter, UINT version)
2718 {
2719     IDirectDrawSurfaceImpl *object = NULL;
2720     struct wined3d_display_mode mode;
2721     HRESULT hr;
2722     LONG extra_surfaces = 0;
2723     DDSURFACEDESC2 desc2;
2724     const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
2725
2726     TRACE("ddraw %p, surface_desc %p, surface %p, outer_unknown %p.\n", ddraw, DDSD, Surf, UnkOuter);
2727
2728     /* Some checks before we start */
2729     if (TRACE_ON(ddraw))
2730     {
2731         TRACE(" (%p) Requesting surface desc :\n", ddraw);
2732         DDRAW_dump_surface_desc(DDSD);
2733     }
2734
2735     if (UnkOuter != NULL)
2736     {
2737         FIXME("(%p) : outer != NULL?\n", ddraw);
2738         return CLASS_E_NOAGGREGATION; /* unchecked */
2739     }
2740
2741     if (Surf == NULL)
2742     {
2743         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", ddraw);
2744         return E_POINTER; /* unchecked */
2745     }
2746
2747     if (!(DDSD->dwFlags & DDSD_CAPS))
2748     {
2749         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2750         DDSD->dwFlags |= DDSD_CAPS;
2751     }
2752
2753     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2754     {
2755         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2756         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2757     }
2758
2759     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2760     {
2761         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2762         WARN("(%p) Null surface pointer specified, ignore it!\n", ddraw);
2763         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2764     }
2765
2766     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2767        !(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
2768     {
2769         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n",
2770                 ddraw);
2771         *Surf = NULL;
2772         return DDERR_NOEXCLUSIVEMODE;
2773     }
2774
2775     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE))
2776     {
2777         WARN("Application wanted to create back buffer primary surface\n");
2778         return DDERR_INVALIDCAPS;
2779     }
2780
2781     if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
2782     {
2783         /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
2784         WARN("Application tries to put the surface in both system and video memory\n");
2785         *Surf = NULL;
2786         return DDERR_INVALIDCAPS;
2787     }
2788
2789     /* Check cube maps but only if the size includes them */
2790     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2791     {
2792         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
2793            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
2794         {
2795             WARN("Cube map faces requested without cube map flag\n");
2796             return DDERR_INVALIDCAPS;
2797         }
2798         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2799            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
2800         {
2801             WARN("Cube map without faces requested\n");
2802             return DDERR_INVALIDPARAMS;
2803         }
2804
2805         /* Quick tests confirm those can be created, but we don't do that yet */
2806         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2807            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
2808         {
2809             FIXME("Partial cube maps not supported yet\n");
2810         }
2811     }
2812
2813     /* According to the msdn this flag is ignored by CreateSurface */
2814     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2815         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2816
2817     /* Modify some flags */
2818     copy_to_surfacedesc2(&desc2, DDSD);
2819     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
2820
2821     /* Get the video mode from WineD3D - we will need it */
2822     hr = wined3d_device_get_display_mode(ddraw->wined3d_device, 0, &mode);
2823     if (FAILED(hr))
2824     {
2825         ERR("Failed to read display mode from wined3d\n");
2826         switch(ddraw->orig_bpp)
2827         {
2828             case 8:
2829                 mode.format_id = WINED3DFMT_P8_UINT;
2830                 break;
2831
2832             case 15:
2833                 mode.format_id = WINED3DFMT_B5G5R5X1_UNORM;
2834                 break;
2835
2836             case 16:
2837                 mode.format_id = WINED3DFMT_B5G6R5_UNORM;
2838                 break;
2839
2840             case 24:
2841                 mode.format_id = WINED3DFMT_B8G8R8_UNORM;
2842                 break;
2843
2844             case 32:
2845                 mode.format_id = WINED3DFMT_B8G8R8X8_UNORM;
2846                 break;
2847         }
2848         mode.width = ddraw->orig_width;
2849         mode.height = ddraw->orig_height;
2850     }
2851
2852     /* No pixelformat given? Use the current screen format */
2853     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
2854     {
2855         desc2.dwFlags |= DDSD_PIXELFORMAT;
2856         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
2857
2858         PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, mode.format_id);
2859     }
2860
2861     /* No Width or no Height? Use the original screen size
2862      */
2863     if(!(desc2.dwFlags & DDSD_WIDTH) ||
2864        !(desc2.dwFlags & DDSD_HEIGHT) )
2865     {
2866         /* Invalid for non-render targets */
2867         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
2868         {
2869             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
2870             *Surf = NULL;
2871             return DDERR_INVALIDPARAMS;
2872         }
2873
2874         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
2875         desc2.dwWidth = mode.width;
2876         desc2.dwHeight = mode.height;
2877     }
2878
2879     if (!desc2.dwWidth || !desc2.dwHeight)
2880         return DDERR_INVALIDPARAMS;
2881
2882     /* Mipmap count fixes */
2883     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2884     {
2885         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
2886         {
2887             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
2888             {
2889                 /* Mipmap count is given, should not be 0 */
2890                 if( desc2.u2.dwMipMapCount == 0 )
2891                     return DDERR_INVALIDPARAMS;
2892             }
2893             else
2894             {
2895                 /* Undocumented feature: Create sublevels until
2896                  * either the width or the height is 1
2897                  */
2898                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
2899                             desc2.dwWidth : desc2.dwHeight;
2900                 desc2.u2.dwMipMapCount = 0;
2901                 while( min )
2902                 {
2903                     desc2.u2.dwMipMapCount += 1;
2904                     min >>= 1;
2905                 }
2906             }
2907         }
2908         else
2909         {
2910             /* Not-complex mipmap -> Mipmapcount = 1 */
2911             desc2.u2.dwMipMapCount = 1;
2912         }
2913         extra_surfaces = desc2.u2.dwMipMapCount - 1;
2914
2915         /* There's a mipmap count in the created surface in any case */
2916         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
2917     }
2918     /* If no mipmap is given, the texture has only one level */
2919
2920     /* The first surface is a front buffer, the back buffer is created afterwards */
2921     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
2922     {
2923         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
2924     }
2925
2926     /* The root surface in a cube map is positive x */
2927     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2928     {
2929         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
2930         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
2931     }
2932
2933     /* Create the first surface */
2934     hr = ddraw_create_surface(ddraw, &desc2, &object, 0, version);
2935     if (FAILED(hr))
2936     {
2937         WARN("ddraw_create_surface failed, hr %#x.\n", hr);
2938         return hr;
2939     }
2940     object->is_complex_root = TRUE;
2941
2942     *Surf = object;
2943
2944     /* Create Additional surfaces if necessary
2945      * This applies to Primary surfaces which have a back buffer count
2946      * set, but not to mipmap textures. In case of Mipmap textures,
2947      * wineD3D takes care of the creation of additional surfaces
2948      */
2949     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
2950     {
2951         extra_surfaces = DDSD->dwBackBufferCount;
2952         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
2953         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
2954         desc2.dwBackBufferCount = 0;
2955     }
2956
2957     hr = DD_OK;
2958     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2959     {
2960         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
2961         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
2962         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
2963         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
2964         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
2965         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
2966         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
2967         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
2968         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
2969         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
2970         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
2971         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
2972         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
2973         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
2974         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE, version);
2975         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
2976         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
2977     }
2978
2979     hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces, desc2, FALSE, version);
2980     if(hr != DD_OK)
2981     {
2982         /* This destroys and possibly created surfaces too */
2983         if (version == 7)
2984             IDirectDrawSurface7_Release(&object->IDirectDrawSurface7_iface);
2985         else if (version == 4)
2986             IDirectDrawSurface4_Release(&object->IDirectDrawSurface4_iface);
2987         else
2988             IDirectDrawSurface_Release(&object->IDirectDrawSurface_iface);
2989
2990         return hr;
2991     }
2992
2993     if (!ddraw->d3d_initialized && desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE))
2994     {
2995         if (FAILED(hr = ddraw_create_swapchain(ddraw, object)))
2996         {
2997             IDirectDrawSurfaceImpl *release_surf;
2998             ERR("Failed to create swapchain, hr %#x.\n", hr);
2999             *Surf = NULL;
3000
3001             /* The earlier created surface structures are in an incomplete
3002              * state here. Wined3d holds the reference on the parents, and it
3003              * released them on the failure already. So the regular release
3004              * method implementation would fail on the attempt to destroy
3005              * either the parents or the swapchain. So free the surface here.
3006              * The surface structure here is a list, not a tree, because
3007              * onscreen targets cannot be cube textures. */
3008             while (object)
3009             {
3010                 release_surf = object;
3011                 object = object->complex_array[0];
3012                 ddraw_surface_destroy(release_surf);
3013             }
3014             return hr;
3015         }
3016
3017         if (DefaultSurfaceType == SURFACE_OPENGL)
3018             ddraw->d3d_target = ddraw->primary ? ddraw->primary : object;
3019     }
3020
3021     if (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
3022         ddraw->primary = object;
3023
3024     /* Create a WineD3DTexture if a texture was requested */
3025     if (desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
3026     {
3027         ddraw->tex_root = object;
3028         ddraw_surface_create_texture(object);
3029         ddraw->tex_root = NULL;
3030     }
3031
3032     return hr;
3033 }
3034
3035 static HRESULT WINAPI ddraw7_CreateSurface(IDirectDraw7 *iface, DDSURFACEDESC2 *surface_desc,
3036         IDirectDrawSurface7 **surface, IUnknown *outer_unknown)
3037 {
3038     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3039     IDirectDrawSurfaceImpl *impl;
3040     HRESULT hr;
3041
3042     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3043             iface, surface_desc, surface, outer_unknown);
3044
3045     wined3d_mutex_lock();
3046
3047     if (!(This->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3048     {
3049         WARN("Cooperative level not set.\n");
3050         wined3d_mutex_unlock();
3051         return DDERR_NOCOOPERATIVELEVELSET;
3052     }
3053
3054     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3055     {
3056         WARN("Application supplied invalid surface descriptor\n");
3057         wined3d_mutex_unlock();
3058         return DDERR_INVALIDPARAMS;
3059     }
3060
3061     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3062     {
3063         if (TRACE_ON(ddraw))
3064         {
3065             TRACE(" (%p) Requesting surface desc :\n", iface);
3066             DDRAW_dump_surface_desc(surface_desc);
3067         }
3068
3069         WARN("Application tried to create an explicit front or back buffer\n");
3070         wined3d_mutex_unlock();
3071         return DDERR_INVALIDCAPS;
3072     }
3073
3074     hr = CreateSurface(This, surface_desc, &impl, outer_unknown, 7);
3075     wined3d_mutex_unlock();
3076     if (FAILED(hr))
3077     {
3078         *surface = NULL;
3079         return hr;
3080     }
3081
3082     *surface = &impl->IDirectDrawSurface7_iface;
3083     IDirectDraw7_AddRef(iface);
3084     impl->ifaceToRelease = (IUnknown *)iface;
3085
3086     return hr;
3087 }
3088
3089 static HRESULT WINAPI ddraw4_CreateSurface(IDirectDraw4 *iface,
3090         DDSURFACEDESC2 *surface_desc, IDirectDrawSurface4 **surface, IUnknown *outer_unknown)
3091 {
3092     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3093     IDirectDrawSurfaceImpl *impl;
3094     HRESULT hr;
3095
3096     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3097             iface, surface_desc, surface, outer_unknown);
3098
3099     wined3d_mutex_lock();
3100
3101     if (!(This->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3102     {
3103         WARN("Cooperative level not set.\n");
3104         wined3d_mutex_unlock();
3105         return DDERR_NOCOOPERATIVELEVELSET;
3106     }
3107
3108     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3109     {
3110         WARN("Application supplied invalid surface descriptor\n");
3111         wined3d_mutex_unlock();
3112         return DDERR_INVALIDPARAMS;
3113     }
3114
3115     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3116     {
3117         if (TRACE_ON(ddraw))
3118         {
3119             TRACE(" (%p) Requesting surface desc :\n", iface);
3120             DDRAW_dump_surface_desc(surface_desc);
3121         }
3122
3123         WARN("Application tried to create an explicit front or back buffer\n");
3124         wined3d_mutex_unlock();
3125         return DDERR_INVALIDCAPS;
3126     }
3127
3128     hr = CreateSurface(This, surface_desc, &impl, outer_unknown, 4);
3129     wined3d_mutex_unlock();
3130     if (FAILED(hr))
3131     {
3132         *surface = NULL;
3133         return hr;
3134     }
3135
3136     *surface = &impl->IDirectDrawSurface4_iface;
3137     IDirectDraw4_AddRef(iface);
3138     impl->ifaceToRelease = (IUnknown *)iface;
3139
3140     return hr;
3141 }
3142
3143 static HRESULT WINAPI ddraw2_CreateSurface(IDirectDraw2 *iface,
3144         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3145 {
3146     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3147     IDirectDrawSurfaceImpl *impl;
3148     HRESULT hr;
3149     DDSURFACEDESC2 surface_desc2;
3150
3151     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3152             iface, surface_desc, surface, outer_unknown);
3153
3154     wined3d_mutex_lock();
3155
3156     if (!(This->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3157     {
3158         WARN("Cooperative level not set.\n");
3159         wined3d_mutex_unlock();
3160         return DDERR_NOCOOPERATIVELEVELSET;
3161     }
3162
3163     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3164     {
3165         WARN("Application supplied invalid surface descriptor\n");
3166         wined3d_mutex_unlock();
3167         return DDERR_INVALIDPARAMS;
3168     }
3169
3170     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3171     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3172     {
3173         if (TRACE_ON(ddraw))
3174         {
3175             TRACE(" (%p) Requesting surface desc :\n", iface);
3176             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3177         }
3178
3179         WARN("Application tried to create an explicit front or back buffer\n");
3180         wined3d_mutex_unlock();
3181         return DDERR_INVALIDCAPS;
3182     }
3183
3184     hr = CreateSurface(This, &surface_desc2, &impl, outer_unknown, 2);
3185     wined3d_mutex_unlock();
3186     if (FAILED(hr))
3187     {
3188         *surface = NULL;
3189         return hr;
3190     }
3191
3192     *surface = &impl->IDirectDrawSurface_iface;
3193     impl->ifaceToRelease = NULL;
3194
3195     return hr;
3196 }
3197
3198 static HRESULT WINAPI ddraw1_CreateSurface(IDirectDraw *iface,
3199         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3200 {
3201     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3202     IDirectDrawSurfaceImpl *impl;
3203     HRESULT hr;
3204     DDSURFACEDESC2 surface_desc2;
3205
3206     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3207             iface, surface_desc, surface, outer_unknown);
3208
3209     wined3d_mutex_lock();
3210
3211     if (!(This->cooperative_level & (DDSCL_NORMAL | DDSCL_EXCLUSIVE)))
3212     {
3213         WARN("Cooperative level not set.\n");
3214         wined3d_mutex_unlock();
3215         return DDERR_NOCOOPERATIVELEVELSET;
3216     }
3217
3218     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3219     {
3220         WARN("Application supplied invalid surface descriptor\n");
3221         wined3d_mutex_unlock();
3222         return DDERR_INVALIDPARAMS;
3223     }
3224
3225     /* Remove front buffer flag, this causes failure in v7, and its added to normal
3226      * primaries anyway. */
3227     surface_desc->ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER;
3228     DDSD_to_DDSD2(surface_desc, &surface_desc2);
3229     hr = CreateSurface(This, &surface_desc2, &impl, outer_unknown, 1);
3230     wined3d_mutex_unlock();
3231     if (FAILED(hr))
3232     {
3233         *surface = NULL;
3234         return hr;
3235     }
3236
3237     *surface = &impl->IDirectDrawSurface_iface;
3238     impl->ifaceToRelease = NULL;
3239
3240     return hr;
3241 }
3242
3243 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
3244 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
3245
3246 static BOOL
3247 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
3248                                     const DDPIXELFORMAT *provided)
3249 {
3250     /* Some flags must be present in both or neither for a match. */
3251     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
3252         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
3253         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
3254
3255     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3256         return FALSE;
3257
3258     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
3259         return FALSE;
3260
3261     if (requested->dwFlags & DDPF_FOURCC)
3262         if (requested->dwFourCC != provided->dwFourCC)
3263             return FALSE;
3264
3265     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
3266                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3267         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
3268             return FALSE;
3269
3270     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3271                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3272         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
3273             return FALSE;
3274
3275     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
3276         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
3277             return FALSE;
3278
3279     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
3280     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3281                               |DDPF_BUMPDUDV))
3282         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
3283             return FALSE;
3284
3285     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
3286         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
3287             return FALSE;
3288
3289     return TRUE;
3290 }
3291
3292 static BOOL ddraw_match_surface_desc(const DDSURFACEDESC2 *requested, const DDSURFACEDESC2 *provided)
3293 {
3294     struct compare_info
3295     {
3296         DWORD flag;
3297         ptrdiff_t offset;
3298         size_t size;
3299     };
3300
3301 #define CMP(FLAG, FIELD)                                \
3302         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
3303           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
3304
3305     static const struct compare_info compare[] =
3306     {
3307         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
3308         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
3309         CMP(CAPS, ddsCaps),
3310         CMP(CKDESTBLT, ddckCKDestBlt),
3311         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
3312         CMP(CKSRCBLT, ddckCKSrcBlt),
3313         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
3314         CMP(HEIGHT, dwHeight),
3315         CMP(LINEARSIZE, u1 /* dwLinearSize */),
3316         CMP(LPSURFACE, lpSurface),
3317         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
3318         CMP(PITCH, u1 /* lPitch */),
3319         /* PIXELFORMAT: manual */
3320         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
3321         CMP(TEXTURESTAGE, dwTextureStage),
3322         CMP(WIDTH, dwWidth),
3323         /* ZBUFFERBITDEPTH: "obsolete" */
3324     };
3325
3326 #undef CMP
3327
3328     unsigned int i;
3329
3330     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3331         return FALSE;
3332
3333     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
3334     {
3335         if (requested->dwFlags & compare[i].flag
3336             && memcmp((const char *)provided + compare[i].offset,
3337                       (const char *)requested + compare[i].offset,
3338                       compare[i].size) != 0)
3339             return FALSE;
3340     }
3341
3342     if (requested->dwFlags & DDSD_PIXELFORMAT)
3343     {
3344         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
3345                                                 &provided->u4.ddpfPixelFormat))
3346             return FALSE;
3347     }
3348
3349     return TRUE;
3350 }
3351
3352 #undef DDENUMSURFACES_SEARCHTYPE
3353 #undef DDENUMSURFACES_MATCHTYPE
3354
3355 struct surfacescallback2_context
3356 {
3357     LPDDENUMSURFACESCALLBACK2 func;
3358     void *context;
3359 };
3360
3361 struct surfacescallback_context
3362 {
3363     LPDDENUMSURFACESCALLBACK func;
3364     void *context;
3365 };
3366
3367 static HRESULT CALLBACK EnumSurfacesCallback2Thunk(IDirectDrawSurface7 *surface,
3368         DDSURFACEDESC2 *surface_desc, void *context)
3369 {
3370     IDirectDrawSurfaceImpl *surface_impl = impl_from_IDirectDrawSurface7(surface);
3371     struct surfacescallback2_context *cbcontext = context;
3372
3373     IDirectDrawSurface4_AddRef(&surface_impl->IDirectDrawSurface4_iface);
3374     IDirectDrawSurface7_Release(surface);
3375
3376     return cbcontext->func(&surface_impl->IDirectDrawSurface4_iface,
3377             surface_desc, cbcontext->context);
3378 }
3379
3380 static HRESULT CALLBACK EnumSurfacesCallbackThunk(IDirectDrawSurface7 *surface,
3381         DDSURFACEDESC2 *surface_desc, void *context)
3382 {
3383     IDirectDrawSurfaceImpl *surface_impl = impl_from_IDirectDrawSurface7(surface);
3384     struct surfacescallback_context *cbcontext = context;
3385
3386     IDirectDrawSurface_AddRef(&surface_impl->IDirectDrawSurface_iface);
3387     IDirectDrawSurface7_Release(surface);
3388
3389     return cbcontext->func(&surface_impl->IDirectDrawSurface_iface,
3390             (DDSURFACEDESC *)surface_desc, cbcontext->context);
3391 }
3392
3393 /*****************************************************************************
3394  * IDirectDraw7::EnumSurfaces
3395  *
3396  * Loops through all surfaces attached to this device and calls the
3397  * application callback. This can't be relayed to WineD3DDevice,
3398  * because some WineD3DSurfaces' parents are IParent objects
3399  *
3400  * Params:
3401  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
3402  *  DDSD: Description to filter for
3403  *  Context: Application-provided pointer, it's passed unmodified to the
3404  *           Callback function
3405  *  Callback: Address to call for each surface
3406  *
3407  * Returns:
3408  *  DDERR_INVALIDPARAMS if the callback is NULL
3409  *  DD_OK on success
3410  *
3411  *****************************************************************************/
3412 static HRESULT WINAPI ddraw7_EnumSurfaces(IDirectDraw7 *iface, DWORD Flags,
3413         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMSURFACESCALLBACK7 Callback)
3414 {
3415     /* The surface enumeration is handled by WineDDraw,
3416      * because it keeps track of all surfaces attached to
3417      * it. The filtering is done by our callback function,
3418      * because WineDDraw doesn't handle ddraw-like surface
3419      * caps structures
3420      */
3421     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3422     IDirectDrawSurfaceImpl *surf;
3423     BOOL all, nomatch;
3424     DDSURFACEDESC2 desc;
3425     struct list *entry, *entry2;
3426
3427     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3428             iface, Flags, DDSD, Context, Callback);
3429
3430     all = Flags & DDENUMSURFACES_ALL;
3431     nomatch = Flags & DDENUMSURFACES_NOMATCH;
3432
3433     if (!Callback)
3434         return DDERR_INVALIDPARAMS;
3435
3436     wined3d_mutex_lock();
3437
3438     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
3439     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
3440     {
3441         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3442         if (all || (nomatch != ddraw_match_surface_desc(DDSD, &surf->surface_desc)))
3443         {
3444             TRACE("Enumerating surface %p.\n", surf);
3445             desc = surf->surface_desc;
3446             IDirectDrawSurface7_AddRef(&surf->IDirectDrawSurface7_iface);
3447             if (Callback(&surf->IDirectDrawSurface7_iface, &desc, Context) != DDENUMRET_OK)
3448             {
3449                 wined3d_mutex_unlock();
3450                 return DD_OK;
3451             }
3452         }
3453     }
3454
3455     wined3d_mutex_unlock();
3456
3457     return DD_OK;
3458 }
3459
3460 static HRESULT WINAPI ddraw4_EnumSurfaces(IDirectDraw4 *iface, DWORD flags,
3461         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMSURFACESCALLBACK2 callback)
3462 {
3463     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3464     struct surfacescallback2_context cbcontext;
3465
3466     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3467             iface, flags, surface_desc, context, callback);
3468
3469     cbcontext.func = callback;
3470     cbcontext.context = context;
3471
3472     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, surface_desc,
3473             &cbcontext, EnumSurfacesCallback2Thunk);
3474 }
3475
3476 static HRESULT WINAPI ddraw2_EnumSurfaces(IDirectDraw2 *iface, DWORD flags,
3477         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3478 {
3479     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3480     struct surfacescallback_context cbcontext;
3481     DDSURFACEDESC2 surface_desc2;
3482
3483     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3484             iface, flags, surface_desc, context, callback);
3485
3486     cbcontext.func = callback;
3487     cbcontext.context = context;
3488
3489     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
3490     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags,
3491             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumSurfacesCallbackThunk);
3492 }
3493
3494 static HRESULT WINAPI ddraw1_EnumSurfaces(IDirectDraw *iface, DWORD flags,
3495         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3496 {
3497     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3498     struct surfacescallback_context cbcontext;
3499     DDSURFACEDESC2 surface_desc2;
3500
3501     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3502             iface, flags, surface_desc, context, callback);
3503
3504     cbcontext.func = callback;
3505     cbcontext.context = context;
3506
3507     if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
3508     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags,
3509             surface_desc ? &surface_desc2 : NULL, &cbcontext, EnumSurfacesCallbackThunk);
3510 }
3511
3512 /*****************************************************************************
3513  * DirectDrawCreateClipper (DDRAW.@)
3514  *
3515  * Creates a new IDirectDrawClipper object.
3516  *
3517  * Params:
3518  *  Clipper: Address to write the interface pointer to
3519  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3520  *            NULL
3521  *
3522  * Returns:
3523  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3524  *  E_OUTOFMEMORY if allocating the object failed
3525  *
3526  *****************************************************************************/
3527 HRESULT WINAPI
3528 DirectDrawCreateClipper(DWORD Flags,
3529                         LPDIRECTDRAWCLIPPER *Clipper,
3530                         IUnknown *UnkOuter)
3531 {
3532     IDirectDrawClipperImpl* object;
3533     HRESULT hr;
3534
3535     TRACE("flags %#x, clipper %p, outer_unknown %p.\n",
3536             Flags, Clipper, UnkOuter);
3537
3538     if (UnkOuter)
3539         return CLASS_E_NOAGGREGATION;
3540
3541     wined3d_mutex_lock();
3542
3543     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3544                      sizeof(IDirectDrawClipperImpl));
3545     if (object == NULL)
3546     {
3547         wined3d_mutex_unlock();
3548         return E_OUTOFMEMORY;
3549     }
3550
3551     hr = ddraw_clipper_init(object);
3552     if (FAILED(hr))
3553     {
3554         WARN("Failed to initialize clipper, hr %#x.\n", hr);
3555         HeapFree(GetProcessHeap(), 0, object);
3556         wined3d_mutex_unlock();
3557         return hr;
3558     }
3559
3560     TRACE("Created clipper %p.\n", object);
3561     *Clipper = &object->IDirectDrawClipper_iface;
3562     wined3d_mutex_unlock();
3563
3564     return DD_OK;
3565 }
3566
3567 /*****************************************************************************
3568  * IDirectDraw7::CreateClipper
3569  *
3570  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3571  *
3572  *****************************************************************************/
3573 static HRESULT WINAPI ddraw7_CreateClipper(IDirectDraw7 *iface, DWORD Flags,
3574         IDirectDrawClipper **Clipper, IUnknown *UnkOuter)
3575 {
3576     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3577             iface, Flags, Clipper, UnkOuter);
3578
3579     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3580 }
3581
3582 static HRESULT WINAPI ddraw4_CreateClipper(IDirectDraw4 *iface, DWORD flags,
3583         IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3584 {
3585     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3586
3587     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3588             iface, flags, clipper, outer_unknown);
3589
3590     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3591 }
3592
3593 static HRESULT WINAPI ddraw2_CreateClipper(IDirectDraw2 *iface,
3594         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3595 {
3596     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3597
3598     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3599             iface, flags, clipper, outer_unknown);
3600
3601     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3602 }
3603
3604 static HRESULT WINAPI ddraw1_CreateClipper(IDirectDraw *iface,
3605         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3606 {
3607     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3608
3609     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3610             iface, flags, clipper, outer_unknown);
3611
3612     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3613 }
3614
3615 /*****************************************************************************
3616  * IDirectDraw7::CreatePalette
3617  *
3618  * Creates a new IDirectDrawPalette object
3619  *
3620  * Params:
3621  *  Flags: The flags for the new clipper
3622  *  ColorTable: Color table to assign to the new clipper
3623  *  Palette: Address to write the interface pointer to
3624  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3625  *            NULL
3626  *
3627  * Returns:
3628  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3629  *  E_OUTOFMEMORY if allocating the object failed
3630  *
3631  *****************************************************************************/
3632 static HRESULT WINAPI ddraw7_CreatePalette(IDirectDraw7 *iface, DWORD Flags,
3633         PALETTEENTRY *ColorTable, IDirectDrawPalette **Palette, IUnknown *pUnkOuter)
3634 {
3635     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3636     IDirectDrawPaletteImpl *object;
3637     HRESULT hr;
3638
3639     TRACE("iface %p, flags %#x, color_table %p, palette %p, outer_unknown %p.\n",
3640             iface, Flags, ColorTable, Palette, pUnkOuter);
3641
3642     if (pUnkOuter)
3643         return CLASS_E_NOAGGREGATION;
3644
3645     wined3d_mutex_lock();
3646
3647     /* The refcount test shows that a cooplevel is required for this */
3648     if(!This->cooperative_level)
3649     {
3650         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
3651         wined3d_mutex_unlock();
3652         return DDERR_NOCOOPERATIVELEVELSET;
3653     }
3654
3655     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
3656     if(!object)
3657     {
3658         ERR("Out of memory when allocating memory for a palette implementation\n");
3659         wined3d_mutex_unlock();
3660         return E_OUTOFMEMORY;
3661     }
3662
3663     hr = ddraw_palette_init(object, This, Flags, ColorTable);
3664     if (FAILED(hr))
3665     {
3666         WARN("Failed to initialize palette, hr %#x.\n", hr);
3667         HeapFree(GetProcessHeap(), 0, object);
3668         wined3d_mutex_unlock();
3669         return hr;
3670     }
3671
3672     TRACE("Created palette %p.\n", object);
3673     *Palette = &object->IDirectDrawPalette_iface;
3674     wined3d_mutex_unlock();
3675
3676     return DD_OK;
3677 }
3678
3679 static HRESULT WINAPI ddraw4_CreatePalette(IDirectDraw4 *iface, DWORD flags, PALETTEENTRY *entries,
3680         IDirectDrawPalette **palette, IUnknown *outer_unknown)
3681 {
3682     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3683     HRESULT hr;
3684
3685     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3686             iface, flags, entries, palette, outer_unknown);
3687
3688     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3689     if (SUCCEEDED(hr) && *palette)
3690     {
3691         IDirectDrawPaletteImpl *impl = impl_from_IDirectDrawPalette(*palette);
3692         IDirectDraw7_Release(&This->IDirectDraw7_iface);
3693         IDirectDraw4_AddRef(iface);
3694         impl->ifaceToRelease = (IUnknown *)iface;
3695     }
3696     return hr;
3697 }
3698
3699 static HRESULT WINAPI ddraw2_CreatePalette(IDirectDraw2 *iface, DWORD flags,
3700         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3701 {
3702     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3703     HRESULT hr;
3704
3705     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3706             iface, flags, entries, palette, outer_unknown);
3707
3708     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3709     if (SUCCEEDED(hr) && *palette)
3710     {
3711         IDirectDrawPaletteImpl *impl = impl_from_IDirectDrawPalette(*palette);
3712         IDirectDraw7_Release(&This->IDirectDraw7_iface);
3713         impl->ifaceToRelease = NULL;
3714     }
3715
3716     return hr;
3717 }
3718
3719 static HRESULT WINAPI ddraw1_CreatePalette(IDirectDraw *iface, DWORD flags,
3720         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3721 {
3722     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3723     HRESULT hr;
3724
3725     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3726             iface, flags, entries, palette, outer_unknown);
3727
3728     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
3729     if (SUCCEEDED(hr) && *palette)
3730     {
3731         IDirectDrawPaletteImpl *impl = impl_from_IDirectDrawPalette(*palette);
3732         IDirectDraw7_Release(&This->IDirectDraw7_iface);
3733         impl->ifaceToRelease = NULL;
3734     }
3735
3736     return hr;
3737 }
3738
3739 /*****************************************************************************
3740  * IDirectDraw7::DuplicateSurface
3741  *
3742  * Duplicates a surface. The surface memory points to the same memory as
3743  * the original surface, and it's released when the last surface referencing
3744  * it is released. I guess that's beyond Wine's surface management right now
3745  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
3746  * test application to implement this)
3747  *
3748  * Params:
3749  *  Src: Address of the source surface
3750  *  Dest: Address to write the new surface pointer to
3751  *
3752  * Returns:
3753  *  See IDirectDraw7::CreateSurface
3754  *
3755  *****************************************************************************/
3756 static HRESULT WINAPI ddraw7_DuplicateSurface(IDirectDraw7 *iface,
3757         IDirectDrawSurface7 *Src, IDirectDrawSurface7 **Dest)
3758 {
3759     IDirectDrawSurfaceImpl *Surf = unsafe_impl_from_IDirectDrawSurface7(Src);
3760
3761     FIXME("iface %p, src %p, dst %p partial stub!\n", iface, Src, Dest);
3762
3763     /* For now, simply create a new, independent surface */
3764     return IDirectDraw7_CreateSurface(iface,
3765                                       &Surf->surface_desc,
3766                                       Dest,
3767                                       NULL);
3768 }
3769
3770 static HRESULT WINAPI ddraw4_DuplicateSurface(IDirectDraw4 *iface, IDirectDrawSurface4 *src,
3771         IDirectDrawSurface4 **dst)
3772 {
3773     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3774     IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface4(src);
3775     IDirectDrawSurface7 *dst7;
3776     IDirectDrawSurfaceImpl *dst_impl;
3777     HRESULT hr;
3778
3779     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3780     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
3781             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
3782     if (FAILED(hr))
3783     {
3784         *dst = NULL;
3785         return hr;
3786     }
3787     dst_impl = impl_from_IDirectDrawSurface7(dst7);
3788     *dst = &dst_impl->IDirectDrawSurface4_iface;
3789     IDirectDrawSurface4_AddRef(*dst);
3790     IDirectDrawSurface7_Release(dst7);
3791
3792     return hr;
3793 }
3794
3795 static HRESULT WINAPI ddraw2_DuplicateSurface(IDirectDraw2 *iface,
3796         IDirectDrawSurface *src, IDirectDrawSurface **dst)
3797 {
3798     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3799     IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface(src);
3800     IDirectDrawSurface7 *dst7;
3801     IDirectDrawSurfaceImpl *dst_impl;
3802     HRESULT hr;
3803
3804     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3805     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
3806             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
3807     if (FAILED(hr))
3808         return hr;
3809     dst_impl = impl_from_IDirectDrawSurface7(dst7);
3810     *dst = &dst_impl->IDirectDrawSurface_iface;
3811     IDirectDrawSurface_AddRef(*dst);
3812     IDirectDrawSurface7_Release(dst7);
3813
3814     return hr;
3815 }
3816
3817 static HRESULT WINAPI ddraw1_DuplicateSurface(IDirectDraw *iface, IDirectDrawSurface *src,
3818         IDirectDrawSurface **dst)
3819 {
3820     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3821     IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface(src);
3822     IDirectDrawSurface7 *dst7;
3823     IDirectDrawSurfaceImpl *dst_impl;
3824     HRESULT hr;
3825
3826     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3827     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
3828             src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
3829     if (FAILED(hr))
3830         return hr;
3831     dst_impl = impl_from_IDirectDrawSurface7(dst7);
3832     *dst = &dst_impl->IDirectDrawSurface_iface;
3833     IDirectDrawSurface_AddRef(*dst);
3834     IDirectDrawSurface7_Release(dst7);
3835
3836     return hr;
3837 }
3838
3839 /*****************************************************************************
3840  * IDirect3D7::EnumDevices
3841  *
3842  * The EnumDevices method for IDirect3D7. It enumerates all supported
3843  * D3D7 devices. Currently the T&L, HAL and RGB devices are enumerated.
3844  *
3845  * Params:
3846  *  callback: Function to call for each enumerated device
3847  *  context: Pointer to pass back to the app
3848  *
3849  * Returns:
3850  *  D3D_OK, or the return value of the GetCaps call
3851  *
3852  *****************************************************************************/
3853 static HRESULT WINAPI d3d7_EnumDevices(IDirect3D7 *iface, LPD3DENUMDEVICESCALLBACK7 callback, void *context)
3854 {
3855     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
3856     D3DDEVICEDESC7 device_desc7;
3857     D3DDEVICEDESC device_desc1;
3858     HRESULT hr;
3859     size_t i;
3860
3861     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
3862
3863     if (!callback)
3864         return DDERR_INVALIDPARAMS;
3865
3866     wined3d_mutex_lock();
3867
3868     hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
3869     if (hr != D3D_OK)
3870     {
3871         wined3d_mutex_unlock();
3872         return hr;
3873     }
3874
3875     for (i = 0; i < sizeof(device_list7)/sizeof(device_list7[0]); i++)
3876     {
3877         HRESULT ret;
3878
3879         device_desc7.deviceGUID = *device_list7[i].device_guid;
3880         ret = callback(device_list7[i].interface_name, device_list7[i].device_name, &device_desc7, context);
3881         if (ret != DDENUMRET_OK)
3882         {
3883             TRACE("Application cancelled the enumeration.\n");
3884             wined3d_mutex_unlock();
3885             return D3D_OK;
3886         }
3887     }
3888
3889     TRACE("End of enumeration.\n");
3890
3891     wined3d_mutex_unlock();
3892
3893     return D3D_OK;
3894 }
3895
3896 /*****************************************************************************
3897  * IDirect3D3::EnumDevices
3898  *
3899  * Enumerates all supported Direct3DDevice interfaces. This is the
3900  * implementation for Direct3D 1 to Direc3D 3, Version 7 has its own.
3901  *
3902  * Version 1, 2 and 3
3903  *
3904  * Params:
3905  *  callback: Application-provided routine to call for each enumerated device
3906  *  Context: Pointer to pass to the callback
3907  *
3908  * Returns:
3909  *  D3D_OK on success,
3910  *  The result of IDirect3DImpl_GetCaps if it failed
3911  *
3912  *****************************************************************************/
3913 static HRESULT WINAPI d3d3_EnumDevices(IDirect3D3 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
3914 {
3915     static CHAR wined3d_description[] = "Wine D3DDevice using WineD3D and OpenGL";
3916
3917     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
3918     D3DDEVICEDESC device_desc1, hal_desc, hel_desc;
3919     D3DDEVICEDESC7 device_desc7;
3920     HRESULT hr;
3921
3922     /* Some games (Motoracer 2 demo) have the bad idea to modify the device
3923      * name string. Let's put the string in a sufficiently sized array in
3924      * writable memory. */
3925     char device_name[50];
3926     strcpy(device_name,"Direct3D HEL");
3927
3928     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
3929
3930     if (!callback)
3931         return DDERR_INVALIDPARAMS;
3932
3933     wined3d_mutex_lock();
3934
3935     hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
3936     if (hr != D3D_OK)
3937     {
3938         wined3d_mutex_unlock();
3939         return hr;
3940     }
3941
3942     /* Do I have to enumerate the reference id? Note from old d3d7:
3943      * "It seems that enumerating the reference IID on Direct3D 1 games
3944      * (AvP / Motoracer2) breaks them". So do not enumerate this iid in V1
3945      *
3946      * There's a registry key HKLM\Software\Microsoft\Direct3D\Drivers,
3947      * EnumReference which enables / disables enumerating the reference
3948      * rasterizer. It's a DWORD, 0 means disabled, 2 means enabled. The
3949      * enablerefrast.reg and disablerefrast.reg files in the DirectX 7.0 sdk
3950      * demo directory suggest this.
3951      *
3952      * Some games(GTA 2) seem to use the second enumerated device, so I have
3953      * to enumerate at least 2 devices. So enumerate the reference device to
3954      * have 2 devices.
3955      *
3956      * Other games (Rollcage) tell emulation and hal device apart by certain
3957      * flags. Rollcage expects D3DPTEXTURECAPS_POW2 to be set (yeah, it is a
3958      * limitation flag), and it refuses all devices that have the perspective
3959      * flag set. This way it refuses the emulation device, and HAL devices
3960      * never have POW2 unset in d3d7 on windows. */
3961     if (This->d3dversion != 1)
3962     {
3963         static CHAR reference_description[] = "RGB Direct3D emulation";
3964
3965         TRACE("Enumerating WineD3D D3DDevice interface.\n");
3966         hal_desc = device_desc1;
3967         hel_desc = device_desc1;
3968         /* The rgb device has the pow2 flag set in the hel caps, but not in the hal caps. */
3969         hal_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3970                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3971         hal_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3972                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3973         /* RGB, RAMP and MMX devices have a HAL dcmColorModel of 0 */
3974         hal_desc.dcmColorModel = 0;
3975
3976         hr = callback((GUID *)&IID_IDirect3DRGBDevice, reference_description,
3977                 device_name, &hal_desc, &hel_desc, context);
3978         if (hr != D3DENUMRET_OK)
3979         {
3980             TRACE("Application cancelled the enumeration.\n");
3981             wined3d_mutex_unlock();
3982             return D3D_OK;
3983         }
3984     }
3985
3986     strcpy(device_name,"Direct3D HAL");
3987
3988     TRACE("Enumerating HAL Direct3D device.\n");
3989     hal_desc = device_desc1;
3990     hel_desc = device_desc1;
3991
3992     /* The hal device does not have the pow2 flag set in hel, but in hal. */
3993     hel_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3994             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3995     hel_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
3996             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
3997     /* HAL devices have a HEL dcmColorModel of 0 */
3998     hel_desc.dcmColorModel = 0;
3999
4000     hr = callback((GUID *)&IID_IDirect3DHALDevice, wined3d_description,
4001             device_name, &hal_desc, &hel_desc, context);
4002     if (hr != D3DENUMRET_OK)
4003     {
4004         TRACE("Application cancelled the enumeration.\n");
4005         wined3d_mutex_unlock();
4006         return D3D_OK;
4007     }
4008
4009     TRACE("End of enumeration.\n");
4010
4011     wined3d_mutex_unlock();
4012
4013     return D3D_OK;
4014 }
4015
4016 static HRESULT WINAPI d3d2_EnumDevices(IDirect3D2 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4017 {
4018     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4019
4020     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4021
4022     return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4023 }
4024
4025 static HRESULT WINAPI d3d1_EnumDevices(IDirect3D *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4026 {
4027     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4028
4029     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4030
4031     return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4032 }
4033
4034 /*****************************************************************************
4035  * IDirect3D3::CreateLight
4036  *
4037  * Creates an IDirect3DLight interface. This interface is used in
4038  * Direct3D3 or earlier for lighting. In Direct3D7 it has been replaced
4039  * by the DIRECT3DLIGHT7 structure. Wine's Direct3DLight implementation
4040  * uses the IDirect3DDevice7 interface with D3D7 lights.
4041  *
4042  * Version 1, 2 and 3
4043  *
4044  * Params:
4045  *  light: Address to store the new interface pointer
4046  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4047  *                 Must be NULL
4048  *
4049  * Returns:
4050  *  D3D_OK on success
4051  *  DDERR_OUTOFMEMORY if memory allocation failed
4052  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4053  *
4054  *****************************************************************************/
4055 static HRESULT WINAPI d3d3_CreateLight(IDirect3D3 *iface, IDirect3DLight **light,
4056         IUnknown *outer_unknown)
4057 {
4058     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4059     IDirect3DLightImpl *object;
4060
4061     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4062
4063     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4064
4065     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4066     if (!object)
4067     {
4068         ERR("Failed to allocate light memory.\n");
4069         return DDERR_OUTOFMEMORY;
4070     }
4071
4072     d3d_light_init(object, This);
4073
4074     TRACE("Created light %p.\n", object);
4075     *light = &object->IDirect3DLight_iface;
4076
4077     return D3D_OK;
4078 }
4079
4080 static HRESULT WINAPI d3d2_CreateLight(IDirect3D2 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4081 {
4082     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4083
4084     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4085
4086     return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4087 }
4088
4089 static HRESULT WINAPI d3d1_CreateLight(IDirect3D *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4090 {
4091     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4092
4093     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4094
4095     return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4096 }
4097
4098 /*****************************************************************************
4099  * IDirect3D3::CreateMaterial
4100  *
4101  * Creates an IDirect3DMaterial interface. This interface is used by Direct3D3
4102  * and older versions. The IDirect3DMaterial implementation wraps its
4103  * functionality to IDirect3DDevice7::SetMaterial and friends.
4104  *
4105  * Version 1, 2 and 3
4106  *
4107  * Params:
4108  *  material: Address to store the new interface's pointer to
4109  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4110  *                 Must be NULL
4111  *
4112  * Returns:
4113  *  D3D_OK on success
4114  *  DDERR_OUTOFMEMORY if memory allocation failed
4115  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4116  *
4117  *****************************************************************************/
4118 static HRESULT WINAPI d3d3_CreateMaterial(IDirect3D3 *iface, IDirect3DMaterial3 **material,
4119         IUnknown *outer_unknown)
4120 {
4121     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4122     IDirect3DMaterialImpl *object;
4123
4124     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4125
4126     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4127
4128     object = d3d_material_create(This);
4129     if (!object)
4130     {
4131         ERR("Failed to allocate material memory.\n");
4132         return DDERR_OUTOFMEMORY;
4133     }
4134
4135     TRACE("Created material %p.\n", object);
4136     *material = &object->IDirect3DMaterial3_iface;
4137
4138     return D3D_OK;
4139 }
4140
4141 static HRESULT WINAPI d3d2_CreateMaterial(IDirect3D2 *iface, IDirect3DMaterial2 **material,
4142         IUnknown *outer_unknown)
4143 {
4144     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4145     IDirect3DMaterialImpl *object;
4146
4147     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4148
4149     object = d3d_material_create(This);
4150     if (!object)
4151     {
4152         ERR("Failed to allocate material memory.\n");
4153         return DDERR_OUTOFMEMORY;
4154     }
4155
4156     TRACE("Created material %p.\n", object);
4157     *material = &object->IDirect3DMaterial2_iface;
4158
4159     return D3D_OK;
4160 }
4161
4162 static HRESULT WINAPI d3d1_CreateMaterial(IDirect3D *iface, IDirect3DMaterial **material,
4163         IUnknown *outer_unknown)
4164 {
4165     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4166     IDirect3DMaterialImpl *object;
4167
4168     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4169
4170     object = d3d_material_create(This);
4171     if (!object)
4172     {
4173         ERR("Failed to allocate material memory.\n");
4174         return DDERR_OUTOFMEMORY;
4175     }
4176
4177     TRACE("Created material %p.\n", object);
4178     *material = &object->IDirect3DMaterial_iface;
4179
4180     return D3D_OK;
4181 }
4182
4183 /*****************************************************************************
4184  * IDirect3D3::CreateViewport
4185  *
4186  * Creates an IDirect3DViewport interface. This interface is used
4187  * by Direct3D and earlier versions for Viewport management. In Direct3D7
4188  * it has been replaced by a viewport structure and
4189  * IDirect3DDevice7::*Viewport. Wine's IDirect3DViewport implementation
4190  * uses the IDirect3DDevice7 methods for its functionality
4191  *
4192  * Params:
4193  *  Viewport: Address to store the new interface pointer
4194  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4195  *                 Must be NULL
4196  *
4197  * Returns:
4198  *  D3D_OK on success
4199  *  DDERR_OUTOFMEMORY if memory allocation failed
4200  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4201  *
4202  *****************************************************************************/
4203 static HRESULT WINAPI d3d3_CreateViewport(IDirect3D3 *iface, IDirect3DViewport3 **viewport,
4204         IUnknown *outer_unknown)
4205 {
4206     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4207     IDirect3DViewportImpl *object;
4208
4209     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4210
4211     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4212
4213     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4214     if (!object)
4215     {
4216         ERR("Failed to allocate viewport memory.\n");
4217         return DDERR_OUTOFMEMORY;
4218     }
4219
4220     d3d_viewport_init(object, This);
4221
4222     TRACE("Created viewport %p.\n", object);
4223     *viewport = &object->IDirect3DViewport3_iface;
4224
4225     return D3D_OK;
4226 }
4227
4228 static HRESULT WINAPI d3d2_CreateViewport(IDirect3D2 *iface, IDirect3DViewport2 **viewport, IUnknown *outer_unknown)
4229 {
4230     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4231
4232     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4233
4234     return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4235             outer_unknown);
4236 }
4237
4238 static HRESULT WINAPI d3d1_CreateViewport(IDirect3D *iface, IDirect3DViewport **viewport, IUnknown *outer_unknown)
4239 {
4240     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4241
4242     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4243
4244     return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4245             outer_unknown);
4246 }
4247
4248 /*****************************************************************************
4249  * IDirect3D3::FindDevice
4250  *
4251  * This method finds a device with the requested properties and returns a
4252  * device description
4253  *
4254  * Verion 1, 2 and 3
4255  * Params:
4256  *  fds: Describes the requested device characteristics
4257  *  fdr: Returns the device description
4258  *
4259  * Returns:
4260  *  D3D_OK on success
4261  *  DDERR_INVALIDPARAMS if no device was found
4262  *
4263  *****************************************************************************/
4264 static HRESULT WINAPI d3d3_FindDevice(IDirect3D3 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4265 {
4266     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4267     D3DDEVICEDESC7 desc7;
4268     D3DDEVICEDESC desc1;
4269     HRESULT hr;
4270
4271     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4272
4273     if (!fds || !fdr) return DDERR_INVALIDPARAMS;
4274
4275     if (fds->dwSize != sizeof(D3DFINDDEVICESEARCH)
4276             || fdr->dwSize != sizeof(D3DFINDDEVICERESULT))
4277         return DDERR_INVALIDPARAMS;
4278
4279     if ((fds->dwFlags & D3DFDS_COLORMODEL)
4280             && fds->dcmColorModel != D3DCOLOR_RGB)
4281     {
4282         WARN("Trying to request a non-RGB D3D color model. Not supported.\n");
4283         return DDERR_INVALIDPARAMS; /* No real idea what to return here :-) */
4284     }
4285
4286     if (fds->dwFlags & D3DFDS_GUID)
4287     {
4288         TRACE("Trying to match guid %s.\n", debugstr_guid(&(fds->guid)));
4289         if (!IsEqualGUID(&IID_D3DDEVICE_WineD3D, &fds->guid)
4290                 && !IsEqualGUID(&IID_IDirect3DHALDevice, &fds->guid)
4291                 && !IsEqualGUID(&IID_IDirect3DRGBDevice, &fds->guid))
4292         {
4293             WARN("No match for this GUID.\n");
4294             return DDERR_NOTFOUND;
4295         }
4296     }
4297
4298     /* Get the caps */
4299     hr = IDirect3DImpl_GetCaps(This->wineD3D, &desc1, &desc7);
4300     if (hr != D3D_OK) return hr;
4301
4302     /* Now return our own GUID */
4303     fdr->guid = IID_D3DDEVICE_WineD3D;
4304     fdr->ddHwDesc = desc1;
4305     fdr->ddSwDesc = desc1;
4306
4307     TRACE("Returning Wine's wined3d device with (undumped) capabilities.\n");
4308
4309     return D3D_OK;
4310 }
4311
4312 static HRESULT WINAPI d3d2_FindDevice(IDirect3D2 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4313 {
4314     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4315
4316     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4317
4318     return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4319 }
4320
4321 static HRESULT WINAPI d3d1_FindDevice(IDirect3D *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4322 {
4323     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4324
4325     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4326
4327     return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4328 }
4329
4330 /*****************************************************************************
4331  * IDirect3D7::CreateDevice
4332  *
4333  * Creates an IDirect3DDevice7 interface.
4334  *
4335  * Version 2, 3 and 7. IDirect3DDevice 1 interfaces are interfaces to
4336  * DirectDraw surfaces and are created with
4337  * IDirectDrawSurface::QueryInterface. This method uses CreateDevice to
4338  * create the device object and QueryInterfaces for IDirect3DDevice
4339  *
4340  * Params:
4341  *  refiid: IID of the device to create
4342  *  Surface: Initial rendertarget
4343  *  Device: Address to return the interface pointer
4344  *
4345  * Returns:
4346  *  D3D_OK on success
4347  *  DDERR_OUTOFMEMORY if memory allocation failed
4348  *  DDERR_INVALIDPARAMS if a device exists already
4349  *
4350  *****************************************************************************/
4351 static HRESULT WINAPI d3d7_CreateDevice(IDirect3D7 *iface, REFCLSID riid,
4352         IDirectDrawSurface7 *surface, IDirect3DDevice7 **device)
4353 {
4354     IDirectDrawSurfaceImpl *target = unsafe_impl_from_IDirectDrawSurface7(surface);
4355     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4356     IDirect3DDeviceImpl *object;
4357     HRESULT hr;
4358
4359     TRACE("iface %p, riid %s, surface %p, device %p.\n", iface, debugstr_guid(riid), surface, device);
4360
4361     wined3d_mutex_lock();
4362     *device = NULL;
4363
4364     /* Fail device creation if non-opengl surfaces are used. */
4365     if (DefaultSurfaceType != SURFACE_OPENGL)
4366     {
4367         ERR("The application wants to create a Direct3D device, but non-opengl surfaces are set in the registry.\n");
4368         ERR("Please set the surface implementation to opengl or autodetection to allow 3D rendering.\n");
4369
4370         /* We only hit this path if a default surface is set in the registry. Incorrect autodetection
4371          * is caught in CreateSurface or QueryInterface. */
4372         wined3d_mutex_unlock();
4373         return DDERR_NO3D;
4374     }
4375
4376     if (This->d3ddevice)
4377     {
4378         FIXME("Only one Direct3D device per DirectDraw object supported.\n");
4379         wined3d_mutex_unlock();
4380         return DDERR_INVALIDPARAMS;
4381     }
4382
4383     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4384     if (!object)
4385     {
4386         ERR("Failed to allocate device memory.\n");
4387         wined3d_mutex_unlock();
4388         return DDERR_OUTOFMEMORY;
4389     }
4390
4391     hr = d3d_device_init(object, This, target);
4392     if (FAILED(hr))
4393     {
4394         WARN("Failed to initialize device, hr %#x.\n", hr);
4395         HeapFree(GetProcessHeap(), 0, object);
4396         wined3d_mutex_unlock();
4397         return hr;
4398     }
4399
4400     TRACE("Created device %p.\n", object);
4401     *device = &object->IDirect3DDevice7_iface;
4402
4403     wined3d_mutex_unlock();
4404
4405     return D3D_OK;
4406 }
4407
4408 static HRESULT WINAPI d3d3_CreateDevice(IDirect3D3 *iface, REFCLSID riid,
4409         IDirectDrawSurface4 *surface, IDirect3DDevice3 **device, IUnknown *outer_unknown)
4410 {
4411     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4412     IDirectDrawSurfaceImpl *surface_impl = unsafe_impl_from_IDirectDrawSurface4(surface);
4413     IDirect3DDevice7 *device7;
4414     IDirect3DDeviceImpl *device_impl;
4415     HRESULT hr;
4416
4417     TRACE("iface %p, riid %s, surface %p, device %p, outer_unknown %p.\n",
4418             iface, debugstr_guid(riid), surface, device, outer_unknown);
4419
4420     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4421
4422     hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid,
4423             surface_impl ? &surface_impl->IDirectDrawSurface7_iface : NULL, device ? &device7 : NULL);
4424     if (SUCCEEDED(hr))
4425     {
4426         device_impl = impl_from_IDirect3DDevice7(device7);
4427         *device = &device_impl->IDirect3DDevice3_iface;
4428     }
4429
4430     return hr;
4431 }
4432
4433 static HRESULT WINAPI d3d2_CreateDevice(IDirect3D2 *iface, REFCLSID riid,
4434         IDirectDrawSurface *surface, IDirect3DDevice2 **device)
4435 {
4436     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4437     IDirectDrawSurfaceImpl *surface_impl = unsafe_impl_from_IDirectDrawSurface(surface);
4438     IDirect3DDevice7 *device7;
4439     IDirect3DDeviceImpl *device_impl;
4440     HRESULT hr;
4441
4442     TRACE("iface %p, riid %s, surface %p, device %p.\n",
4443             iface, debugstr_guid(riid), surface, device);
4444
4445     hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid,
4446             surface_impl ? &surface_impl->IDirectDrawSurface7_iface : NULL, device ? &device7 : NULL);
4447     if (SUCCEEDED(hr))
4448     {
4449         device_impl = impl_from_IDirect3DDevice7(device7);
4450         *device = &device_impl->IDirect3DDevice2_iface;
4451     }
4452
4453     return hr;
4454 }
4455
4456 /*****************************************************************************
4457  * IDirect3D7::CreateVertexBuffer
4458  *
4459  * Creates a new vertex buffer object and returns a IDirect3DVertexBuffer7
4460  * interface.
4461  *
4462  * Version 3 and 7
4463  *
4464  * Params:
4465  *  desc: Requested Vertex buffer properties
4466  *  vertex_buffer: Address to return the interface pointer at
4467  *  flags: Some flags, should be 0
4468  *
4469  * Returns
4470  *  D3D_OK on success
4471  *  DDERR_OUTOFMEMORY if memory allocation failed
4472  *  The return value of IWineD3DDevice::CreateVertexBuffer if this call fails
4473  *  DDERR_INVALIDPARAMS if desc or vertex_buffer are NULL
4474  *
4475  *****************************************************************************/
4476 static HRESULT WINAPI d3d7_CreateVertexBuffer(IDirect3D7 *iface, D3DVERTEXBUFFERDESC *desc,
4477         IDirect3DVertexBuffer7 **vertex_buffer, DWORD flags)
4478 {
4479     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4480     IDirect3DVertexBufferImpl *object;
4481     HRESULT hr;
4482
4483     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x.\n",
4484             iface, desc, vertex_buffer, flags);
4485
4486     if (!vertex_buffer || !desc) return DDERR_INVALIDPARAMS;
4487
4488     hr = d3d_vertex_buffer_create(&object, This, desc);
4489     if (hr == D3D_OK)
4490     {
4491         TRACE("Created vertex buffer %p.\n", object);
4492         *vertex_buffer = &object->IDirect3DVertexBuffer7_iface;
4493     }
4494     else
4495         WARN("Failed to create vertex buffer, hr %#x.\n", hr);
4496
4497     return hr;
4498 }
4499
4500 static HRESULT WINAPI d3d3_CreateVertexBuffer(IDirect3D3 *iface, D3DVERTEXBUFFERDESC *desc,
4501         IDirect3DVertexBuffer **vertex_buffer, DWORD flags, IUnknown *outer_unknown)
4502 {
4503     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4504     IDirect3DVertexBufferImpl *object;
4505     HRESULT hr;
4506
4507     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x, outer_unknown %p.\n",
4508             iface, desc, vertex_buffer, flags, outer_unknown);
4509
4510     if (outer_unknown)
4511         return CLASS_E_NOAGGREGATION;
4512     if (!vertex_buffer || !desc)
4513         return DDERR_INVALIDPARAMS;
4514
4515     hr = d3d_vertex_buffer_create(&object, This, desc);
4516     if (hr == D3D_OK)
4517     {
4518         TRACE("Created vertex buffer %p.\n", object);
4519         *vertex_buffer = &object->IDirect3DVertexBuffer_iface;
4520     }
4521     else
4522         WARN("Failed to create vertex buffer, hr %#x.\n", hr);
4523
4524     return hr;
4525 }
4526
4527 /*****************************************************************************
4528  * IDirect3D7::EnumZBufferFormats
4529  *
4530  * Enumerates all supported Z buffer pixel formats
4531  *
4532  * Version 3 and 7
4533  *
4534  * Params:
4535  *  device_iid:
4536  *  callback: callback to call for each pixel format
4537  *  context: Pointer to pass back to the callback
4538  *
4539  * Returns:
4540  *  D3D_OK on success
4541  *  DDERR_INVALIDPARAMS if callback is NULL
4542  *  For details, see IWineD3DDevice::EnumZBufferFormats
4543  *
4544  *****************************************************************************/
4545 static HRESULT WINAPI d3d7_EnumZBufferFormats(IDirect3D7 *iface, REFCLSID device_iid,
4546         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4547 {
4548     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4549     struct wined3d_display_mode mode;
4550     WINED3DDEVTYPE type;
4551     unsigned int i;
4552     HRESULT hr;
4553
4554     /* Order matters. Specifically, BattleZone II (full version) expects the
4555      * 16-bit depth formats to be listed before the 24 and 32 ones. */
4556     static const enum wined3d_format_id formats[] =
4557     {
4558         WINED3DFMT_S1_UINT_D15_UNORM,
4559         WINED3DFMT_D16_UNORM,
4560         WINED3DFMT_X8D24_UNORM,
4561         WINED3DFMT_S4X4_UINT_D24_UNORM,
4562         WINED3DFMT_D24_UNORM_S8_UINT,
4563         WINED3DFMT_D32_UNORM,
4564     };
4565
4566     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4567             iface, debugstr_guid(device_iid), callback, context);
4568
4569     if (!callback) return DDERR_INVALIDPARAMS;
4570
4571     if (IsEqualGUID(device_iid, &IID_IDirect3DHALDevice)
4572             || IsEqualGUID(device_iid, &IID_IDirect3DTnLHalDevice)
4573             || IsEqualGUID(device_iid, &IID_D3DDEVICE_WineD3D))
4574     {
4575         TRACE("Asked for HAL device.\n");
4576         type = WINED3DDEVTYPE_HAL;
4577     }
4578     else if (IsEqualGUID(device_iid, &IID_IDirect3DRGBDevice)
4579             || IsEqualGUID(device_iid, &IID_IDirect3DMMXDevice))
4580     {
4581         TRACE("Asked for SW device.\n");
4582         type = WINED3DDEVTYPE_SW;
4583     }
4584     else if (IsEqualGUID(device_iid, &IID_IDirect3DRefDevice))
4585     {
4586         TRACE("Asked for REF device.\n");
4587         type = WINED3DDEVTYPE_REF;
4588     }
4589     else if (IsEqualGUID(device_iid, &IID_IDirect3DNullDevice))
4590     {
4591         TRACE("Asked for NULLREF device.\n");
4592         type = WINED3DDEVTYPE_NULLREF;
4593     }
4594     else
4595     {
4596         FIXME("Unexpected device GUID %s.\n", debugstr_guid(device_iid));
4597         type = WINED3DDEVTYPE_HAL;
4598     }
4599
4600     wined3d_mutex_lock();
4601     /* We need an adapter format from somewhere to please wined3d and WGL.
4602      * Use the current display mode. So far all cards offer the same depth
4603      * stencil format for all modes, but if some do not and applications do
4604      * not like that we'll have to find some workaround, like iterating over
4605      * all imaginable formats and collecting all the depth stencil formats we
4606      * can get. */
4607     hr = wined3d_device_get_display_mode(This->wined3d_device, 0, &mode);
4608
4609     for (i = 0; i < (sizeof(formats) / sizeof(*formats)); ++i)
4610     {
4611         hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, type, mode.format_id,
4612                 WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, formats[i], SURFACE_OPENGL);
4613         if (SUCCEEDED(hr))
4614         {
4615             DDPIXELFORMAT pformat;
4616
4617             memset(&pformat, 0, sizeof(pformat));
4618             pformat.dwSize = sizeof(pformat);
4619             PixelFormat_WineD3DtoDD(&pformat, formats[i]);
4620
4621             TRACE("Enumerating wined3d format %#x.\n", formats[i]);
4622             hr = callback(&pformat, context);
4623             if (hr != DDENUMRET_OK)
4624             {
4625                 TRACE("Format enumeration cancelled by application.\n");
4626                 wined3d_mutex_unlock();
4627                 return D3D_OK;
4628             }
4629         }
4630     }
4631
4632     /* Historically some windows drivers used dwZBufferBitDepth=24 for WINED3DFMT_X8D24_UNORM,
4633      * while others used dwZBufferBitDepth=32. In either case the pitch matches a 32 bits per
4634      * pixel format, so we use dwZBufferBitDepth=32. Some games expect 24. Windows Vista and
4635      * newer enumerate both versions, so we do the same(bug 22434) */
4636     hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, type, mode.format_id,
4637             WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, WINED3DFMT_X8D24_UNORM, SURFACE_OPENGL);
4638     if (SUCCEEDED(hr))
4639     {
4640         DDPIXELFORMAT x8d24 =
4641         {
4642             sizeof(x8d24), DDPF_ZBUFFER, 0,
4643             {24}, {0x00000000}, {0x00ffffff}, {0x00000000}
4644         };
4645         TRACE("Enumerating WINED3DFMT_X8D24_UNORM, dwZBufferBitDepth=24 version\n");
4646         callback(&x8d24, context);
4647     }
4648
4649     TRACE("End of enumeration.\n");
4650
4651     wined3d_mutex_unlock();
4652
4653     return D3D_OK;
4654 }
4655
4656 static HRESULT WINAPI d3d3_EnumZBufferFormats(IDirect3D3 *iface, REFCLSID device_iid,
4657         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4658 {
4659     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4660
4661     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4662             iface, debugstr_guid(device_iid), callback, context);
4663
4664     return d3d7_EnumZBufferFormats(&This->IDirect3D7_iface, device_iid, callback, context);
4665 }
4666
4667 /*****************************************************************************
4668  * IDirect3D7::EvictManagedTextures
4669  *
4670  * Removes all managed textures (=surfaces with DDSCAPS2_TEXTUREMANAGE or
4671  * DDSCAPS2_D3DTEXTUREMANAGE caps) to be removed from video memory.
4672  *
4673  * Version 3 and 7
4674  *
4675  * Returns:
4676  *  D3D_OK, because it's a stub
4677  *
4678  *****************************************************************************/
4679 static HRESULT WINAPI d3d7_EvictManagedTextures(IDirect3D7 *iface)
4680 {
4681     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4682
4683     TRACE("iface %p!\n", iface);
4684
4685     wined3d_mutex_lock();
4686     if (This->d3d_initialized)
4687         wined3d_device_evict_managed_resources(This->wined3d_device);
4688     wined3d_mutex_unlock();
4689
4690     return D3D_OK;
4691 }
4692
4693 static HRESULT WINAPI d3d3_EvictManagedTextures(IDirect3D3 *iface)
4694 {
4695     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4696
4697     TRACE("iface %p.\n", iface);
4698
4699     return d3d7_EvictManagedTextures(&This->IDirect3D7_iface);
4700 }
4701
4702 /*****************************************************************************
4703  * IDirect3DImpl_GetCaps
4704  *
4705  * This function retrieves the device caps from wined3d
4706  * and converts it into a D3D7 and D3D - D3D3 structure
4707  * This is a helper function called from various places in ddraw
4708  *
4709  * Params:
4710  *  wined3d: The interface to get the caps from
4711  *  desc1: Old D3D <3 structure to fill (needed)
4712  *  desc7: D3D7 device desc structure to fill (needed)
4713  *
4714  * Returns
4715  *  D3D_OK on success, or the return value of IWineD3D::GetCaps
4716  *
4717  *****************************************************************************/
4718 HRESULT IDirect3DImpl_GetCaps(const struct wined3d *wined3d, D3DDEVICEDESC *desc1, D3DDEVICEDESC7 *desc7)
4719 {
4720     WINED3DCAPS wined3d_caps;
4721     HRESULT hr;
4722
4723     TRACE("wined3d %p, desc1 %p, desc7 %p.\n", wined3d, desc1, desc7);
4724
4725     memset(&wined3d_caps, 0, sizeof(wined3d_caps));
4726
4727     wined3d_mutex_lock();
4728     hr = wined3d_get_device_caps(wined3d, 0, WINED3DDEVTYPE_HAL, &wined3d_caps);
4729     wined3d_mutex_unlock();
4730     if (FAILED(hr))
4731     {
4732         WARN("Failed to get device caps, hr %#x.\n", hr);
4733         return hr;
4734     }
4735
4736     /* Copy the results into the d3d7 and d3d3 structures */
4737     desc7->dwDevCaps = wined3d_caps.DevCaps;
4738     desc7->dpcLineCaps.dwMiscCaps = wined3d_caps.PrimitiveMiscCaps;
4739     desc7->dpcLineCaps.dwRasterCaps = wined3d_caps.RasterCaps;
4740     desc7->dpcLineCaps.dwZCmpCaps = wined3d_caps.ZCmpCaps;
4741     desc7->dpcLineCaps.dwSrcBlendCaps = wined3d_caps.SrcBlendCaps;
4742     desc7->dpcLineCaps.dwDestBlendCaps = wined3d_caps.DestBlendCaps;
4743     desc7->dpcLineCaps.dwAlphaCmpCaps = wined3d_caps.AlphaCmpCaps;
4744     desc7->dpcLineCaps.dwShadeCaps = wined3d_caps.ShadeCaps;
4745     desc7->dpcLineCaps.dwTextureCaps = wined3d_caps.TextureCaps;
4746     desc7->dpcLineCaps.dwTextureFilterCaps = wined3d_caps.TextureFilterCaps;
4747     desc7->dpcLineCaps.dwTextureAddressCaps = wined3d_caps.TextureAddressCaps;
4748
4749     desc7->dwMaxTextureWidth = wined3d_caps.MaxTextureWidth;
4750     desc7->dwMaxTextureHeight = wined3d_caps.MaxTextureHeight;
4751
4752     desc7->dwMaxTextureRepeat = wined3d_caps.MaxTextureRepeat;
4753     desc7->dwMaxTextureAspectRatio = wined3d_caps.MaxTextureAspectRatio;
4754     desc7->dwMaxAnisotropy = wined3d_caps.MaxAnisotropy;
4755     desc7->dvMaxVertexW = wined3d_caps.MaxVertexW;
4756
4757     desc7->dvGuardBandLeft = wined3d_caps.GuardBandLeft;
4758     desc7->dvGuardBandTop = wined3d_caps.GuardBandTop;
4759     desc7->dvGuardBandRight = wined3d_caps.GuardBandRight;
4760     desc7->dvGuardBandBottom = wined3d_caps.GuardBandBottom;
4761
4762     desc7->dvExtentsAdjust = wined3d_caps.ExtentsAdjust;
4763     desc7->dwStencilCaps = wined3d_caps.StencilCaps;
4764
4765     desc7->dwFVFCaps = wined3d_caps.FVFCaps;
4766     desc7->dwTextureOpCaps = wined3d_caps.TextureOpCaps;
4767
4768     desc7->dwVertexProcessingCaps = wined3d_caps.VertexProcessingCaps;
4769     desc7->dwMaxActiveLights = wined3d_caps.MaxActiveLights;
4770
4771     /* Remove all non-d3d7 caps */
4772     desc7->dwDevCaps &= (
4773         D3DDEVCAPS_FLOATTLVERTEX         | D3DDEVCAPS_SORTINCREASINGZ          | D3DDEVCAPS_SORTDECREASINGZ          |
4774         D3DDEVCAPS_SORTEXACT             | D3DDEVCAPS_EXECUTESYSTEMMEMORY      | D3DDEVCAPS_EXECUTEVIDEOMEMORY       |
4775         D3DDEVCAPS_TLVERTEXSYSTEMMEMORY  | D3DDEVCAPS_TLVERTEXVIDEOMEMORY      | D3DDEVCAPS_TEXTURESYSTEMMEMORY      |
4776         D3DDEVCAPS_TEXTUREVIDEOMEMORY    | D3DDEVCAPS_DRAWPRIMTLVERTEX         | D3DDEVCAPS_CANRENDERAFTERFLIP       |
4777         D3DDEVCAPS_TEXTURENONLOCALVIDMEM | D3DDEVCAPS_DRAWPRIMITIVES2          | D3DDEVCAPS_SEPARATETEXTUREMEMORIES  |
4778         D3DDEVCAPS_DRAWPRIMITIVES2EX     | D3DDEVCAPS_HWTRANSFORMANDLIGHT      | D3DDEVCAPS_CANBLTSYSTONONLOCAL      |
4779         D3DDEVCAPS_HWRASTERIZATION);
4780
4781     desc7->dwStencilCaps &= (
4782         D3DSTENCILCAPS_KEEP              | D3DSTENCILCAPS_ZERO                 | D3DSTENCILCAPS_REPLACE              |
4783         D3DSTENCILCAPS_INCRSAT           | D3DSTENCILCAPS_DECRSAT              | D3DSTENCILCAPS_INVERT               |
4784         D3DSTENCILCAPS_INCR              | D3DSTENCILCAPS_DECR);
4785
4786     /* FVF caps ?*/
4787
4788     desc7->dwTextureOpCaps &= (
4789         D3DTEXOPCAPS_DISABLE             | D3DTEXOPCAPS_SELECTARG1             | D3DTEXOPCAPS_SELECTARG2             |
4790         D3DTEXOPCAPS_MODULATE            | D3DTEXOPCAPS_MODULATE2X             | D3DTEXOPCAPS_MODULATE4X             |
4791         D3DTEXOPCAPS_ADD                 | D3DTEXOPCAPS_ADDSIGNED              | D3DTEXOPCAPS_ADDSIGNED2X            |
4792         D3DTEXOPCAPS_SUBTRACT            | D3DTEXOPCAPS_ADDSMOOTH              | D3DTEXOPCAPS_BLENDTEXTUREALPHA      |
4793         D3DTEXOPCAPS_BLENDFACTORALPHA    | D3DTEXOPCAPS_BLENDTEXTUREALPHAPM    | D3DTEXOPCAPS_BLENDCURRENTALPHA      |
4794         D3DTEXOPCAPS_PREMODULATE         | D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA |
4795         D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | D3DTEXOPCAPS_BUMPENVMAP    |
4796         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE | D3DTEXOPCAPS_DOTPRODUCT3);
4797
4798     desc7->dwVertexProcessingCaps &= (
4799         D3DVTXPCAPS_TEXGEN               | D3DVTXPCAPS_MATERIALSOURCE7         | D3DVTXPCAPS_VERTEXFOG               |
4800         D3DVTXPCAPS_DIRECTIONALLIGHTS    | D3DVTXPCAPS_POSITIONALLIGHTS        | D3DVTXPCAPS_LOCALVIEWER);
4801
4802     desc7->dpcLineCaps.dwMiscCaps &= (
4803         D3DPMISCCAPS_MASKPLANES          | D3DPMISCCAPS_MASKZ                  | D3DPMISCCAPS_LINEPATTERNREP         |
4804         D3DPMISCCAPS_CONFORMANT          | D3DPMISCCAPS_CULLNONE               | D3DPMISCCAPS_CULLCW                 |
4805         D3DPMISCCAPS_CULLCCW);
4806
4807     desc7->dpcLineCaps.dwRasterCaps &= (
4808         D3DPRASTERCAPS_DITHER            | D3DPRASTERCAPS_ROP2                 | D3DPRASTERCAPS_XOR                  |
4809         D3DPRASTERCAPS_PAT               | D3DPRASTERCAPS_ZTEST                | D3DPRASTERCAPS_SUBPIXEL             |
4810         D3DPRASTERCAPS_SUBPIXELX         | D3DPRASTERCAPS_FOGVERTEX            | D3DPRASTERCAPS_FOGTABLE             |
4811         D3DPRASTERCAPS_STIPPLE           | D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT | D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT |
4812         D3DPRASTERCAPS_ANTIALIASEDGES    | D3DPRASTERCAPS_MIPMAPLODBIAS        | D3DPRASTERCAPS_ZBIAS                |
4813         D3DPRASTERCAPS_ZBUFFERLESSHSR    | D3DPRASTERCAPS_FOGRANGE             | D3DPRASTERCAPS_ANISOTROPY           |
4814         D3DPRASTERCAPS_WBUFFER           | D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT | D3DPRASTERCAPS_WFOG           |
4815         D3DPRASTERCAPS_ZFOG);
4816
4817     desc7->dpcLineCaps.dwZCmpCaps &= (
4818         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4819         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4820         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4821
4822     desc7->dpcLineCaps.dwSrcBlendCaps &= (
4823         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4824         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4825         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4826         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4827         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4828
4829     desc7->dpcLineCaps.dwDestBlendCaps &= (
4830         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4831         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4832         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4833         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4834         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4835
4836     desc7->dpcLineCaps.dwAlphaCmpCaps &= (
4837         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4838         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4839         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4840
4841     desc7->dpcLineCaps.dwShadeCaps &= (
4842         D3DPSHADECAPS_COLORFLATMONO      | D3DPSHADECAPS_COLORFLATRGB          | D3DPSHADECAPS_COLORGOURAUDMONO      |
4843         D3DPSHADECAPS_COLORGOURAUDRGB    | D3DPSHADECAPS_COLORPHONGMONO        | D3DPSHADECAPS_COLORPHONGRGB         |
4844         D3DPSHADECAPS_SPECULARFLATMONO   | D3DPSHADECAPS_SPECULARFLATRGB       | D3DPSHADECAPS_SPECULARGOURAUDMONO   |
4845         D3DPSHADECAPS_SPECULARGOURAUDRGB | D3DPSHADECAPS_SPECULARPHONGMONO     | D3DPSHADECAPS_SPECULARPHONGRGB      |
4846         D3DPSHADECAPS_ALPHAFLATBLEND     | D3DPSHADECAPS_ALPHAFLATSTIPPLED     | D3DPSHADECAPS_ALPHAGOURAUDBLEND     |
4847         D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED | D3DPSHADECAPS_ALPHAPHONGBLEND     | D3DPSHADECAPS_ALPHAPHONGSTIPPLED    |
4848         D3DPSHADECAPS_FOGFLAT            | D3DPSHADECAPS_FOGGOURAUD            | D3DPSHADECAPS_FOGPHONG);
4849
4850     desc7->dpcLineCaps.dwTextureCaps &= (
4851         D3DPTEXTURECAPS_PERSPECTIVE      | D3DPTEXTURECAPS_POW2                | D3DPTEXTURECAPS_ALPHA               |
4852         D3DPTEXTURECAPS_TRANSPARENCY     | D3DPTEXTURECAPS_BORDER              | D3DPTEXTURECAPS_SQUAREONLY          |
4853         D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE | D3DPTEXTURECAPS_ALPHAPALETTE| D3DPTEXTURECAPS_NONPOW2CONDITIONAL  |
4854         D3DPTEXTURECAPS_PROJECTED        | D3DPTEXTURECAPS_CUBEMAP             | D3DPTEXTURECAPS_COLORKEYBLEND);
4855
4856     desc7->dpcLineCaps.dwTextureFilterCaps &= (
4857         D3DPTFILTERCAPS_NEAREST          | D3DPTFILTERCAPS_LINEAR              | D3DPTFILTERCAPS_MIPNEAREST          |
4858         D3DPTFILTERCAPS_MIPLINEAR        | D3DPTFILTERCAPS_LINEARMIPNEAREST    | D3DPTFILTERCAPS_LINEARMIPLINEAR     |
4859         D3DPTFILTERCAPS_MINFPOINT        | D3DPTFILTERCAPS_MINFLINEAR          | D3DPTFILTERCAPS_MINFANISOTROPIC     |
4860         D3DPTFILTERCAPS_MIPFPOINT        | D3DPTFILTERCAPS_MIPFLINEAR          | D3DPTFILTERCAPS_MAGFPOINT           |
4861         D3DPTFILTERCAPS_MAGFLINEAR       | D3DPTFILTERCAPS_MAGFANISOTROPIC     | D3DPTFILTERCAPS_MAGFAFLATCUBIC      |
4862         D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
4863
4864     desc7->dpcLineCaps.dwTextureBlendCaps &= (
4865         D3DPTBLENDCAPS_DECAL             | D3DPTBLENDCAPS_MODULATE             | D3DPTBLENDCAPS_DECALALPHA           |
4866         D3DPTBLENDCAPS_MODULATEALPHA     | D3DPTBLENDCAPS_DECALMASK            | D3DPTBLENDCAPS_MODULATEMASK         |
4867         D3DPTBLENDCAPS_COPY              | D3DPTBLENDCAPS_ADD);
4868
4869     desc7->dpcLineCaps.dwTextureAddressCaps &= (
4870         D3DPTADDRESSCAPS_WRAP            | D3DPTADDRESSCAPS_MIRROR             | D3DPTADDRESSCAPS_CLAMP              |
4871         D3DPTADDRESSCAPS_BORDER          | D3DPTADDRESSCAPS_INDEPENDENTUV);
4872
4873     if (!(desc7->dpcLineCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2))
4874     {
4875         /* DirectX7 always has the np2 flag set, no matter what the card
4876          * supports. Some old games (Rollcage) check the caps incorrectly.
4877          * If wined3d supports nonpow2 textures it also has np2 conditional
4878          * support. */
4879         desc7->dpcLineCaps.dwTextureCaps |= D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL;
4880     }
4881
4882     /* Fill the missing members, and do some fixup */
4883     desc7->dpcLineCaps.dwSize = sizeof(desc7->dpcLineCaps);
4884     desc7->dpcLineCaps.dwTextureBlendCaps = D3DPTBLENDCAPS_ADD | D3DPTBLENDCAPS_MODULATEMASK |
4885                                             D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_DECAL |
4886                                             D3DPTBLENDCAPS_DECALALPHA | D3DPTBLENDCAPS_DECALMASK |
4887                                             D3DPTBLENDCAPS_MODULATE | D3DPTBLENDCAPS_MODULATEALPHA;
4888     desc7->dpcLineCaps.dwStippleWidth = 32;
4889     desc7->dpcLineCaps.dwStippleHeight = 32;
4890     /* Use the same for the TriCaps */
4891     desc7->dpcTriCaps = desc7->dpcLineCaps;
4892
4893     desc7->dwDeviceRenderBitDepth = DDBD_16 | DDBD_24 | DDBD_32;
4894     desc7->dwDeviceZBufferBitDepth = DDBD_16 | DDBD_24;
4895     desc7->dwMinTextureWidth = 1;
4896     desc7->dwMinTextureHeight = 1;
4897
4898     /* Convert DWORDs safely to WORDs */
4899     if (wined3d_caps.MaxTextureBlendStages > 0xffff) desc7->wMaxTextureBlendStages = 0xffff;
4900     else desc7->wMaxTextureBlendStages = (WORD)wined3d_caps.MaxTextureBlendStages;
4901     if (wined3d_caps.MaxSimultaneousTextures > 0xffff) desc7->wMaxSimultaneousTextures = 0xffff;
4902     else desc7->wMaxSimultaneousTextures = (WORD)wined3d_caps.MaxSimultaneousTextures;
4903
4904     if (wined3d_caps.MaxUserClipPlanes > 0xffff) desc7->wMaxUserClipPlanes = 0xffff;
4905     else desc7->wMaxUserClipPlanes = (WORD)wined3d_caps.MaxUserClipPlanes;
4906     if (wined3d_caps.MaxVertexBlendMatrices > 0xffff) desc7->wMaxVertexBlendMatrices = 0xffff;
4907     else desc7->wMaxVertexBlendMatrices = (WORD)wined3d_caps.MaxVertexBlendMatrices;
4908
4909     desc7->deviceGUID = IID_IDirect3DTnLHalDevice;
4910
4911     desc7->dwReserved1 = 0;
4912     desc7->dwReserved2 = 0;
4913     desc7->dwReserved3 = 0;
4914     desc7->dwReserved4 = 0;
4915
4916     /* Fill the old structure */
4917     memset(desc1, 0, sizeof(*desc1));
4918     desc1->dwSize = sizeof(D3DDEVICEDESC);
4919     desc1->dwFlags = D3DDD_COLORMODEL
4920             | D3DDD_DEVCAPS
4921             | D3DDD_TRANSFORMCAPS
4922             | D3DDD_BCLIPPING
4923             | D3DDD_LIGHTINGCAPS
4924             | D3DDD_LINECAPS
4925             | D3DDD_TRICAPS
4926             | D3DDD_DEVICERENDERBITDEPTH
4927             | D3DDD_DEVICEZBUFFERBITDEPTH
4928             | D3DDD_MAXBUFFERSIZE
4929             | D3DDD_MAXVERTEXCOUNT;
4930
4931     desc1->dcmColorModel = D3DCOLOR_RGB;
4932     desc1->dwDevCaps = desc7->dwDevCaps;
4933     desc1->dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
4934     desc1->dtcTransformCaps.dwCaps = D3DTRANSFORMCAPS_CLIP;
4935     desc1->bClipping = TRUE;
4936     desc1->dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
4937     desc1->dlcLightingCaps.dwCaps = D3DLIGHTCAPS_DIRECTIONAL
4938             | D3DLIGHTCAPS_PARALLELPOINT
4939             | D3DLIGHTCAPS_POINT
4940             | D3DLIGHTCAPS_SPOT;
4941
4942     desc1->dlcLightingCaps.dwLightingModel = D3DLIGHTINGMODEL_RGB;
4943     desc1->dlcLightingCaps.dwNumLights = desc7->dwMaxActiveLights;
4944
4945     desc1->dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
4946     desc1->dpcLineCaps.dwMiscCaps = desc7->dpcLineCaps.dwMiscCaps;
4947     desc1->dpcLineCaps.dwRasterCaps = desc7->dpcLineCaps.dwRasterCaps;
4948     desc1->dpcLineCaps.dwZCmpCaps = desc7->dpcLineCaps.dwZCmpCaps;
4949     desc1->dpcLineCaps.dwSrcBlendCaps = desc7->dpcLineCaps.dwSrcBlendCaps;
4950     desc1->dpcLineCaps.dwDestBlendCaps = desc7->dpcLineCaps.dwDestBlendCaps;
4951     desc1->dpcLineCaps.dwShadeCaps = desc7->dpcLineCaps.dwShadeCaps;
4952     desc1->dpcLineCaps.dwTextureCaps = desc7->dpcLineCaps.dwTextureCaps;
4953     desc1->dpcLineCaps.dwTextureFilterCaps = desc7->dpcLineCaps.dwTextureFilterCaps;
4954     desc1->dpcLineCaps.dwTextureBlendCaps = desc7->dpcLineCaps.dwTextureBlendCaps;
4955     desc1->dpcLineCaps.dwTextureAddressCaps = desc7->dpcLineCaps.dwTextureAddressCaps;
4956     desc1->dpcLineCaps.dwStippleWidth = desc7->dpcLineCaps.dwStippleWidth;
4957     desc1->dpcLineCaps.dwAlphaCmpCaps = desc7->dpcLineCaps.dwAlphaCmpCaps;
4958
4959     desc1->dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
4960     desc1->dpcTriCaps.dwMiscCaps = desc7->dpcTriCaps.dwMiscCaps;
4961     desc1->dpcTriCaps.dwRasterCaps = desc7->dpcTriCaps.dwRasterCaps;
4962     desc1->dpcTriCaps.dwZCmpCaps = desc7->dpcTriCaps.dwZCmpCaps;
4963     desc1->dpcTriCaps.dwSrcBlendCaps = desc7->dpcTriCaps.dwSrcBlendCaps;
4964     desc1->dpcTriCaps.dwDestBlendCaps = desc7->dpcTriCaps.dwDestBlendCaps;
4965     desc1->dpcTriCaps.dwShadeCaps = desc7->dpcTriCaps.dwShadeCaps;
4966     desc1->dpcTriCaps.dwTextureCaps = desc7->dpcTriCaps.dwTextureCaps;
4967     desc1->dpcTriCaps.dwTextureFilterCaps = desc7->dpcTriCaps.dwTextureFilterCaps;
4968     desc1->dpcTriCaps.dwTextureBlendCaps = desc7->dpcTriCaps.dwTextureBlendCaps;
4969     desc1->dpcTriCaps.dwTextureAddressCaps = desc7->dpcTriCaps.dwTextureAddressCaps;
4970     desc1->dpcTriCaps.dwStippleWidth = desc7->dpcTriCaps.dwStippleWidth;
4971     desc1->dpcTriCaps.dwAlphaCmpCaps = desc7->dpcTriCaps.dwAlphaCmpCaps;
4972
4973     desc1->dwDeviceRenderBitDepth = desc7->dwDeviceRenderBitDepth;
4974     desc1->dwDeviceZBufferBitDepth = desc7->dwDeviceZBufferBitDepth;
4975     desc1->dwMaxBufferSize = 0;
4976     desc1->dwMaxVertexCount = 65536;
4977     desc1->dwMinTextureWidth  = desc7->dwMinTextureWidth;
4978     desc1->dwMinTextureHeight = desc7->dwMinTextureHeight;
4979     desc1->dwMaxTextureWidth  = desc7->dwMaxTextureWidth;
4980     desc1->dwMaxTextureHeight = desc7->dwMaxTextureHeight;
4981     desc1->dwMinStippleWidth  = 1;
4982     desc1->dwMinStippleHeight = 1;
4983     desc1->dwMaxStippleWidth  = 32;
4984     desc1->dwMaxStippleHeight = 32;
4985     desc1->dwMaxTextureRepeat = desc7->dwMaxTextureRepeat;
4986     desc1->dwMaxTextureAspectRatio = desc7->dwMaxTextureAspectRatio;
4987     desc1->dwMaxAnisotropy = desc7->dwMaxAnisotropy;
4988     desc1->dvGuardBandLeft = desc7->dvGuardBandLeft;
4989     desc1->dvGuardBandRight = desc7->dvGuardBandRight;
4990     desc1->dvGuardBandTop = desc7->dvGuardBandTop;
4991     desc1->dvGuardBandBottom = desc7->dvGuardBandBottom;
4992     desc1->dvExtentsAdjust = desc7->dvExtentsAdjust;
4993     desc1->dwStencilCaps = desc7->dwStencilCaps;
4994     desc1->dwFVFCaps = desc7->dwFVFCaps;
4995     desc1->dwTextureOpCaps = desc7->dwTextureOpCaps;
4996     desc1->wMaxTextureBlendStages = desc7->wMaxTextureBlendStages;
4997     desc1->wMaxSimultaneousTextures = desc7->wMaxSimultaneousTextures;
4998
4999     return DD_OK;
5000 }
5001
5002 /*****************************************************************************
5003  * IDirectDraw7 VTable
5004  *****************************************************************************/
5005 static const struct IDirectDraw7Vtbl ddraw7_vtbl =
5006 {
5007     /* IUnknown */
5008     ddraw7_QueryInterface,
5009     ddraw7_AddRef,
5010     ddraw7_Release,
5011     /* IDirectDraw */
5012     ddraw7_Compact,
5013     ddraw7_CreateClipper,
5014     ddraw7_CreatePalette,
5015     ddraw7_CreateSurface,
5016     ddraw7_DuplicateSurface,
5017     ddraw7_EnumDisplayModes,
5018     ddraw7_EnumSurfaces,
5019     ddraw7_FlipToGDISurface,
5020     ddraw7_GetCaps,
5021     ddraw7_GetDisplayMode,
5022     ddraw7_GetFourCCCodes,
5023     ddraw7_GetGDISurface,
5024     ddraw7_GetMonitorFrequency,
5025     ddraw7_GetScanLine,
5026     ddraw7_GetVerticalBlankStatus,
5027     ddraw7_Initialize,
5028     ddraw7_RestoreDisplayMode,
5029     ddraw7_SetCooperativeLevel,
5030     ddraw7_SetDisplayMode,
5031     ddraw7_WaitForVerticalBlank,
5032     /* IDirectDraw2 */
5033     ddraw7_GetAvailableVidMem,
5034     /* IDirectDraw3 */
5035     ddraw7_GetSurfaceFromDC,
5036     /* IDirectDraw4 */
5037     ddraw7_RestoreAllSurfaces,
5038     ddraw7_TestCooperativeLevel,
5039     ddraw7_GetDeviceIdentifier,
5040     /* IDirectDraw7 */
5041     ddraw7_StartModeTest,
5042     ddraw7_EvaluateMode
5043 };
5044
5045 static const struct IDirectDraw4Vtbl ddraw4_vtbl =
5046 {
5047     /* IUnknown */
5048     ddraw4_QueryInterface,
5049     ddraw4_AddRef,
5050     ddraw4_Release,
5051     /* IDirectDraw */
5052     ddraw4_Compact,
5053     ddraw4_CreateClipper,
5054     ddraw4_CreatePalette,
5055     ddraw4_CreateSurface,
5056     ddraw4_DuplicateSurface,
5057     ddraw4_EnumDisplayModes,
5058     ddraw4_EnumSurfaces,
5059     ddraw4_FlipToGDISurface,
5060     ddraw4_GetCaps,
5061     ddraw4_GetDisplayMode,
5062     ddraw4_GetFourCCCodes,
5063     ddraw4_GetGDISurface,
5064     ddraw4_GetMonitorFrequency,
5065     ddraw4_GetScanLine,
5066     ddraw4_GetVerticalBlankStatus,
5067     ddraw4_Initialize,
5068     ddraw4_RestoreDisplayMode,
5069     ddraw4_SetCooperativeLevel,
5070     ddraw4_SetDisplayMode,
5071     ddraw4_WaitForVerticalBlank,
5072     /* IDirectDraw2 */
5073     ddraw4_GetAvailableVidMem,
5074     /* IDirectDraw3 */
5075     ddraw4_GetSurfaceFromDC,
5076     /* IDirectDraw4 */
5077     ddraw4_RestoreAllSurfaces,
5078     ddraw4_TestCooperativeLevel,
5079     ddraw4_GetDeviceIdentifier,
5080 };
5081
5082 static const struct IDirectDraw2Vtbl ddraw2_vtbl =
5083 {
5084     /* IUnknown */
5085     ddraw2_QueryInterface,
5086     ddraw2_AddRef,
5087     ddraw2_Release,
5088     /* IDirectDraw */
5089     ddraw2_Compact,
5090     ddraw2_CreateClipper,
5091     ddraw2_CreatePalette,
5092     ddraw2_CreateSurface,
5093     ddraw2_DuplicateSurface,
5094     ddraw2_EnumDisplayModes,
5095     ddraw2_EnumSurfaces,
5096     ddraw2_FlipToGDISurface,
5097     ddraw2_GetCaps,
5098     ddraw2_GetDisplayMode,
5099     ddraw2_GetFourCCCodes,
5100     ddraw2_GetGDISurface,
5101     ddraw2_GetMonitorFrequency,
5102     ddraw2_GetScanLine,
5103     ddraw2_GetVerticalBlankStatus,
5104     ddraw2_Initialize,
5105     ddraw2_RestoreDisplayMode,
5106     ddraw2_SetCooperativeLevel,
5107     ddraw2_SetDisplayMode,
5108     ddraw2_WaitForVerticalBlank,
5109     /* IDirectDraw2 */
5110     ddraw2_GetAvailableVidMem,
5111 };
5112
5113 static const struct IDirectDrawVtbl ddraw1_vtbl =
5114 {
5115     /* IUnknown */
5116     ddraw1_QueryInterface,
5117     ddraw1_AddRef,
5118     ddraw1_Release,
5119     /* IDirectDraw */
5120     ddraw1_Compact,
5121     ddraw1_CreateClipper,
5122     ddraw1_CreatePalette,
5123     ddraw1_CreateSurface,
5124     ddraw1_DuplicateSurface,
5125     ddraw1_EnumDisplayModes,
5126     ddraw1_EnumSurfaces,
5127     ddraw1_FlipToGDISurface,
5128     ddraw1_GetCaps,
5129     ddraw1_GetDisplayMode,
5130     ddraw1_GetFourCCCodes,
5131     ddraw1_GetGDISurface,
5132     ddraw1_GetMonitorFrequency,
5133     ddraw1_GetScanLine,
5134     ddraw1_GetVerticalBlankStatus,
5135     ddraw1_Initialize,
5136     ddraw1_RestoreDisplayMode,
5137     ddraw1_SetCooperativeLevel,
5138     ddraw1_SetDisplayMode,
5139     ddraw1_WaitForVerticalBlank,
5140 };
5141
5142 static const struct IDirect3D7Vtbl d3d7_vtbl =
5143 {
5144     /* IUnknown methods */
5145     d3d7_QueryInterface,
5146     d3d7_AddRef,
5147     d3d7_Release,
5148     /* IDirect3D7 methods */
5149     d3d7_EnumDevices,
5150     d3d7_CreateDevice,
5151     d3d7_CreateVertexBuffer,
5152     d3d7_EnumZBufferFormats,
5153     d3d7_EvictManagedTextures
5154 };
5155
5156 static const struct IDirect3D3Vtbl d3d3_vtbl =
5157 {
5158     /* IUnknown methods */
5159     d3d3_QueryInterface,
5160     d3d3_AddRef,
5161     d3d3_Release,
5162     /* IDirect3D3 methods */
5163     d3d3_EnumDevices,
5164     d3d3_CreateLight,
5165     d3d3_CreateMaterial,
5166     d3d3_CreateViewport,
5167     d3d3_FindDevice,
5168     d3d3_CreateDevice,
5169     d3d3_CreateVertexBuffer,
5170     d3d3_EnumZBufferFormats,
5171     d3d3_EvictManagedTextures
5172 };
5173
5174 static const struct IDirect3D2Vtbl d3d2_vtbl =
5175 {
5176     /* IUnknown methods */
5177     d3d2_QueryInterface,
5178     d3d2_AddRef,
5179     d3d2_Release,
5180     /* IDirect3D2 methods */
5181     d3d2_EnumDevices,
5182     d3d2_CreateLight,
5183     d3d2_CreateMaterial,
5184     d3d2_CreateViewport,
5185     d3d2_FindDevice,
5186     d3d2_CreateDevice
5187 };
5188
5189 static const struct IDirect3DVtbl d3d1_vtbl =
5190 {
5191     /* IUnknown methods */
5192     d3d1_QueryInterface,
5193     d3d1_AddRef,
5194     d3d1_Release,
5195     /* IDirect3D methods */
5196     d3d1_Initialize,
5197     d3d1_EnumDevices,
5198     d3d1_CreateLight,
5199     d3d1_CreateMaterial,
5200     d3d1_CreateViewport,
5201     d3d1_FindDevice
5202 };
5203
5204 /*****************************************************************************
5205  * ddraw_find_decl
5206  *
5207  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
5208  * if none was found.
5209  *
5210  * This function is in ddraw.c and the DDraw object space because D3D7
5211  * vertex buffers are created using the IDirect3D interface to the ddraw
5212  * object, so they can be valid across D3D devices(theoretically. The ddraw
5213  * object also owns the wined3d device
5214  *
5215  * Parameters:
5216  *  This: Device
5217  *  fvf: Fvf to find the decl for
5218  *
5219  * Returns:
5220  *  NULL in case of an error, the vertex declaration for the FVF otherwise.
5221  *
5222  *****************************************************************************/
5223 struct wined3d_vertex_declaration *ddraw_find_decl(IDirectDrawImpl *This, DWORD fvf)
5224 {
5225     struct wined3d_vertex_declaration *pDecl = NULL;
5226     HRESULT hr;
5227     int p, low, high; /* deliberately signed */
5228     struct FvfToDecl *convertedDecls = This->decls;
5229
5230     TRACE("Searching for declaration for fvf %08x... ", fvf);
5231
5232     low = 0;
5233     high = This->numConvertedDecls - 1;
5234     while(low <= high) {
5235         p = (low + high) >> 1;
5236         TRACE("%d ", p);
5237         if(convertedDecls[p].fvf == fvf) {
5238             TRACE("found %p\n", convertedDecls[p].decl);
5239             return convertedDecls[p].decl;
5240         } else if(convertedDecls[p].fvf < fvf) {
5241             low = p + 1;
5242         } else {
5243             high = p - 1;
5244         }
5245     }
5246     TRACE("not found. Creating and inserting at position %d.\n", low);
5247
5248     hr = wined3d_vertex_declaration_create_from_fvf(This->wined3d_device,
5249             fvf, This, &ddraw_null_wined3d_parent_ops, &pDecl);
5250     if (hr != S_OK) return NULL;
5251
5252     if(This->declArraySize == This->numConvertedDecls) {
5253         int grow = max(This->declArraySize / 2, 8);
5254         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
5255                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
5256         if (!convertedDecls)
5257         {
5258             wined3d_vertex_declaration_decref(pDecl);
5259             return NULL;
5260         }
5261         This->decls = convertedDecls;
5262         This->declArraySize += grow;
5263     }
5264
5265     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
5266     convertedDecls[low].decl = pDecl;
5267     convertedDecls[low].fvf = fvf;
5268     This->numConvertedDecls++;
5269
5270     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
5271     return pDecl;
5272 }
5273
5274 static inline struct IDirectDrawImpl *ddraw_from_device_parent(struct wined3d_device_parent *device_parent)
5275 {
5276     return CONTAINING_RECORD(device_parent, struct IDirectDrawImpl, device_parent);
5277 }
5278
5279 static void CDECL device_parent_wined3d_device_created(struct wined3d_device_parent *device_parent,
5280         struct wined3d_device *device)
5281 {
5282     TRACE("device_parent %p, device %p.\n", device_parent, device);
5283 }
5284
5285 static HRESULT CDECL device_parent_create_surface(struct wined3d_device_parent *device_parent,
5286         void *container_parent, UINT width, UINT height, enum wined3d_format_id format, DWORD usage,
5287         WINED3DPOOL pool, UINT level, WINED3DCUBEMAP_FACES face, struct wined3d_surface **surface)
5288 {
5289     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5290     IDirectDrawSurfaceImpl *surf = NULL;
5291     UINT i = 0;
5292     DDSCAPS2 searchcaps = ddraw->tex_root->surface_desc.ddsCaps;
5293
5294     TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, usage %#x,\n"
5295             "\tpool %#x, level %u, face %u, surface %p.\n",
5296             device_parent, container_parent, width, height, format, usage, pool, level, face, surface);
5297
5298     searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
5299     switch(face)
5300     {
5301         case WINED3DCUBEMAP_FACE_POSITIVE_X:
5302             TRACE("Asked for positive x\n");
5303             if (searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP)
5304             {
5305                 searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
5306             }
5307             surf = ddraw->tex_root; break;
5308         case WINED3DCUBEMAP_FACE_NEGATIVE_X:
5309             TRACE("Asked for negative x\n");
5310             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
5311         case WINED3DCUBEMAP_FACE_POSITIVE_Y:
5312             TRACE("Asked for positive y\n");
5313             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
5314         case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
5315             TRACE("Asked for negative y\n");
5316             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
5317         case WINED3DCUBEMAP_FACE_POSITIVE_Z:
5318             TRACE("Asked for positive z\n");
5319             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
5320         case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
5321             TRACE("Asked for negative z\n");
5322             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
5323         default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
5324     }
5325
5326     if (!surf)
5327     {
5328         IDirectDrawSurface7 *attached;
5329         IDirectDrawSurface7_GetAttachedSurface(&ddraw->tex_root->IDirectDrawSurface7_iface, &searchcaps, &attached);
5330         surf = unsafe_impl_from_IDirectDrawSurface7(attached);
5331         IDirectDrawSurface7_Release(attached);
5332     }
5333     if (!surf) ERR("root search surface not found\n");
5334
5335     /* Find the wanted mipmap. There are enough mipmaps in the chain */
5336     while (i < level)
5337     {
5338         IDirectDrawSurface7 *attached;
5339         IDirectDrawSurface7_GetAttachedSurface(&surf->IDirectDrawSurface7_iface, &searchcaps, &attached);
5340         if(!attached) ERR("Surface not found\n");
5341         surf = impl_from_IDirectDrawSurface7(attached);
5342         IDirectDrawSurface7_Release(attached);
5343         ++i;
5344     }
5345
5346     /* Return the surface */
5347     *surface = surf->wined3d_surface;
5348     wined3d_surface_incref(*surface);
5349
5350     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, surf);
5351
5352     return D3D_OK;
5353 }
5354
5355 static void STDMETHODCALLTYPE ddraw_frontbuffer_destroyed(void *parent)
5356 {
5357     struct IDirectDrawImpl *ddraw = parent;
5358     ddraw->wined3d_frontbuffer = NULL;
5359 }
5360
5361 static const struct wined3d_parent_ops ddraw_frontbuffer_parent_ops =
5362 {
5363     ddraw_frontbuffer_destroyed,
5364 };
5365
5366 static HRESULT CDECL device_parent_create_rendertarget(struct wined3d_device_parent *device_parent,
5367         void *container_parent, UINT width, UINT height, enum wined3d_format_id format,
5368         WINED3DMULTISAMPLE_TYPE multisample_type, DWORD multisample_quality, BOOL lockable,
5369         struct wined3d_surface **surface)
5370 {
5371     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5372     HRESULT hr;
5373
5374     TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5375             "\tmultisample_quality %u, lockable %u, surface %p.\n",
5376             device_parent, container_parent, width, height, format, multisample_type,
5377             multisample_quality, lockable, surface);
5378
5379     if (ddraw->wined3d_frontbuffer)
5380     {
5381         ERR("Frontbuffer already created.\n");
5382         return E_FAIL;
5383     }
5384
5385     hr = wined3d_surface_create(ddraw->wined3d_device, width, height, format, lockable, FALSE, 0,
5386             WINED3DUSAGE_RENDERTARGET, WINED3DPOOL_DEFAULT, multisample_type, multisample_quality,
5387             DefaultSurfaceType, ddraw, &ddraw_frontbuffer_parent_ops, surface);
5388     if (SUCCEEDED(hr))
5389         ddraw->wined3d_frontbuffer = *surface;
5390
5391     return hr;
5392 }
5393
5394 static HRESULT CDECL device_parent_create_depth_stencil(struct wined3d_device_parent *device_parent,
5395         UINT width, UINT height, enum wined3d_format_id format, WINED3DMULTISAMPLE_TYPE multisample_type,
5396         DWORD multisample_quality, BOOL discard, struct wined3d_surface **surface)
5397 {
5398     ERR("DirectDraw doesn't have and shouldn't try creating implicit depth buffers.\n");
5399     return E_NOTIMPL;
5400 }
5401
5402 static HRESULT CDECL device_parent_create_volume(struct wined3d_device_parent *device_parent,
5403         void *container_parent, UINT width, UINT height, UINT depth, enum wined3d_format_id format,
5404         WINED3DPOOL pool, DWORD usage, struct wined3d_volume **volume)
5405 {
5406     TRACE("device_parent %p, container_parent %p, width %u, height %u, depth %u, "
5407             "format %#x, pool %#x, usage %#x, volume %p.\n",
5408             device_parent, container_parent, width, height, depth,
5409             format, pool, usage, volume);
5410
5411     ERR("Not implemented!\n");
5412
5413     return E_NOTIMPL;
5414 }
5415
5416 static HRESULT CDECL device_parent_create_swapchain(struct wined3d_device_parent *device_parent,
5417         WINED3DPRESENT_PARAMETERS *present_parameters, struct wined3d_swapchain **swapchain)
5418 {
5419     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5420     HRESULT hr;
5421
5422     TRACE("device_parent %p, present_parameters %p, swapchain %p.\n", device_parent, present_parameters, swapchain);
5423
5424     if (ddraw->wined3d_swapchain)
5425     {
5426         ERR("Swapchain already created.\n");
5427         return E_FAIL;
5428     }
5429
5430     hr = wined3d_swapchain_create(ddraw->wined3d_device, present_parameters,
5431             DefaultSurfaceType, NULL, &ddraw_null_wined3d_parent_ops, swapchain);
5432     if (FAILED(hr))
5433         WARN("Failed to create swapchain, hr %#x.\n", hr);
5434
5435     return hr;
5436 }
5437
5438 static const struct wined3d_device_parent_ops ddraw_wined3d_device_parent_ops =
5439 {
5440     device_parent_wined3d_device_created,
5441     device_parent_create_surface,
5442     device_parent_create_rendertarget,
5443     device_parent_create_depth_stencil,
5444     device_parent_create_volume,
5445     device_parent_create_swapchain,
5446 };
5447
5448 HRESULT ddraw_init(IDirectDrawImpl *ddraw, WINED3DDEVTYPE device_type)
5449 {
5450     HRESULT hr;
5451     HDC hDC;
5452
5453     ddraw->IDirectDraw7_iface.lpVtbl = &ddraw7_vtbl;
5454     ddraw->IDirectDraw_iface.lpVtbl = &ddraw1_vtbl;
5455     ddraw->IDirectDraw2_iface.lpVtbl = &ddraw2_vtbl;
5456     ddraw->IDirectDraw4_iface.lpVtbl = &ddraw4_vtbl;
5457     ddraw->IDirect3D_iface.lpVtbl = &d3d1_vtbl;
5458     ddraw->IDirect3D2_iface.lpVtbl = &d3d2_vtbl;
5459     ddraw->IDirect3D3_iface.lpVtbl = &d3d3_vtbl;
5460     ddraw->IDirect3D7_iface.lpVtbl = &d3d7_vtbl;
5461     ddraw->device_parent.ops = &ddraw_wined3d_device_parent_ops;
5462     ddraw->numIfaces = 1;
5463     ddraw->ref7 = 1;
5464
5465     /* Get the current screen settings. */
5466     hDC = GetDC(0);
5467     ddraw->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
5468     ReleaseDC(0, hDC);
5469     ddraw->orig_width = GetSystemMetrics(SM_CXSCREEN);
5470     ddraw->orig_height = GetSystemMetrics(SM_CYSCREEN);
5471
5472     ddraw->wineD3D = wined3d_create(7, WINED3D_LEGACY_DEPTH_BIAS,
5473             &ddraw->IDirectDraw7_iface);
5474     if (!ddraw->wineD3D)
5475     {
5476         WARN("Failed to create a wined3d object.\n");
5477         return E_OUTOFMEMORY;
5478     }
5479
5480     hr = wined3d_device_create(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, device_type,
5481             NULL, 0, 8, &ddraw->device_parent, &ddraw->wined3d_device);
5482     if (FAILED(hr))
5483     {
5484         WARN("Failed to create a wined3d device, hr %#x.\n", hr);
5485         wined3d_decref(ddraw->wineD3D);
5486         return hr;
5487     }
5488
5489     list_init(&ddraw->surface_list);
5490
5491     return DD_OK;
5492 }