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