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