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