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