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