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