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