ddraw/tests: Remove superfluous casts.
[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 <assert.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <stdlib.h>
30
31 #define COBJMACROS
32 #define NONAMELESSUNION
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winerror.h"
37 #include "wingdi.h"
38 #include "wine/exception.h"
39
40 #include "ddraw.h"
41 #include "d3d.h"
42
43 #include "ddraw_private.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
47
48 static BOOL IDirectDrawImpl_DDSD_Match(const DDSURFACEDESC2* requested, const DDSURFACEDESC2* provided);
49 static HRESULT IDirectDrawImpl_AttachD3DDevice(IDirectDrawImpl *This, IDirectDrawSurfaceImpl *primary);
50 static HRESULT IDirectDrawImpl_CreateNewSurface(IDirectDrawImpl *This, DDSURFACEDESC2 *pDDSD, IDirectDrawSurfaceImpl **ppSurf, UINT level);
51 static HRESULT IDirectDrawImpl_CreateGDISwapChain(IDirectDrawImpl *This, IDirectDrawSurfaceImpl *primary);
52
53 /* Device identifier. Don't relay it to WineD3D */
54 static const DDDEVICEIDENTIFIER2 deviceidentifier =
55 {
56     "display",
57     "DirectDraw HAL",
58     { { 0x00010001, 0x00010001 } },
59     0, 0, 0, 0,
60     /* a8373c10-7ac4-4deb-849a-009844d08b2d */
61     {0xa8373c10,0x7ac4,0x4deb, {0x84,0x9a,0x00,0x98,0x44,0xd0,0x8b,0x2d}},
62     0
63 };
64
65 /*****************************************************************************
66  * IUnknown Methods
67  *****************************************************************************/
68
69 /*****************************************************************************
70  * IDirectDraw7::QueryInterface
71  *
72  * Queries different interfaces of the DirectDraw object. It can return
73  * IDirectDraw interfaces in version 1, 2, 4 and 7, and IDirect3D interfaces
74  * in version 1, 2, 3 and 7. An IDirect3DDevice can be created with this
75  * method.
76  * The returned interface is AddRef()-ed before it's returned
77  *
78  * Used for version 1, 2, 4 and 7
79  *
80  * Params:
81  *  refiid: Interface ID asked for
82  *  obj: Used to return the interface pointer
83  *
84  * Returns:
85  *  S_OK if an interface was found
86  *  E_NOINTERFACE if the requested interface wasn't found
87  *
88  *****************************************************************************/
89 static HRESULT WINAPI
90 IDirectDrawImpl_QueryInterface(IDirectDraw7 *iface,
91                                REFIID refiid,
92                                void **obj)
93 {
94     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
95
96     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(refiid), obj);
97
98     /* Can change surface impl type */
99     EnterCriticalSection(&ddraw_cs);
100
101     /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
102     *obj = NULL;
103
104     if(!refiid)
105     {
106         LeaveCriticalSection(&ddraw_cs);
107         return DDERR_INVALIDPARAMS;
108     }
109
110     /* Check DirectDraw Interfaces */
111     if ( IsEqualGUID( &IID_IUnknown, refiid ) ||
112          IsEqualGUID( &IID_IDirectDraw7, refiid ) )
113     {
114         *obj = ICOM_INTERFACE(This, IDirectDraw7);
115         TRACE("(%p) Returning IDirectDraw7 interface at %p\n", This, *obj);
116     }
117     else if ( IsEqualGUID( &IID_IDirectDraw4, refiid ) )
118     {
119         *obj = ICOM_INTERFACE(This, IDirectDraw4);
120         TRACE("(%p) Returning IDirectDraw4 interface at %p\n", This, *obj);
121     }
122     else if ( IsEqualGUID( &IID_IDirectDraw3, refiid ) )
123     {
124         /* This Interface exists in ddrawex.dll, it is implemented in a wrapper */
125         WARN("IDirectDraw3 is not valid in ddraw.dll\n");
126         *obj = NULL;
127         LeaveCriticalSection(&ddraw_cs);
128         return E_NOINTERFACE;
129     }
130     else if ( IsEqualGUID( &IID_IDirectDraw2, refiid ) )
131     {
132         *obj = ICOM_INTERFACE(This, IDirectDraw2);
133         TRACE("(%p) Returning IDirectDraw2 interface at %p\n", This, *obj);
134     }
135     else if ( IsEqualGUID( &IID_IDirectDraw, refiid ) )
136     {
137         *obj = ICOM_INTERFACE(This, IDirectDraw);
138         TRACE("(%p) Returning IDirectDraw interface at %p\n", This, *obj);
139     }
140
141     /* Direct3D
142      * The refcount unit test revealed that an IDirect3D7 interface can only be queried
143      * from a DirectDraw object that was created as an IDirectDraw7 interface. No idea
144      * who had this idea and why. The older interfaces can query and IDirect3D version
145      * because they are all created as IDirectDraw(1). This isn't really crucial behavior,
146      * and messy to implement with the common creation function, so it has been left out here.
147      */
148     else if ( IsEqualGUID( &IID_IDirect3D  , refiid ) ||
149               IsEqualGUID( &IID_IDirect3D2 , refiid ) ||
150               IsEqualGUID( &IID_IDirect3D3 , refiid ) ||
151               IsEqualGUID( &IID_IDirect3D7 , refiid ) )
152     {
153         /* Check the surface implementation */
154         if(This->ImplType == SURFACE_UNKNOWN)
155         {
156             /* Apps may create the IDirect3D Interface before the primary surface.
157              * set the surface implementation */
158             This->ImplType = SURFACE_OPENGL;
159             TRACE("(%p) Choosing OpenGL surfaces because a Direct3D interface was requested\n", This);
160         }
161         else if(This->ImplType != SURFACE_OPENGL && DefaultSurfaceType == SURFACE_UNKNOWN)
162         {
163             ERR("(%p) The App is requesting a D3D device, but a non-OpenGL surface type was choosen. Prepare for trouble!\n", This);
164             ERR(" (%p) You may want to contact wine-devel for help\n", This);
165             /* Should I assert(0) here??? */
166         }
167         else if(This->ImplType != SURFACE_OPENGL)
168         {
169             WARN("The app requests a Direct3D interface, but non-opengl surfaces where set in winecfg\n");
170             /* Do not abort here, only reject 3D Device creation */
171         }
172
173         if ( IsEqualGUID( &IID_IDirect3D  , refiid ) )
174         {
175             This->d3dversion = 1;
176             *obj = ICOM_INTERFACE(This, IDirect3D);
177             TRACE(" returning Direct3D interface at %p.\n", *obj);
178         }
179         else if ( IsEqualGUID( &IID_IDirect3D2  , refiid ) )
180         {
181             This->d3dversion = 2;
182             *obj = ICOM_INTERFACE(This, IDirect3D2);
183             TRACE(" returning Direct3D2 interface at %p.\n", *obj);
184         }
185         else if ( IsEqualGUID( &IID_IDirect3D3  , refiid ) )
186         {
187             This->d3dversion = 3;
188             *obj = ICOM_INTERFACE(This, IDirect3D3);
189             TRACE(" returning Direct3D3 interface at %p.\n", *obj);
190         }
191         else if(IsEqualGUID( &IID_IDirect3D7  , refiid ))
192         {
193             This->d3dversion = 7;
194             *obj = ICOM_INTERFACE(This, IDirect3D7);
195             TRACE(" returning Direct3D7 interface at %p.\n", *obj);
196         }
197     }
198
199     /* Unknown interface */
200     else
201     {
202         ERR("(%p)->(%s, %p): No interface found\n", This, debugstr_guid(refiid), obj);
203         LeaveCriticalSection(&ddraw_cs);
204         return E_NOINTERFACE;
205     }
206
207     IUnknown_AddRef( (IUnknown *) *obj );
208     LeaveCriticalSection(&ddraw_cs);
209     return S_OK;
210 }
211
212 /*****************************************************************************
213  * IDirectDraw7::AddRef
214  *
215  * Increases the interfaces refcount, basically
216  *
217  * DDraw refcounting is a bit tricky. The different DirectDraw interface
218  * versions have individual refcounts, but the IDirect3D interfaces do not.
219  * All interfaces are from one object, that means calling QueryInterface on an
220  * IDirectDraw7 interface for an IDirectDraw4 interface does not create a new
221  * IDirectDrawImpl object.
222  *
223  * That means all AddRef and Release implementations of IDirectDrawX work
224  * with their own counter, and IDirect3DX::AddRef thunk to IDirectDraw (1),
225  * except of IDirect3D7 which thunks to IDirectDraw7
226  *
227  * Returns: The new refcount
228  *
229  *****************************************************************************/
230 static ULONG WINAPI
231 IDirectDrawImpl_AddRef(IDirectDraw7 *iface)
232 {
233     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
234     ULONG ref = InterlockedIncrement(&This->ref7);
235
236     TRACE("(%p) : incrementing IDirectDraw7 refcount from %u.\n", This, ref -1);
237
238     if(ref == 1) InterlockedIncrement(&This->numIfaces);
239
240     return ref;
241 }
242
243 /*****************************************************************************
244  * IDirectDrawImpl_Destroy
245  *
246  * Destroys a ddraw object if all refcounts are 0. This is to share code
247  * between the IDirectDrawX::Release functions
248  *
249  * Params:
250  *  This: DirectDraw object to destroy
251  *
252  *****************************************************************************/
253 void
254 IDirectDrawImpl_Destroy(IDirectDrawImpl *This)
255 {
256     /* Clear the cooplevel to restore window and display mode */
257     IDirectDraw7_SetCooperativeLevel(ICOM_INTERFACE(This, IDirectDraw7),
258                                         NULL,
259                                         DDSCL_NORMAL);
260
261     /* Destroy the device window if we created one */
262     if(This->devicewindow != 0)
263     {
264         TRACE(" (%p) Destroying the device window %p\n", This, This->devicewindow);
265         DestroyWindow(This->devicewindow);
266         This->devicewindow = 0;
267     }
268
269     /* Unregister the window class */
270     UnregisterClassA(This->classname, 0);
271
272     EnterCriticalSection(&ddraw_cs);
273     list_remove(&This->ddraw_list_entry);
274     LeaveCriticalSection(&ddraw_cs);
275
276     /* Release the attached WineD3D stuff */
277     IWineD3DDevice_Release(This->wineD3DDevice);
278     IWineD3D_Release(This->wineD3D);
279
280     /* Now free the object */
281     HeapFree(GetProcessHeap(), 0, This);
282 }
283
284 /*****************************************************************************
285  * IDirectDraw7::Release
286  *
287  * Decreases the refcount. If the refcount falls to 0, the object is destroyed
288  *
289  * Returns: The new refcount
290  *****************************************************************************/
291 static ULONG WINAPI
292 IDirectDrawImpl_Release(IDirectDraw7 *iface)
293 {
294     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
295     ULONG ref = InterlockedDecrement(&This->ref7);
296
297     TRACE("(%p)->() decrementing IDirectDraw7 refcount from %u.\n", This, ref +1);
298
299     if(ref == 0)
300     {
301         ULONG ifacecount = InterlockedDecrement(&This->numIfaces);
302         if(ifacecount == 0) IDirectDrawImpl_Destroy(This);
303     }
304
305     return ref;
306 }
307
308 /*****************************************************************************
309  * IDirectDraw methods
310  *****************************************************************************/
311
312 /*****************************************************************************
313  * IDirectDraw7::SetCooperativeLevel
314  *
315  * Sets the cooperative level for the DirectDraw object, and the window
316  * assigned to it. The cooperative level determines the general behavior
317  * of the DirectDraw application
318  *
319  * Warning: This is quite tricky, as it's not really documented which
320  * cooperative levels can be combined with each other. If a game fails
321  * after this function, try to check the cooperative levels passed on
322  * Windows, and if it returns something different.
323  *
324  * If you think that this function caused the failure because it writes a
325  * fixme, be sure to run again with a +ddraw trace.
326  *
327  * What is known about cooperative levels (See the ddraw modes test):
328  * DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN must be used with each other
329  * DDSCL_NORMAL is not compatible with DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN
330  * DDSCL_SETFOCUSWINDOW can be passed only in DDSCL_NORMAL mode, but after that
331  * DDSCL_FULLSCREEN can be activated
332  * DDSCL_SETFOCUSWINDOW may only be used with DDSCL_NOWINDOWCHANGES
333  *
334  * Handled flags: DDSCL_NORMAL, DDSCL_FULLSCREEN, DDSCL_EXCLUSIVE,
335  *                DDSCL_SETFOCUSWINDOW (partially),
336  *                DDSCL_MULTITHREADED (work in progress)
337  *
338  * Unhandled flags, which should be implemented
339  *  DDSCL_SETDEVICEWINDOW: Sets a window specially used for rendering (I don't
340  *  expect any difference to a normal window for wine)
341  *  DDSCL_CREATEDEVICEWINDOW: Tells ddraw to create its own window for
342  *  rendering (Possible test case: Half-life)
343  *
344  * Unsure about these: DDSCL_FPUSETUP DDSCL_FPURESERVE
345  *
346  * These don't seem very important for wine:
347  *  DDSCL_ALLOWREBOOT, DDSCL_NOWINDOWCHANGES, DDSCL_ALLOWMODEX
348  *
349  * Returns:
350  *  DD_OK if the cooperative level was set successfully
351  *  DDERR_INVALIDPARAMS if the passed cooperative level combination is invalid
352  *  DDERR_HWNDALREADYSET if DDSCL_SETFOCUSWINDOW is passed in exclusive mode
353  *   (Probably others too, have to investigate)
354  *
355  *****************************************************************************/
356 static HRESULT WINAPI
357 IDirectDrawImpl_SetCooperativeLevel(IDirectDraw7 *iface,
358                                     HWND hwnd,
359                                     DWORD cooplevel)
360 {
361     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
362     HWND window;
363
364     TRACE("(%p)->(%p,%08x)\n",This,hwnd,cooplevel);
365     DDRAW_dump_cooperativelevel(cooplevel);
366
367     EnterCriticalSection(&ddraw_cs);
368
369     /* Get the old window */
370     window = This->dest_window;
371
372     /* Tests suggest that we need one of them: */
373     if(!(cooplevel & (DDSCL_SETFOCUSWINDOW |
374                       DDSCL_NORMAL         |
375                       DDSCL_EXCLUSIVE      )))
376     {
377         TRACE("Incorrect cooplevel flags, returning DDERR_INVALIDPARAMS\n");
378         LeaveCriticalSection(&ddraw_cs);
379         return DDERR_INVALIDPARAMS;
380     }
381
382     /* Handle those levels first which set various hwnds */
383     if(cooplevel & DDSCL_SETFOCUSWINDOW)
384     {
385         /* This isn't compatible with a lot of flags */
386         if(cooplevel & ( DDSCL_MULTITHREADED   |
387                          DDSCL_FPUSETUP        |
388                          DDSCL_FPUPRESERVE     |
389                          DDSCL_ALLOWREBOOT     |
390                          DDSCL_ALLOWMODEX      |
391                          DDSCL_SETDEVICEWINDOW |
392                          DDSCL_NORMAL          |
393                          DDSCL_EXCLUSIVE       |
394                          DDSCL_FULLSCREEN      ) )
395         {
396             TRACE("Called with incompatible flags, returning DDERR_INVALIDPARAMS\n");
397             LeaveCriticalSection(&ddraw_cs);
398             return DDERR_INVALIDPARAMS;
399         }
400         else if( (This->cooperative_level & DDSCL_FULLSCREEN) && window)
401         {
402             TRACE("Setting DDSCL_SETFOCUSWINDOW with an already set window, returning DDERR_HWNDALREADYSET\n");
403             LeaveCriticalSection(&ddraw_cs);
404             return DDERR_HWNDALREADYSET;
405         }
406
407         This->focuswindow = hwnd;
408         /* Won't use the hwnd param for anything else */
409         hwnd = NULL;
410
411         /* Use the focus window for drawing too */
412         This->dest_window = This->focuswindow;
413
414         /* Destroy the device window, if we have one */
415         if(This->devicewindow)
416         {
417             DestroyWindow(This->devicewindow);
418             This->devicewindow = NULL;
419         }
420     }
421     /* DDSCL_NORMAL or DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE */
422     if(cooplevel & DDSCL_NORMAL)
423     {
424         /* Can't coexist with fullscreen or exclusive */
425         if(cooplevel & (DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE) )
426         {
427             TRACE("(%p) DDSCL_NORMAL is not compative with DDSCL_FULLSCREEN or DDSCL_EXCLUSIVE\n", This);
428             LeaveCriticalSection(&ddraw_cs);
429             return DDERR_INVALIDPARAMS;
430         }
431
432         /* Switching from fullscreen? */
433         if(This->cooperative_level & DDSCL_FULLSCREEN)
434         {
435             /* Restore the display mode */
436             IDirectDraw7_RestoreDisplayMode(iface);
437
438             This->cooperative_level &= ~DDSCL_FULLSCREEN;
439             This->cooperative_level &= ~DDSCL_EXCLUSIVE;
440             This->cooperative_level &= ~DDSCL_ALLOWMODEX;
441         }
442
443         /* Don't override focus windows or private device windows */
444         if( hwnd &&
445             !(This->focuswindow) &&
446             !(This->devicewindow) &&
447             (hwnd != window) )
448         {
449             This->dest_window = hwnd;
450         }
451     }
452     else if(cooplevel & DDSCL_FULLSCREEN)
453     {
454         /* Needs DDSCL_EXCLUSIVE */
455         if(!(cooplevel & DDSCL_EXCLUSIVE) )
456         {
457             TRACE("(%p) DDSCL_FULLSCREEN needs DDSCL_EXCLUSIVE\n", This);
458             LeaveCriticalSection(&ddraw_cs);
459             return DDERR_INVALIDPARAMS;
460         }
461         /* Need a HWND
462         if(hwnd == 0)
463         {
464             TRACE("(%p) DDSCL_FULLSCREEN needs a HWND\n", This);
465             return DDERR_INVALIDPARAMS;
466         }
467         */
468
469         This->cooperative_level &= ~DDSCL_NORMAL;
470
471         /* Don't override focus windows or private device windows */
472         if( hwnd &&
473             !(This->focuswindow) &&
474             !(This->devicewindow) &&
475             (hwnd != window) )
476         {
477             This->dest_window = hwnd;
478         }
479     }
480     else if(cooplevel & DDSCL_EXCLUSIVE)
481     {
482         TRACE("(%p) DDSCL_EXCLUSIVE needs DDSCL_FULLSCREEN\n", This);
483         LeaveCriticalSection(&ddraw_cs);
484         return DDERR_INVALIDPARAMS;
485     }
486
487     if(cooplevel & DDSCL_CREATEDEVICEWINDOW)
488     {
489         /* Don't create a device window if a focus window is set */
490         if( !(This->focuswindow) )
491         {
492             HWND devicewindow = CreateWindowExA(0, This->classname, "DDraw device window",
493                                                 WS_POPUP, 0, 0,
494                                                 GetSystemMetrics(SM_CXSCREEN),
495                                                 GetSystemMetrics(SM_CYSCREEN),
496                                                 NULL, NULL, GetModuleHandleA(0), NULL);
497
498             ShowWindow(devicewindow, SW_SHOW);   /* Just to be sure */
499             TRACE("(%p) Created a DDraw device window. HWND=%p\n", This, devicewindow);
500
501             This->devicewindow = devicewindow;
502             This->dest_window = devicewindow;
503         }
504     }
505
506     if(cooplevel & DDSCL_MULTITHREADED && !(This->cooperative_level & DDSCL_MULTITHREADED))
507     {
508         /* Enable thread safety in wined3d */
509         IWineD3DDevice_SetMultithreaded(This->wineD3DDevice);
510     }
511
512     /* Unhandled flags */
513     if(cooplevel & DDSCL_ALLOWREBOOT)
514         WARN("(%p) Unhandled flag DDSCL_ALLOWREBOOT, harmless\n", This);
515     if(cooplevel & DDSCL_ALLOWMODEX)
516         WARN("(%p) Unhandled flag DDSCL_ALLOWMODEX, harmless\n", This);
517     if(cooplevel & DDSCL_FPUSETUP)
518         WARN("(%p) Unhandled flag DDSCL_FPUSETUP, harmless\n", This);
519
520     /* Store the cooperative_level */
521     This->cooperative_level |= cooplevel;
522     TRACE("SetCooperativeLevel retuning DD_OK\n");
523     LeaveCriticalSection(&ddraw_cs);
524     return DD_OK;
525 }
526
527 /*****************************************************************************
528  *
529  * Helper function for SetDisplayMode and RestoreDisplayMode
530  *
531  * Implements DirectDraw's SetDisplayMode, but ignores the value of
532  * ForceRefreshRate, since it is already handled by
533  * IDirectDrawImpl_SetDisplayMode.  RestoreDisplayMode can use this function
534  * without worrying that ForceRefreshRate will override the refresh rate.  For
535  * argument and return value documentation, see
536  * IDirectDrawImpl_SetDisplayMode.
537  *
538  *****************************************************************************/
539 static HRESULT
540 IDirectDrawImpl_SetDisplayModeNoOverride(IDirectDraw7 *iface,
541                                          DWORD Width,
542                                          DWORD Height,
543                                          DWORD BPP,
544                                          DWORD RefreshRate,
545                                          DWORD Flags)
546 {
547     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
548     WINED3DDISPLAYMODE Mode;
549     HRESULT hr;
550     TRACE("(%p)->(%d,%d,%d,%d,%x): Relay!\n", This, Width, Height, BPP, RefreshRate, Flags);
551
552     EnterCriticalSection(&ddraw_cs);
553     if( !Width || !Height )
554     {
555         ERR("Width=%d, Height=%d, what to do?\n", Width, Height);
556         /* It looks like Need for Speed Porsche Unleashed expects DD_OK here */
557         LeaveCriticalSection(&ddraw_cs);
558         return DD_OK;
559     }
560
561     /* Check the exclusive mode
562     if(!(This->cooperative_level & DDSCL_EXCLUSIVE))
563         return DDERR_NOEXCLUSIVEMODE;
564      * This is WRONG. Don't know if the SDK is completely
565      * wrong and if there are any conditions when DDERR_NOEXCLUSIVE
566      * is returned, but Half-Life 1.1.1.1 (Steam version)
567      * depends on this
568      */
569
570     Mode.Width = Width;
571     Mode.Height = Height;
572     Mode.RefreshRate = RefreshRate;
573     switch(BPP)
574     {
575         case 8:  Mode.Format = WINED3DFMT_P8;       break;
576         case 15: Mode.Format = WINED3DFMT_X1R5G5B5; break;
577         case 16: Mode.Format = WINED3DFMT_R5G6B5;   break;
578         case 24: Mode.Format = WINED3DFMT_R8G8B8;   break;
579         case 32: Mode.Format = WINED3DFMT_X8R8G8B8; break;
580     }
581
582     /* TODO: The possible return values from msdn suggest that
583      * the screen mode can't be changed if a surface is locked
584      * or some drawing is in progress
585      */
586
587     /* TODO: Lose the primary surface */
588     hr = IWineD3DDevice_SetDisplayMode(This->wineD3DDevice,
589                                        0, /* First swapchain */
590                                        &Mode);
591     LeaveCriticalSection(&ddraw_cs);
592     switch(hr)
593     {
594         case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
595         default:                            return hr;
596     }
597 }
598
599 /*****************************************************************************
600  * IDirectDraw7::SetDisplayMode
601  *
602  * Sets the display screen resolution, color depth and refresh frequency
603  * when in fullscreen mode (in theory).
604  * Possible return values listed in the SDK suggest that this method fails
605  * when not in fullscreen mode, but this is wrong. Windows 2000 happily sets
606  * the display mode in DDSCL_NORMAL mode without an hwnd specified.
607  * It seems to be valid to pass 0 for With and Height, this has to be tested
608  * It could mean that the current video mode should be left as-is. (But why
609  * call it then?)
610  *
611  * Params:
612  *  Height, Width: Screen dimension
613  *  BPP: Color depth in Bits per pixel
614  *  Refreshrate: Screen refresh rate
615  *  Flags: Other stuff
616  *
617  * Returns
618  *  DD_OK on success
619  *
620  *****************************************************************************/
621 static HRESULT WINAPI
622 IDirectDrawImpl_SetDisplayMode(IDirectDraw7 *iface,
623                                DWORD Width,
624                                DWORD Height,
625                                DWORD BPP,
626                                DWORD RefreshRate,
627                                DWORD Flags)
628 {
629     if (force_refresh_rate != 0)
630     {
631         TRACE("ForceRefreshRate overriding passed-in refresh rate (%d Hz) to %d Hz\n", RefreshRate, force_refresh_rate);
632         RefreshRate = force_refresh_rate;
633     }
634
635     return IDirectDrawImpl_SetDisplayModeNoOverride(iface, Width, Height, BPP,
636                                                     RefreshRate, Flags);
637 }
638
639 /*****************************************************************************
640  * IDirectDraw7::RestoreDisplayMode
641  *
642  * Restores the display mode to what it was at creation time. Basically.
643  *
644  * A problem arises when there are 2 DirectDraw objects using the same hwnd:
645  *  -> DD_1 finds the screen at 1400x1050x32 when created, sets it to 640x480x16
646  *  -> DD_2 is created, finds the screen at 640x480x16, sets it to 1024x768x32
647  *  -> DD_1 is released. The screen should be left at 1024x768x32.
648  *  -> DD_2 is released. The screen should be set to 1400x1050x32
649  * This case is unhandled right now, but Empire Earth does it this way.
650  * (But perhaps there is something in SetCooperativeLevel to prevent this)
651  *
652  * The msdn says that this method resets the display mode to what it was before
653  * SetDisplayMode was called. What if SetDisplayModes is called 2 times??
654  *
655  * Returns
656  *  DD_OK on success
657  *  DDERR_NOEXCLUSIVE mode if the device isn't in fullscreen mode
658  *
659  *****************************************************************************/
660 static HRESULT WINAPI
661 IDirectDrawImpl_RestoreDisplayMode(IDirectDraw7 *iface)
662 {
663     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
664     TRACE("(%p)\n", This);
665
666     return IDirectDrawImpl_SetDisplayModeNoOverride(ICOM_INTERFACE(This, IDirectDraw7),
667                                                     This->orig_width,
668                                                     This->orig_height,
669                                                     This->orig_bpp,
670                                                     0,
671                                                     0);
672 }
673
674 /*****************************************************************************
675  * IDirectDraw7::GetCaps
676  *
677  * Returns the drives capabilities
678  *
679  * Used for version 1, 2, 4 and 7
680  *
681  * Params:
682  *  DriverCaps: Structure to write the Hardware accelerated caps to
683  *  HelCaps: Structure to write the emulation caps to
684  *
685  * Returns
686  *  This implementation returns DD_OK only
687  *
688  *****************************************************************************/
689 static HRESULT WINAPI
690 IDirectDrawImpl_GetCaps(IDirectDraw7 *iface,
691                         DDCAPS *DriverCaps,
692                         DDCAPS *HELCaps)
693 {
694     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
695     DDCAPS caps;
696     WINED3DCAPS winecaps;
697     HRESULT hr;
698     DDSCAPS2 ddscaps = {0, 0, 0, 0};
699     TRACE("(%p)->(%p,%p)\n", This, DriverCaps, HELCaps);
700
701     /* One structure must be != NULL */
702     if( (!DriverCaps) && (!HELCaps) )
703     {
704         ERR("(%p) Invalid params to IDirectDrawImpl_GetCaps\n", This);
705         return DDERR_INVALIDPARAMS;
706     }
707
708     memset(&caps, 0, sizeof(caps));
709     memset(&winecaps, 0, sizeof(winecaps));
710     caps.dwSize = sizeof(caps);
711     EnterCriticalSection(&ddraw_cs);
712     hr = IWineD3DDevice_GetDeviceCaps(This->wineD3DDevice, &winecaps);
713     if(FAILED(hr)) {
714         WARN("IWineD3DDevice::GetDeviceCaps failed\n");
715         LeaveCriticalSection(&ddraw_cs);
716         return hr;
717     }
718
719     hr = IDirectDraw7_GetAvailableVidMem(iface, &ddscaps, &caps.dwVidMemTotal, &caps.dwVidMemFree);
720     LeaveCriticalSection(&ddraw_cs);
721     if(FAILED(hr)) {
722         WARN("IDirectDraw7::GetAvailableVidMem failed\n");
723         return hr;
724     }
725
726     caps.dwCaps = winecaps.DirectDrawCaps.Caps;
727     caps.dwCaps2 = winecaps.DirectDrawCaps.Caps2;
728     caps.dwCKeyCaps = winecaps.DirectDrawCaps.CKeyCaps;
729     caps.dwFXCaps = winecaps.DirectDrawCaps.FXCaps;
730     caps.dwPalCaps = winecaps.DirectDrawCaps.PalCaps;
731     caps.ddsCaps.dwCaps = winecaps.DirectDrawCaps.ddsCaps;
732     caps.dwSVBCaps = winecaps.DirectDrawCaps.SVBCaps;
733     caps.dwSVBCKeyCaps = winecaps.DirectDrawCaps.SVBCKeyCaps;
734     caps.dwSVBFXCaps = winecaps.DirectDrawCaps.SVBFXCaps;
735     caps.dwVSBCaps = winecaps.DirectDrawCaps.VSBCaps;
736     caps.dwVSBCKeyCaps = winecaps.DirectDrawCaps.VSBCKeyCaps;
737     caps.dwVSBFXCaps = winecaps.DirectDrawCaps.VSBFXCaps;
738     caps.dwSSBCaps = winecaps.DirectDrawCaps.SSBCaps;
739     caps.dwSSBCKeyCaps = winecaps.DirectDrawCaps.SSBCKeyCaps;
740     caps.dwSSBFXCaps = winecaps.DirectDrawCaps.SSBFXCaps;
741
742     /* Even if WineD3D supports 3D rendering, remove the cap if ddraw is configured
743      * not to use it
744      */
745     if(DefaultSurfaceType == SURFACE_GDI) {
746         caps.dwCaps &= ~DDCAPS_3D;
747         caps.ddsCaps.dwCaps &= ~(DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER);
748     }
749     if(winecaps.DirectDrawCaps.StrideAlign != 0) {
750         caps.dwCaps |= DDCAPS_ALIGNSTRIDE;
751         caps.dwAlignStrideAlign = winecaps.DirectDrawCaps.StrideAlign;
752     }
753
754     if(DriverCaps)
755     {
756         DD_STRUCT_COPY_BYSIZE(DriverCaps, &caps);
757         if (TRACE_ON(ddraw))
758         {
759             TRACE("Driver Caps :\n");
760             DDRAW_dump_DDCAPS(DriverCaps);
761         }
762
763     }
764     if(HELCaps)
765     {
766         DD_STRUCT_COPY_BYSIZE(HELCaps, &caps);
767         if (TRACE_ON(ddraw))
768         {
769             TRACE("HEL Caps :\n");
770             DDRAW_dump_DDCAPS(HELCaps);
771         }
772     }
773
774     return DD_OK;
775 }
776
777 /*****************************************************************************
778  * IDirectDraw7::Compact
779  *
780  * No idea what it does, MSDN says it's not implemented.
781  *
782  * Returns
783  *  DD_OK, but this is unchecked
784  *
785  *****************************************************************************/
786 static HRESULT WINAPI
787 IDirectDrawImpl_Compact(IDirectDraw7 *iface)
788 {
789     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
790     TRACE("(%p)\n", This);
791
792     return DD_OK;
793 }
794
795 /*****************************************************************************
796  * IDirectDraw7::GetDisplayMode
797  *
798  * Returns information about the current display mode
799  *
800  * Exists in Version 1, 2, 4 and 7
801  *
802  * Params:
803  *  DDSD: Address of a surface description structure to write the info to
804  *
805  * Returns
806  *  DD_OK
807  *
808  *****************************************************************************/
809 static HRESULT WINAPI
810 IDirectDrawImpl_GetDisplayMode(IDirectDraw7 *iface,
811                                DDSURFACEDESC2 *DDSD)
812 {
813     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
814     HRESULT hr;
815     WINED3DDISPLAYMODE Mode;
816     DWORD Size;
817     TRACE("(%p)->(%p): Relay\n", This, DDSD);
818
819     EnterCriticalSection(&ddraw_cs);
820     /* This seems sane */
821     if(!DDSD) 
822     {
823         LeaveCriticalSection(&ddraw_cs);
824         return DDERR_INVALIDPARAMS;
825     }
826
827     /* The necessary members of LPDDSURFACEDESC and LPDDSURFACEDESC2 are equal,
828      * so one method can be used for all versions (Hopefully)
829      */
830     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
831                                       0 /* swapchain 0 */,
832                                       &Mode);
833     if( hr != D3D_OK )
834     {
835         ERR(" (%p) IWineD3DDevice::GetDisplayMode returned %08x\n", This, hr);
836         LeaveCriticalSection(&ddraw_cs);
837         return hr;
838     }
839
840     Size = DDSD->dwSize;
841     memset(DDSD, 0, Size);
842
843     DDSD->dwSize = Size;
844     DDSD->dwFlags |= DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_PITCH | DDSD_REFRESHRATE;
845     DDSD->dwWidth = Mode.Width;
846     DDSD->dwHeight = Mode.Height; 
847     DDSD->u2.dwRefreshRate = 60;
848     DDSD->ddsCaps.dwCaps = 0;
849     DDSD->u4.ddpfPixelFormat.dwSize = sizeof(DDSD->u4.ddpfPixelFormat);
850     PixelFormat_WineD3DtoDD(&DDSD->u4.ddpfPixelFormat, Mode.Format);
851     DDSD->u1.lPitch = Mode.Width * DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount / 8;
852
853     if(TRACE_ON(ddraw))
854     {
855         TRACE("Returning surface desc :\n");
856         DDRAW_dump_surface_desc(DDSD);
857     }
858
859     LeaveCriticalSection(&ddraw_cs);
860     return DD_OK;
861 }
862
863 /*****************************************************************************
864  * IDirectDraw7::GetFourCCCodes
865  *
866  * Returns an array of supported FourCC codes.
867  *
868  * Exists in Version 1, 2, 4 and 7
869  *
870  * Params:
871  *  NumCodes: Contains the number of Codes that Codes can carry. Returns the number
872  *            of enumerated codes
873  *  Codes: Pointer to an array of DWORDs where the supported codes are written
874  *         to
875  *
876  * Returns
877  *  Always returns DD_OK, as it's a stub for now
878  *
879  *****************************************************************************/
880 static HRESULT WINAPI
881 IDirectDrawImpl_GetFourCCCodes(IDirectDraw7 *iface,
882                                DWORD *NumCodes, DWORD *Codes)
883 {
884     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
885     WINED3DFORMAT formats[] = {
886         WINED3DFMT_YUY2, WINED3DFMT_UYVY, WINED3DFMT_YV12,
887         WINED3DFMT_DXT1, WINED3DFMT_DXT2, WINED3DFMT_DXT3, WINED3DFMT_DXT4, WINED3DFMT_DXT5,
888         WINED3DFMT_ATI2N, WINED3DFMT_NVHU, WINED3DFMT_NVHS
889     };
890     DWORD count = 0, i, outsize;
891     HRESULT hr;
892     WINED3DDISPLAYMODE d3ddm;
893     WINED3DSURFTYPE type = This->ImplType;
894     TRACE("(%p)->(%p, %p)\n", This, NumCodes, Codes);
895
896     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
897                                   0 /* swapchain 0 */,
898                                   &d3ddm);
899
900     outsize = NumCodes && Codes ? *NumCodes : 0;
901
902     if(type == SURFACE_UNKNOWN) type = SURFACE_GDI;
903
904     for(i = 0; i < (sizeof(formats) / sizeof(formats[0])); i++) {
905         hr = IWineD3D_CheckDeviceFormat(This->wineD3D,
906                                         WINED3DADAPTER_DEFAULT,
907                                         WINED3DDEVTYPE_HAL,
908                                         d3ddm.Format /* AdapterFormat */,
909                                         0 /* usage */,
910                                         WINED3DRTYPE_SURFACE,
911                                         formats[i],
912                                         type);
913         if(SUCCEEDED(hr)) {
914             if(count < outsize) {
915                 Codes[count] = formats[i];
916             }
917             count++;
918         }
919     }
920     if(NumCodes) {
921         TRACE("Returning %u FourCC codes\n", count);
922         *NumCodes = count;
923     }
924
925     return DD_OK;
926 }
927
928 /*****************************************************************************
929  * IDirectDraw7::GetMonitorFrequency
930  *
931  * Returns the monitor's frequency
932  *
933  * Exists in Version 1, 2, 4 and 7
934  *
935  * Params:
936  *  Freq: Pointer to a DWORD to write the frequency to
937  *
938  * Returns
939  *  Always returns DD_OK
940  *
941  *****************************************************************************/
942 static HRESULT WINAPI
943 IDirectDrawImpl_GetMonitorFrequency(IDirectDraw7 *iface,
944                                     DWORD *Freq)
945 {
946     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
947     TRACE("(%p)->(%p)\n", This, Freq);
948
949     /* Ideally this should be in WineD3D, as it concerns the screen setup,
950      * but for now this should make the games happy
951      */
952     *Freq = 60;
953     return DD_OK;
954 }
955
956 /*****************************************************************************
957  * IDirectDraw7::GetVerticalBlankStatus
958  *
959  * Returns the Vertical blank status of the monitor. This should be in WineD3D
960  * too basically, but as it's a semi stub, I didn't create a function there
961  *
962  * Params:
963  *  status: Pointer to a BOOL to be filled with the vertical blank status
964  *
965  * Returns
966  *  DD_OK on success
967  *  DDERR_INVALIDPARAMS if status is NULL
968  *
969  *****************************************************************************/
970 static HRESULT WINAPI
971 IDirectDrawImpl_GetVerticalBlankStatus(IDirectDraw7 *iface,
972                                        BOOL *status)
973 {
974     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
975     TRACE("(%p)->(%p)\n", This, status);
976
977     /* This looks sane, the MSDN suggests it too */
978     EnterCriticalSection(&ddraw_cs);
979     if(!status)
980     {
981         LeaveCriticalSection(&ddraw_cs);
982         return DDERR_INVALIDPARAMS;
983     }
984
985     *status = This->fake_vblank;
986     This->fake_vblank = !This->fake_vblank;
987     LeaveCriticalSection(&ddraw_cs);
988     return DD_OK;
989 }
990
991 /*****************************************************************************
992  * IDirectDraw7::GetAvailableVidMem
993  *
994  * Returns the total and free video memory
995  *
996  * Params:
997  *  Caps: Specifies the memory type asked for
998  *  total: Pointer to a DWORD to be filled with the total memory
999  *  free: Pointer to a DWORD to be filled with the free memory
1000  *
1001  * Returns
1002  *  DD_OK on success
1003  *  DDERR_INVALIDPARAMS of free and total are NULL
1004  *
1005  *****************************************************************************/
1006 static HRESULT WINAPI
1007 IDirectDrawImpl_GetAvailableVidMem(IDirectDraw7 *iface, DDSCAPS2 *Caps, DWORD *total, DWORD *free)
1008 {
1009     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1010     TRACE("(%p)->(%p, %p, %p)\n", This, Caps, total, free);
1011
1012     if(TRACE_ON(ddraw))
1013     {
1014         TRACE("(%p) Asked for memory with description: ", This);
1015         DDRAW_dump_DDSCAPS2(Caps);
1016     }
1017     EnterCriticalSection(&ddraw_cs);
1018
1019     /* Todo: System memory vs local video memory vs non-local video memory
1020      * The MSDN also mentions differences between texture memory and other
1021      * resources, but that's not important
1022      */
1023
1024     if( (!total) && (!free) )
1025     {
1026         LeaveCriticalSection(&ddraw_cs);
1027         return DDERR_INVALIDPARAMS;
1028     }
1029
1030     if(total) *total = This->total_vidmem;
1031     if(free) *free = IWineD3DDevice_GetAvailableTextureMem(This->wineD3DDevice);
1032
1033     LeaveCriticalSection(&ddraw_cs);
1034     return DD_OK;
1035 }
1036
1037 /*****************************************************************************
1038  * IDirectDraw7::Initialize
1039  *
1040  * Initializes a DirectDraw interface.
1041  *
1042  * Params:
1043  *  GUID: Interface identifier. Well, don't know what this is really good
1044  *   for
1045  *
1046  * Returns
1047  *  Returns DD_OK on the first call,
1048  *  DDERR_ALREADYINITIALIZED on repeated calls
1049  *
1050  *****************************************************************************/
1051 static HRESULT WINAPI
1052 IDirectDrawImpl_Initialize(IDirectDraw7 *iface,
1053                            GUID *Guid)
1054 {
1055     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1056     TRACE("(%p)->(%s): No-op\n", This, debugstr_guid(Guid));
1057
1058     if(This->initialized)
1059     {
1060         return DDERR_ALREADYINITIALIZED;
1061     }
1062     else
1063     {
1064         return DD_OK;
1065     }
1066 }
1067
1068 /*****************************************************************************
1069  * IDirectDraw7::FlipToGDISurface
1070  *
1071  * "Makes the surface that the GDI writes to the primary surface"
1072  * Looks like some windows specific thing we don't have to care about.
1073  * According to MSDN it permits GDI dialog boxes in FULLSCREEN mode. Good to
1074  * show error boxes ;)
1075  * Well, just return DD_OK.
1076  *
1077  * Returns:
1078  *  Always returns DD_OK
1079  *
1080  *****************************************************************************/
1081 static HRESULT WINAPI
1082 IDirectDrawImpl_FlipToGDISurface(IDirectDraw7 *iface)
1083 {
1084     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1085     TRACE("(%p)\n", This);
1086
1087     return DD_OK;
1088 }
1089
1090 /*****************************************************************************
1091  * IDirectDraw7::WaitForVerticalBlank
1092  *
1093  * This method allows applications to get in sync with the vertical blank
1094  * interval.
1095  * The wormhole demo in the DirectX 7 sdk uses this call, and it doesn't
1096  * redraw the screen, most likely because of this stub
1097  *
1098  * Parameters:
1099  *  Flags: one of DDWAITVB_BLOCKBEGIN, DDWAITVB_BLOCKBEGINEVENT
1100  *         or DDWAITVB_BLOCKEND
1101  *  h: Not used, according to MSDN
1102  *
1103  * Returns:
1104  *  Always returns DD_OK
1105  *
1106  *****************************************************************************/ 
1107 static HRESULT WINAPI
1108 IDirectDrawImpl_WaitForVerticalBlank(IDirectDraw7 *iface,
1109                                      DWORD Flags,
1110                                      HANDLE h)
1111 {
1112     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1113     static BOOL hide = FALSE;
1114
1115     /* This function is called often, so print the fixme only once */
1116     if(!hide)
1117     {
1118         FIXME("(%p)->(%x,%p): Stub\n", This, Flags, h);
1119         hide = TRUE;
1120     }
1121
1122     /* MSDN says DDWAITVB_BLOCKBEGINEVENT is not supported */
1123     if(Flags & DDWAITVB_BLOCKBEGINEVENT)
1124         return DDERR_UNSUPPORTED; /* unchecked */
1125
1126     return DD_OK;
1127 }
1128
1129 /*****************************************************************************
1130  * IDirectDraw7::GetScanLine
1131  *
1132  * Returns the scan line that is being drawn on the monitor
1133  *
1134  * Parameters:
1135  *  Scanline: Address to write the scan line value to
1136  *
1137  * Returns:
1138  *  Always returns DD_OK
1139  *
1140  *****************************************************************************/ 
1141 static HRESULT WINAPI IDirectDrawImpl_GetScanLine(IDirectDraw7 *iface, DWORD *Scanline)
1142 {
1143     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1144     static BOOL hide = FALSE;
1145     WINED3DDISPLAYMODE Mode;
1146
1147     /* This function is called often, so print the fixme only once */
1148     EnterCriticalSection(&ddraw_cs);
1149     if(!hide)
1150     {
1151         FIXME("(%p)->(%p): Semi-Stub\n", This, Scanline);
1152         hide = TRUE;
1153     }
1154
1155     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1156                                   0,
1157                                   &Mode);
1158
1159     /* Fake the line sweeping of the monitor */
1160     /* FIXME: We should synchronize with a source to keep the refresh rate */ 
1161     *Scanline = This->cur_scanline++;
1162     /* Assume 20 scan lines in the vertical blank */
1163     if (This->cur_scanline >= Mode.Height + 20)
1164         This->cur_scanline = 0;
1165
1166     LeaveCriticalSection(&ddraw_cs);
1167     return DD_OK;
1168 }
1169
1170 /*****************************************************************************
1171  * IDirectDraw7::TestCooperativeLevel
1172  *
1173  * Informs the application about the state of the video adapter, depending
1174  * on the cooperative level
1175  *
1176  * Returns:
1177  *  DD_OK if the device is in a sane state
1178  *  DDERR_NOEXCLUSIVEMODE or DDERR_EXCLUSIVEMODEALREADYSET
1179  *  if the state is not correct(See below)
1180  *
1181  *****************************************************************************/ 
1182 static HRESULT WINAPI
1183 IDirectDrawImpl_TestCooperativeLevel(IDirectDraw7 *iface)
1184 {
1185     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1186     HRESULT hr;
1187     TRACE("(%p)\n", This);
1188
1189     EnterCriticalSection(&ddraw_cs);
1190     /* Description from MSDN:
1191      * For fullscreen apps return DDERR_NOEXCLUSIVEMODE if the user switched
1192      * away from the app with e.g. alt-tab. Windowed apps receive 
1193      * DDERR_EXCLUSIVEMODEALREADYSET if another application created a 
1194      * DirectDraw object in exclusive mode. DDERR_WRONGMODE is returned,
1195      * when the video mode has changed
1196      */
1197
1198     hr =  IWineD3DDevice_TestCooperativeLevel(This->wineD3DDevice);
1199
1200     /* Fix the result value. These values are mapped from their
1201      * d3d9 counterpart.
1202      */
1203     switch(hr)
1204     {
1205         case WINED3DERR_DEVICELOST:
1206             if(This->cooperative_level & DDSCL_EXCLUSIVE)
1207             {
1208                 LeaveCriticalSection(&ddraw_cs);
1209                 return DDERR_NOEXCLUSIVEMODE;
1210             }
1211             else
1212             {
1213                 LeaveCriticalSection(&ddraw_cs);
1214                 return DDERR_EXCLUSIVEMODEALREADYSET;
1215             }
1216
1217         case WINED3DERR_DEVICENOTRESET:
1218             LeaveCriticalSection(&ddraw_cs);
1219             return DD_OK;
1220
1221         case WINED3D_OK:
1222             LeaveCriticalSection(&ddraw_cs);
1223             return DD_OK;
1224
1225         case WINED3DERR_DRIVERINTERNALERROR:
1226         default:
1227             ERR("(%p) Unexpected return value %08x from wineD3D, "
1228                 " returning DD_OK\n", This, hr);
1229     }
1230
1231     LeaveCriticalSection(&ddraw_cs);
1232     return DD_OK;
1233 }
1234
1235 /*****************************************************************************
1236  * IDirectDraw7::GetGDISurface
1237  *
1238  * Returns the surface that GDI is treating as the primary surface.
1239  * For Wine this is the front buffer
1240  *
1241  * Params:
1242  *  GDISurface: Address to write the surface pointer to
1243  *
1244  * Returns:
1245  *  DD_OK if the surface was found
1246  *  DDERR_NOTFOUND if the GDI surface wasn't found
1247  *
1248  *****************************************************************************/ 
1249 static HRESULT WINAPI
1250 IDirectDrawImpl_GetGDISurface(IDirectDraw7 *iface,
1251                               IDirectDrawSurface7 **GDISurface)
1252 {
1253     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1254     IWineD3DSurface *Surf;
1255     IDirectDrawSurface7 *ddsurf;
1256     HRESULT hr;
1257     DDSCAPS2 ddsCaps;
1258     TRACE("(%p)->(%p)\n", This, GDISurface);
1259
1260     /* Get the back buffer from the wineD3DDevice and search its
1261      * attached surfaces for the front buffer
1262      */
1263     EnterCriticalSection(&ddraw_cs);
1264     hr = IWineD3DDevice_GetBackBuffer(This->wineD3DDevice,
1265                                       0, /* SwapChain */
1266                                       0, /* first back buffer*/
1267                                       WINED3DBACKBUFFER_TYPE_MONO,
1268                                       &Surf);
1269
1270     if( (hr != D3D_OK) ||
1271         (!Surf) )
1272     {
1273         ERR("IWineD3DDevice::GetBackBuffer failed\n");
1274         LeaveCriticalSection(&ddraw_cs);
1275         return DDERR_NOTFOUND;
1276     }
1277
1278     /* GetBackBuffer AddRef()ed the surface, release it */
1279     IWineD3DSurface_Release(Surf);
1280
1281     IWineD3DSurface_GetParent(Surf,
1282                               (IUnknown **) &ddsurf);
1283     IDirectDrawSurface7_Release(ddsurf);  /* For the GetParent */
1284
1285     /* Find the front buffer */
1286     ddsCaps.dwCaps = DDSCAPS_FRONTBUFFER;
1287     hr = IDirectDrawSurface7_GetAttachedSurface(ddsurf,
1288                                                 &ddsCaps,
1289                                                 GDISurface);
1290     if(hr != DD_OK)
1291     {
1292         ERR("IDirectDrawSurface7::GetAttachedSurface failed, hr = %x\n", hr);
1293     }
1294
1295     /* The AddRef is OK this time */
1296     LeaveCriticalSection(&ddraw_cs);
1297     return hr;
1298 }
1299
1300 /*****************************************************************************
1301  * IDirectDraw7::EnumDisplayModes
1302  *
1303  * Enumerates the supported Display modes. The modes can be filtered with
1304  * the DDSD parameter.
1305  *
1306  * Params:
1307  *  Flags: can be DDEDM_REFRESHRATES and DDEDM_STANDARDVGAMODES
1308  *  DDSD: Surface description to filter the modes
1309  *  Context: Pointer passed back to the callback function
1310  *  cb: Application-provided callback function
1311  *
1312  * Returns:
1313  *  DD_OK on success
1314  *  DDERR_INVALIDPARAMS if the callback wasn't set
1315  *
1316  *****************************************************************************/ 
1317 static HRESULT WINAPI
1318 IDirectDrawImpl_EnumDisplayModes(IDirectDraw7 *iface,
1319                                  DWORD Flags,
1320                                  DDSURFACEDESC2 *DDSD,
1321                                  void *Context,
1322                                  LPDDENUMMODESCALLBACK2 cb)
1323 {
1324     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1325     unsigned int modenum, fmt;
1326     WINED3DFORMAT pixelformat = WINED3DFMT_UNKNOWN;
1327     WINED3DDISPLAYMODE mode;
1328     DDSURFACEDESC2 callback_sd;
1329     WINED3DDISPLAYMODE *enum_modes = NULL;
1330     unsigned enum_mode_count = 0, enum_mode_array_size = 0;
1331
1332     WINED3DFORMAT checkFormatList[] =
1333     {
1334         WINED3DFMT_R8G8B8,
1335         WINED3DFMT_A8R8G8B8,
1336         WINED3DFMT_X8R8G8B8,
1337         WINED3DFMT_R5G6B5,
1338         WINED3DFMT_X1R5G5B5,
1339         WINED3DFMT_A1R5G5B5,
1340         WINED3DFMT_A4R4G4B4,
1341         WINED3DFMT_R3G3B2,
1342         WINED3DFMT_A8R3G3B2,
1343         WINED3DFMT_X4R4G4B4,
1344         WINED3DFMT_A2B10G10R10,
1345         WINED3DFMT_A8B8G8R8,
1346         WINED3DFMT_X8B8G8R8,
1347         WINED3DFMT_A2R10G10B10,
1348         WINED3DFMT_A8P8,
1349         WINED3DFMT_P8
1350     };
1351
1352     TRACE("(%p)->(%p,%p,%p): Relay\n", This, DDSD, Context, cb);
1353
1354     EnterCriticalSection(&ddraw_cs);
1355     /* This looks sane */
1356     if(!cb)
1357     {
1358         LeaveCriticalSection(&ddraw_cs);
1359         return DDERR_INVALIDPARAMS;
1360     }
1361
1362     if(DDSD)
1363     {
1364         if ((DDSD->dwFlags & DDSD_PIXELFORMAT) && (DDSD->u4.ddpfPixelFormat.dwFlags & DDPF_RGB) )
1365             pixelformat = PixelFormat_DD2WineD3D(&DDSD->u4.ddpfPixelFormat);
1366     }
1367
1368     if(!(Flags & DDEDM_REFRESHRATES))
1369     {
1370         enum_mode_array_size = 16;
1371         enum_modes = HeapAlloc(GetProcessHeap(), 0, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
1372         if (!enum_modes)
1373         {
1374             ERR("Out of memory\n");
1375             LeaveCriticalSection(&ddraw_cs);
1376             return DDERR_OUTOFMEMORY;
1377         }
1378     }
1379
1380     for(fmt = 0; fmt < (sizeof(checkFormatList) / sizeof(checkFormatList[0])); fmt++)
1381     {
1382         if(pixelformat != WINED3DFMT_UNKNOWN && checkFormatList[fmt] != pixelformat)
1383         {
1384             continue;
1385         }
1386
1387         modenum = 0;
1388         while(IWineD3D_EnumAdapterModes(This->wineD3D,
1389                                         WINED3DADAPTER_DEFAULT,
1390                                         checkFormatList[fmt],
1391                                         modenum++,
1392                                         &mode) == WINED3D_OK)
1393         {
1394             if(DDSD)
1395             {
1396                 if(DDSD->dwFlags & DDSD_WIDTH && mode.Width != DDSD->dwWidth) continue;
1397                 if(DDSD->dwFlags & DDSD_HEIGHT && mode.Height != DDSD->dwHeight) continue;
1398             }
1399
1400             if(!(Flags & DDEDM_REFRESHRATES))
1401             {
1402                 /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
1403                  * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
1404                  * to be reduced to a single unique result in such case.
1405                  */
1406                 BOOL found = FALSE;
1407                 unsigned i;
1408
1409                 for (i = 0; i < enum_mode_count; i++)
1410                 {
1411                     if(enum_modes[i].Width == mode.Width && enum_modes[i].Height == mode.Height &&
1412                        enum_modes[i].Format == mode.Format)
1413                     {
1414                         found = TRUE;
1415                         break;
1416                     }
1417                 }
1418
1419                 if(found) continue;
1420             }
1421
1422             memset(&callback_sd, 0, sizeof(callback_sd));
1423             callback_sd.dwSize = sizeof(callback_sd);
1424             callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1425
1426             callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH;
1427             if(Flags & DDEDM_REFRESHRATES)
1428             {
1429                 callback_sd.dwFlags |= DDSD_REFRESHRATE;
1430                 callback_sd.u2.dwRefreshRate = mode.RefreshRate;
1431             }
1432
1433             callback_sd.dwWidth = mode.Width;
1434             callback_sd.dwHeight = mode.Height;
1435
1436             PixelFormat_WineD3DtoDD(&callback_sd.u4.ddpfPixelFormat, mode.Format);
1437
1438             /* Calc pitch and DWORD align like MSDN says */
1439             callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.Width;
1440             callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;
1441
1442             TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
1443               callback_sd.u2.dwRefreshRate);
1444
1445             if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
1446             {
1447                 TRACE("Application asked to terminate the enumeration\n");
1448                 HeapFree(GetProcessHeap(), 0, enum_modes);
1449                 LeaveCriticalSection(&ddraw_cs);
1450                 return DD_OK;
1451             }
1452
1453             if(!(Flags & DDEDM_REFRESHRATES))
1454             {
1455                 if (enum_mode_count == enum_mode_array_size)
1456                 {
1457                     WINED3DDISPLAYMODE *new_enum_modes;
1458
1459                     enum_mode_array_size *= 2;
1460                     new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
1461
1462                     if (!new_enum_modes)
1463                     {
1464                         ERR("Out of memory\n");
1465                         HeapFree(GetProcessHeap(), 0, enum_modes);
1466                         LeaveCriticalSection(&ddraw_cs);
1467                         return DDERR_OUTOFMEMORY;
1468                     }
1469
1470                     enum_modes = new_enum_modes;
1471                 }
1472
1473                 enum_modes[enum_mode_count++] = mode;
1474             }
1475         }
1476     }
1477
1478     TRACE("End of enumeration\n");
1479     HeapFree(GetProcessHeap(), 0, enum_modes);
1480     LeaveCriticalSection(&ddraw_cs);
1481     return DD_OK;
1482 }
1483
1484 /*****************************************************************************
1485  * IDirectDraw7::EvaluateMode
1486  *
1487  * Used with IDirectDraw7::StartModeTest to test video modes.
1488  * EvaluateMode is used to pass or fail a mode, and continue with the next
1489  * mode
1490  *
1491  * Params:
1492  *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
1493  *  Timeout: Returns the amount of seconds left before the mode would have
1494  *           been failed automatically
1495  *
1496  * Returns:
1497  *  This implementation always DD_OK, because it's a stub
1498  *
1499  *****************************************************************************/
1500 static HRESULT WINAPI
1501 IDirectDrawImpl_EvaluateMode(IDirectDraw7 *iface,
1502                              DWORD Flags,
1503                              DWORD *Timeout)
1504 {
1505     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1506     FIXME("(%p)->(%d,%p): Stub!\n", This, Flags, Timeout);
1507
1508     /* When implementing this, implement it in WineD3D */
1509
1510     return DD_OK;
1511 }
1512
1513 /*****************************************************************************
1514  * IDirectDraw7::GetDeviceIdentifier
1515  *
1516  * Returns the device identifier, which gives information about the driver
1517  * Our device identifier is defined at the beginning of this file.
1518  *
1519  * Params:
1520  *  DDDI: Address for the returned structure
1521  *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
1522  *
1523  * Returns:
1524  *  On success it returns DD_OK
1525  *  DDERR_INVALIDPARAMS if DDDI is NULL
1526  *
1527  *****************************************************************************/
1528 static HRESULT WINAPI
1529 IDirectDrawImpl_GetDeviceIdentifier(IDirectDraw7 *iface,
1530                                     DDDEVICEIDENTIFIER2 *DDDI,
1531                                     DWORD Flags)
1532 {
1533     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1534     TRACE("(%p)->(%p,%08x)\n", This, DDDI, Flags);
1535
1536     if(!DDDI)
1537         return DDERR_INVALIDPARAMS;
1538
1539     /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
1540      * host adapter, if there's a secondary 3D adapter. This doesn't apply
1541      * to any modern hardware, nor is it interesting for Wine, so ignore it
1542      */
1543
1544     *DDDI = deviceidentifier;
1545     return DD_OK;
1546 }
1547
1548 /*****************************************************************************
1549  * IDirectDraw7::GetSurfaceFromDC
1550  *
1551  * Returns the Surface for a GDI device context handle.
1552  * Is this related to IDirectDrawSurface::GetDC ???
1553  *
1554  * Params:
1555  *  hdc: hdc to return the surface for
1556  *  Surface: Address to write the surface pointer to
1557  *
1558  * Returns:
1559  *  Always returns DD_OK because it's a stub
1560  *
1561  *****************************************************************************/
1562 static HRESULT WINAPI
1563 IDirectDrawImpl_GetSurfaceFromDC(IDirectDraw7 *iface,
1564                                  HDC hdc,
1565                                  IDirectDrawSurface7 **Surface)
1566 {
1567     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1568     FIXME("(%p)->(%p,%p): Stub!\n", This, hdc, Surface);
1569
1570     /* Implementation idea if needed: Loop through all surfaces and compare
1571      * their hdc with hdc. Implement it in WineD3D! */
1572     return DDERR_NOTFOUND;
1573 }
1574
1575 /*****************************************************************************
1576  * IDirectDraw7::RestoreAllSurfaces
1577  *
1578  * Calls the restore method of all surfaces
1579  *
1580  * Params:
1581  *
1582  * Returns:
1583  *  Always returns DD_OK because it's a stub
1584  *
1585  *****************************************************************************/
1586 static HRESULT WINAPI
1587 IDirectDrawImpl_RestoreAllSurfaces(IDirectDraw7 *iface)
1588 {
1589     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1590     FIXME("(%p): Stub\n", This);
1591
1592     /* This isn't hard to implement: Enumerate all WineD3D surfaces,
1593      * get their parent and call their restore method. Do not implement
1594      * it in WineD3D, as restoring a surface means re-creating the
1595      * WineD3DDSurface
1596      */
1597     return DD_OK;
1598 }
1599
1600 /*****************************************************************************
1601  * IDirectDraw7::StartModeTest
1602  *
1603  * Tests the specified video modes to update the system registry with
1604  * refresh rate information. StartModeTest starts the mode test,
1605  * EvaluateMode is used to fail or pass a mode. If EvaluateMode
1606  * isn't called within 15 seconds, the mode is failed automatically
1607  *
1608  * As refresh rates are handled by the X server, I don't think this
1609  * Method is important
1610  *
1611  * Params:
1612  *  Modes: An array of mode specifications
1613  *  NumModes: The number of modes in Modes
1614  *  Flags: Some flags...
1615  *
1616  * Returns:
1617  *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
1618  *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
1619  *  otherwise DD_OK
1620  *
1621  *****************************************************************************/
1622 static HRESULT WINAPI
1623 IDirectDrawImpl_StartModeTest(IDirectDraw7 *iface,
1624                               SIZE *Modes,
1625                               DWORD NumModes,
1626                               DWORD Flags)
1627 {
1628     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
1629     WARN("(%p)->(%p, %d, %x): Semi-Stub, most likely harmless\n", This, Modes, NumModes, Flags);
1630
1631     /* This looks sane */
1632     if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;
1633
1634     /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
1635      * As it is not, DDERR_TESTFINISHED is returned
1636      * (hopefully that's correct
1637      *
1638     if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
1639      * well, that value doesn't (yet) exist in the wine headers, so ignore it
1640      */
1641
1642     return DD_OK;
1643 }
1644
1645 /*****************************************************************************
1646  * IDirectDrawImpl_RecreateSurfacesCallback
1647  *
1648  * Enumeration callback for IDirectDrawImpl_RecreateAllSurfaces.
1649  * It re-recreates the WineD3DSurface. It's pretty straightforward
1650  *
1651  *****************************************************************************/
1652 HRESULT WINAPI
1653 IDirectDrawImpl_RecreateSurfacesCallback(IDirectDrawSurface7 *surf,
1654                                          DDSURFACEDESC2 *desc,
1655                                          void *Context)
1656 {
1657     IDirectDrawSurfaceImpl *surfImpl = ICOM_OBJECT(IDirectDrawSurfaceImpl,
1658                                                    IDirectDrawSurface7,
1659                                                    surf);
1660     IDirectDrawImpl *This = surfImpl->ddraw;
1661     IUnknown *Parent;
1662     IParentImpl *parImpl = NULL;
1663     IWineD3DSurface *wineD3DSurface;
1664     IWineD3DSwapChain *swapchain;
1665     HRESULT hr;
1666     void *tmp;
1667     IWineD3DClipper *clipper = NULL;
1668
1669     WINED3DSURFACE_DESC     Desc;
1670     WINED3DFORMAT           Format;
1671     WINED3DRESOURCETYPE     Type;
1672     DWORD                   Usage;
1673     WINED3DPOOL             Pool;
1674     UINT                    Size;
1675
1676     WINED3DMULTISAMPLE_TYPE MultiSampleType;
1677     DWORD                   MultiSampleQuality;
1678     UINT                    Width;
1679     UINT                    Height;
1680
1681     TRACE("(%p): Enumerated Surface %p\n", This, surfImpl);
1682
1683     /* For the enumeration */
1684     IDirectDrawSurface7_Release(surf);
1685
1686     if(surfImpl->ImplType == This->ImplType) return DDENUMRET_OK; /* Continue */
1687
1688     /* Get the objects */
1689     swapchain = surfImpl->wineD3DSwapChain;
1690     surfImpl->wineD3DSwapChain = NULL;
1691     wineD3DSurface = surfImpl->WineD3DSurface;
1692     IWineD3DSurface_GetParent(wineD3DSurface, &Parent);
1693     IUnknown_Release(Parent); /* For the getParent */
1694
1695     /* Is the parent an IParent interface? */
1696     if(IUnknown_QueryInterface(Parent, &IID_IParent, &tmp) == S_OK)
1697     {
1698         /* It is a IParent interface! */
1699         IUnknown_Release(Parent); /* For the QueryInterface */
1700         parImpl = ICOM_OBJECT(IParentImpl, IParent, Parent);
1701         /* Release the reference the parent interface is holding */
1702         IWineD3DSurface_Release(wineD3DSurface);
1703     }
1704
1705     /* get the clipper */
1706     IWineD3DSurface_GetClipper(wineD3DSurface, &clipper);
1707
1708     /* Get the surface properties */
1709     Desc.Format = &Format;
1710     Desc.Type = &Type;
1711     Desc.Usage = &Usage;
1712     Desc.Pool = &Pool;
1713     Desc.Size = &Size;
1714     Desc.MultiSampleType = &MultiSampleType;
1715     Desc.MultiSampleQuality = &MultiSampleQuality;
1716     Desc.Width = &Width;
1717     Desc.Height = &Height;
1718
1719     hr = IWineD3DSurface_GetDesc(wineD3DSurface, &Desc);
1720     if(hr != D3D_OK) return hr;
1721
1722     if(swapchain) {
1723         /* If there's a swapchain, it owns the IParent interface. Create a new one for the
1724          * new surface
1725          */
1726         parImpl = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*parImpl));
1727         ICOM_INIT_INTERFACE(parImpl, IParent, IParent_Vtbl);
1728         parImpl->ref = 1;
1729
1730         Parent = (IUnknown *) parImpl;
1731     }
1732
1733     /* Create the new surface */
1734     hr = IWineD3DDevice_CreateSurface(This->wineD3DDevice,
1735                                       Width, Height, Format,
1736                                       TRUE /* Lockable */,
1737                                       FALSE /* Discard */,
1738                                       surfImpl->mipmap_level,
1739                                       &surfImpl->WineD3DSurface,
1740                                       Type,
1741                                       Usage,
1742                                       Pool,
1743                                       MultiSampleType,
1744                                       MultiSampleQuality,
1745                                       0 /* SharedHandle */,
1746                                       This->ImplType,
1747                                       Parent);
1748
1749     if(hr != D3D_OK)
1750         return hr;
1751
1752     IWineD3DSurface_SetClipper(surfImpl->WineD3DSurface, clipper);
1753
1754     /* Update the IParent if it exists */
1755     if(parImpl)
1756     {
1757         parImpl->child = (IUnknown *) surfImpl->WineD3DSurface;
1758         /* Add a reference for the IParent */
1759         IWineD3DSurface_AddRef(surfImpl->WineD3DSurface);
1760     }
1761     /* TODO: Copy the surface content, except for render targets */
1762
1763     /* If there's a swapchain, it owns the wined3d surfaces. So Destroy
1764      * the swapchain
1765      */
1766     if(swapchain) {
1767         /* The backbuffers have the swapchain set as well, but the primary
1768          * owns it and destroys it
1769          */
1770         if(surfImpl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) {
1771             IWineD3DDevice_UninitGDI(This->wineD3DDevice, D3D7CB_DestroySwapChain);
1772         }
1773         surfImpl->isRenderTarget = FALSE;
1774     } else {
1775         if(IWineD3DSurface_Release(wineD3DSurface) == 0)
1776             TRACE("Surface released successful, next surface\n");
1777         else
1778             ERR("Something's still holding the old WineD3DSurface\n");
1779     }
1780
1781     surfImpl->ImplType = This->ImplType;
1782
1783     if(clipper)
1784     {
1785         IWineD3DClipper_Release(clipper);
1786     }
1787     return DDENUMRET_OK;
1788 }
1789
1790 /*****************************************************************************
1791  * IDirectDrawImpl_RecreateAllSurfaces
1792  *
1793  * A function, that converts all wineD3DSurfaces to the new implementation type
1794  * It enumerates all surfaces with IWineD3DDevice::EnumSurfaces, creates a
1795  * new WineD3DSurface, copies the content and releases the old surface
1796  *
1797  *****************************************************************************/
1798 static HRESULT
1799 IDirectDrawImpl_RecreateAllSurfaces(IDirectDrawImpl *This)
1800 {
1801     DDSURFACEDESC2 desc;
1802     TRACE("(%p): Switch to implementation %d\n", This, This->ImplType);
1803
1804     if(This->ImplType != SURFACE_OPENGL && This->d3d_initialized)
1805     {
1806         /* Should happen almost never */
1807         FIXME("(%p) Switching to non-opengl surfaces with d3d started. Is this a bug?\n", This);
1808         /* Shutdown d3d */
1809         IWineD3DDevice_Uninit3D(This->wineD3DDevice, D3D7CB_DestroyDepthStencilSurface, D3D7CB_DestroySwapChain);
1810     }
1811     /* Contrary: D3D starting is handled by the caller, because it knows the render target */
1812
1813     memset(&desc, 0, sizeof(desc));
1814     desc.dwSize = sizeof(desc);
1815
1816     return IDirectDraw7_EnumSurfaces(ICOM_INTERFACE(This, IDirectDraw7),
1817                                      0,
1818                                      &desc,
1819                                      This,
1820                                      IDirectDrawImpl_RecreateSurfacesCallback);
1821 }
1822
1823 /*****************************************************************************
1824  * D3D7CB_CreateSurface
1825  *
1826  * Callback function for IDirect3DDevice_CreateTexture. It searches for the
1827  * correct mipmap sublevel, and returns it to WineD3D.
1828  * The surfaces are created already by IDirectDraw7::CreateSurface
1829  *
1830  * Params:
1831  *  With, Height: With and height of the surface
1832  *  Format: The requested format
1833  *  Usage, Pool: D3DUSAGE and D3DPOOL of the surface
1834  *  level: The mipmap level
1835  *  Face: The cube map face type
1836  *  Surface: Pointer to pass the created surface back at
1837  *  SharedHandle: NULL
1838  *
1839  * Returns:
1840  *  D3D_OK
1841  *
1842  *****************************************************************************/
1843 static HRESULT WINAPI
1844 D3D7CB_CreateSurface(IUnknown *device,
1845                      IUnknown *pSuperior,
1846                      UINT Width, UINT Height,
1847                      WINED3DFORMAT Format,
1848                      DWORD Usage, WINED3DPOOL Pool, UINT level,
1849                      WINED3DCUBEMAP_FACES Face,
1850                      IWineD3DSurface **Surface,
1851                      HANDLE *SharedHandle)
1852 {
1853     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
1854     IDirectDrawSurfaceImpl *surf = NULL;
1855     UINT i = 0;
1856     DDSCAPS2 searchcaps = This->tex_root->surface_desc.ddsCaps;
1857     TRACE("(%p) call back. surf=%p. Face %d level %d\n", device, This->tex_root, Face, level);
1858
1859     searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
1860     switch(Face)
1861     {
1862         case WINED3DCUBEMAP_FACE_POSITIVE_X:
1863             TRACE("Asked for positive x\n");
1864             if(searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP) {
1865                 searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
1866             }
1867             surf = This->tex_root; break;
1868         case WINED3DCUBEMAP_FACE_NEGATIVE_X:
1869             TRACE("Asked for negative x\n");
1870             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
1871         case WINED3DCUBEMAP_FACE_POSITIVE_Y:
1872             TRACE("Asked for positive y\n");
1873             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
1874         case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
1875             TRACE("Asked for negative y\n");
1876             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
1877         case WINED3DCUBEMAP_FACE_POSITIVE_Z:
1878             TRACE("Asked for positive z\n");
1879             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
1880         case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
1881             TRACE("Asked for negative z\n");
1882             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
1883         default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
1884     }
1885
1886     if(!surf)
1887     {
1888         IDirectDrawSurface7 *attached;
1889         IDirectDrawSurface7_GetAttachedSurface(ICOM_INTERFACE(This->tex_root, IDirectDrawSurface7),
1890                                                &searchcaps,
1891                                                &attached);
1892         surf = ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, attached);
1893         IDirectDrawSurface7_Release(attached);
1894     }
1895     if(!surf) ERR("root search surface not found\n");
1896
1897     /* Find the wanted mipmap. There are enough mipmaps in the chain */
1898     while(i < level)
1899     {
1900         IDirectDrawSurface7 *attached;
1901         IDirectDrawSurface7_GetAttachedSurface(ICOM_INTERFACE(surf, IDirectDrawSurface7),
1902                                                &searchcaps,
1903                                                &attached);
1904         if(!attached) ERR("Surface not found\n");
1905         surf = ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, attached);
1906         IDirectDrawSurface7_Release(attached);
1907         i++;
1908     }
1909
1910     /* Return the surface */
1911     *Surface = surf->WineD3DSurface;
1912
1913     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *Surface, surf);
1914     return D3D_OK;
1915 }
1916
1917 ULONG WINAPI D3D7CB_DestroySwapChain(IWineD3DSwapChain *pSwapChain) {
1918     IUnknown* swapChainParent;
1919     TRACE("(%p) call back\n", pSwapChain);
1920
1921     IWineD3DSwapChain_GetParent(pSwapChain, &swapChainParent);
1922     IUnknown_Release(swapChainParent);
1923     return IUnknown_Release(swapChainParent);
1924 }
1925
1926 ULONG WINAPI D3D7CB_DestroyDepthStencilSurface(IWineD3DSurface *pSurface) {
1927     IUnknown* surfaceParent;
1928     TRACE("(%p) call back\n", pSurface);
1929
1930     IWineD3DSurface_GetParent(pSurface, &surfaceParent);
1931     IUnknown_Release(surfaceParent);
1932     return IUnknown_Release(surfaceParent);
1933 }
1934
1935 /*****************************************************************************
1936  * IDirectDrawImpl_CreateNewSurface
1937  *
1938  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
1939  * with the passed parameters.
1940  *
1941  * Params:
1942  *  DDSD: Description of the surface to create
1943  *  Surf: Address to store the interface pointer at
1944  *
1945  * Returns:
1946  *  DD_OK on success
1947  *
1948  *****************************************************************************/
1949 static HRESULT
1950 IDirectDrawImpl_CreateNewSurface(IDirectDrawImpl *This,
1951                                  DDSURFACEDESC2 *pDDSD,
1952                                  IDirectDrawSurfaceImpl **ppSurf,
1953                                  UINT level)
1954 {
1955     HRESULT hr;
1956     UINT Width = 0, Height = 0;
1957     WINED3DFORMAT Format = WINED3DFMT_UNKNOWN;
1958     WINED3DRESOURCETYPE ResType = WINED3DRTYPE_SURFACE;
1959     DWORD Usage = 0;
1960     WINED3DSURFTYPE ImplType = This->ImplType;
1961     WINED3DSURFACE_DESC Desc;
1962     IUnknown *Parent;
1963     IParentImpl *parImpl = NULL;
1964     WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
1965
1966     /* Dummies for GetDesc */
1967     WINED3DPOOL dummy_d3dpool;
1968     WINED3DMULTISAMPLE_TYPE dummy_mst;
1969     UINT dummy_uint;
1970     DWORD dummy_dword;
1971
1972     if (TRACE_ON(ddraw))
1973     {
1974         TRACE(" (%p) Requesting surface desc :\n", This);
1975         DDRAW_dump_surface_desc(pDDSD);
1976     }
1977
1978     /* Select the surface type, if it wasn't choosen yet */
1979     if(ImplType == SURFACE_UNKNOWN)
1980     {
1981         /* Use GL Surfaces if a D3DDEVICE Surface is requested */
1982         if(pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
1983         {
1984             TRACE("(%p) Choosing GL surfaces because a 3DDEVICE Surface was requested\n", This);
1985             ImplType = SURFACE_OPENGL;
1986         }
1987
1988         /* Otherwise use GDI surfaces for now */
1989         else
1990         {
1991             TRACE("(%p) Choosing GDI surfaces for 2D rendering\n", This);
1992             ImplType = SURFACE_GDI;
1993         }
1994
1995         /* Policy if all surface implementations are available:
1996          * First, check if a default type was set with winecfg. If not,
1997          * try Xrender surfaces, and use them if they work. Next, check if
1998          * accelerated OpenGL is available, and use GL surfaces in this
1999          * case. If all else fails, use GDI surfaces. If a 3DDEVICE surface
2000          * was created, always use OpenGL surfaces.
2001          *
2002          * (Note: Xrender surfaces are not implemented for now, the
2003          * unaccelerated implementation uses GDI to render in Software)
2004          */
2005
2006         /* Store the type. If it needs to be changed, all WineD3DSurfaces have to
2007          * be re-created. This could be done with IDirectDrawSurface7::Restore
2008          */
2009         This->ImplType = ImplType;
2010     }
2011     else
2012     {
2013          if((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE ) && 
2014             (This->ImplType != SURFACE_OPENGL ) && DefaultSurfaceType == SURFACE_UNKNOWN)
2015         {
2016             /* We have to change to OpenGL,
2017              * and re-create all WineD3DSurfaces
2018              */
2019             ImplType = SURFACE_OPENGL;
2020             This->ImplType = ImplType;
2021             TRACE("(%p) Re-creating all surfaces\n", This);
2022             IDirectDrawImpl_RecreateAllSurfaces(This);
2023             TRACE("(%p) Done recreating all surfaces\n", This);
2024         }
2025         else if(This->ImplType != SURFACE_OPENGL && pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2026         {
2027             WARN("The application requests a 3D capable surface, but a non-opengl surface was set in the registry\n");
2028             /* Do not fail surface creation, only fail 3D device creation */
2029         }
2030     }
2031
2032     if (!(pDDSD->ddsCaps.dwCaps & (DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY)) &&
2033         !((pDDSD->ddsCaps.dwCaps & DDSCAPS_TEXTURE) && (pDDSD->ddsCaps.dwCaps2 & DDSCAPS2_TEXTUREMANAGE)) )
2034     {
2035         /* Tests show surfaces without memory flags get these flags added right after creation. */
2036         pDDSD->ddsCaps.dwCaps |= DDSCAPS_LOCALVIDMEM | DDSCAPS_VIDEOMEMORY;
2037     }
2038     /* Get the correct wined3d usage */
2039     if (pDDSD->ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE |
2040                                  DDSCAPS_3DDEVICE       ) )
2041     {
2042         Usage |= WINED3DUSAGE_RENDERTARGET;
2043
2044         pDDSD->ddsCaps.dwCaps |= DDSCAPS_VISIBLE;
2045     }
2046     if (pDDSD->ddsCaps.dwCaps & (DDSCAPS_OVERLAY))
2047     {
2048         Usage |= WINED3DUSAGE_OVERLAY;
2049     }
2050     if(This->depthstencil || (pDDSD->ddsCaps.dwCaps & DDSCAPS_ZBUFFER) )
2051     {
2052         /* The depth stencil creation callback sets this flag.
2053          * Set the WineD3D usage to let it know that it's a depth
2054          * Stencil surface.
2055          */
2056         Usage |= WINED3DUSAGE_DEPTHSTENCIL;
2057     }
2058     if(pDDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
2059     {
2060         Pool = WINED3DPOOL_SYSTEMMEM;
2061     }
2062     else if(pDDSD->ddsCaps.dwCaps2 & DDSCAPS2_TEXTUREMANAGE)
2063     {
2064         Pool = WINED3DPOOL_MANAGED;
2065         /* Managed textures have the system memory flag set */
2066         pDDSD->ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
2067     }
2068     else if(pDDSD->ddsCaps.dwCaps & DDSCAPS_VIDEOMEMORY)
2069     {
2070         /* Videomemory adds localvidmem, this is mutually exclusive with systemmemory
2071          * and texturemanage
2072          */
2073         pDDSD->ddsCaps.dwCaps |= DDSCAPS_LOCALVIDMEM;
2074     }
2075
2076     Format = PixelFormat_DD2WineD3D(&pDDSD->u4.ddpfPixelFormat);
2077     if(Format == WINED3DFMT_UNKNOWN)
2078     {
2079         ERR("Unsupported / Unknown pixelformat\n");
2080         return DDERR_INVALIDPIXELFORMAT;
2081     }
2082
2083     /* Create the Surface object */
2084     *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
2085     if(!*ppSurf)
2086     {
2087         ERR("(%p) Error allocating memory for a surface\n", This);
2088         return DDERR_OUTOFVIDEOMEMORY;
2089     }
2090     ICOM_INIT_INTERFACE(*ppSurf, IDirectDrawSurface7, IDirectDrawSurface7_Vtbl);
2091     ICOM_INIT_INTERFACE(*ppSurf, IDirectDrawSurface3, IDirectDrawSurface3_Vtbl);
2092     ICOM_INIT_INTERFACE(*ppSurf, IDirectDrawGammaControl, IDirectDrawGammaControl_Vtbl);
2093     ICOM_INIT_INTERFACE(*ppSurf, IDirect3DTexture2, IDirect3DTexture2_Vtbl);
2094     ICOM_INIT_INTERFACE(*ppSurf, IDirect3DTexture, IDirect3DTexture1_Vtbl);
2095     (*ppSurf)->ref = 1;
2096     (*ppSurf)->version = 7;
2097     TRACE("%p->version = %d\n", (*ppSurf), (*ppSurf)->version);
2098     (*ppSurf)->ddraw = This;
2099     (*ppSurf)->surface_desc.dwSize = sizeof(DDSURFACEDESC2);
2100     (*ppSurf)->surface_desc.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2101     DD_STRUCT_COPY_BYSIZE(&(*ppSurf)->surface_desc, pDDSD);
2102
2103     /* Surface attachments */
2104     (*ppSurf)->next_attached = NULL;
2105     (*ppSurf)->first_attached = *ppSurf;
2106
2107     /* Needed to re-create the surface on an implementation change */
2108     (*ppSurf)->ImplType = ImplType;
2109
2110     /* For D3DDevice creation */
2111     (*ppSurf)->isRenderTarget = FALSE;
2112
2113     /* A trace message for debugging */
2114     TRACE("(%p) Created IDirectDrawSurface implementation structure at %p\n", This, *ppSurf);
2115
2116     if(pDDSD->ddsCaps.dwCaps & ( DDSCAPS_PRIMARYSURFACE | DDSCAPS_TEXTURE | DDSCAPS_3DDEVICE) )
2117     {
2118         /* Render targets and textures need a IParent interface,
2119          * because WineD3D will destroy them when the swapchain
2120          * is released
2121          */
2122         parImpl = HeapAlloc(GetProcessHeap(), 0, sizeof(IParentImpl));
2123         if(!parImpl)
2124         {
2125             ERR("Out of memory when allocating memory for a IParent implementation\n");
2126             return DDERR_OUTOFMEMORY;
2127         }
2128         parImpl->ref = 1;
2129         ICOM_INIT_INTERFACE(parImpl, IParent, IParent_Vtbl);
2130         Parent = (IUnknown *) ICOM_INTERFACE(parImpl, IParent);
2131         TRACE("Using IParent interface %p as parent\n", parImpl);
2132     }
2133     else
2134     {
2135         /* Use the surface as parent */
2136         Parent = (IUnknown *) ICOM_INTERFACE(*ppSurf, IDirectDrawSurface7);
2137         TRACE("Using Surface interface %p as parent\n", *ppSurf);
2138     }
2139
2140     /* Now create the WineD3D Surface */
2141     hr = IWineD3DDevice_CreateSurface(This->wineD3DDevice,
2142                                       pDDSD->dwWidth,
2143                                       pDDSD->dwHeight,
2144                                       Format,
2145                                       TRUE /* Lockable */,
2146                                       FALSE /* Discard */,
2147                                       level,
2148                                       &(*ppSurf)->WineD3DSurface,
2149                                       ResType, Usage,
2150                                       Pool,
2151                                       WINED3DMULTISAMPLE_NONE,
2152                                       0 /* MultiSampleQuality */,
2153                                       0 /* SharedHandle */,
2154                                       ImplType,
2155                                       Parent);
2156
2157     if(hr != D3D_OK)
2158     {
2159         ERR("IWineD3DDevice::CreateSurface failed. hr = %08x\n", hr);
2160         return hr;
2161     }
2162
2163     /* Set the child of the parent implementation if it exists */
2164     if(parImpl)
2165     {
2166         parImpl->child = (IUnknown *) (*ppSurf)->WineD3DSurface;
2167         /* The IParent releases the WineD3DSurface, and
2168          * the ddraw surface does that too. Hold a reference
2169          */
2170         IWineD3DSurface_AddRef((*ppSurf)->WineD3DSurface);
2171     }
2172
2173     /* Increase the surface counter, and attach the surface */
2174     InterlockedIncrement(&This->surfaces);
2175     list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
2176
2177     /* Here we could store all created surfaces in the DirectDrawImpl structure,
2178      * But this could also be delegated to WineDDraw, as it keeps track of all its
2179      * resources. Not implemented for now, as there are more important things ;)
2180      */
2181
2182     /* Get the pixel format of the WineD3DSurface and store it.
2183      * Don't use the Format choosen above, WineD3D might have
2184      * changed it
2185      */
2186     Desc.Format = &Format;
2187     Desc.Type = &ResType;
2188     Desc.Usage = &Usage;
2189     Desc.Pool = &dummy_d3dpool;
2190     Desc.Size = &dummy_uint;
2191     Desc.MultiSampleType = &dummy_mst;
2192     Desc.MultiSampleQuality = &dummy_dword;
2193     Desc.Width = &Width;
2194     Desc.Height = &Height;
2195
2196     (*ppSurf)->surface_desc.dwFlags |= DDSD_PIXELFORMAT;
2197     hr = IWineD3DSurface_GetDesc((*ppSurf)->WineD3DSurface, &Desc);
2198     if(hr != D3D_OK)
2199     {
2200         ERR("IWineD3DSurface::GetDesc failed\n");
2201         IDirectDrawSurface7_Release( (IDirectDrawSurface7 *) *ppSurf);
2202         return hr;
2203     }
2204
2205     if(Format == WINED3DFMT_UNKNOWN)
2206     {
2207         FIXME("IWineD3DSurface::GetDesc returned WINED3DFMT_UNKNOWN\n");
2208     }
2209     PixelFormat_WineD3DtoDD( &(*ppSurf)->surface_desc.u4.ddpfPixelFormat, Format);
2210
2211     /* Anno 1602 stores the pitch right after surface creation, so make sure it's there.
2212      * I can't LockRect() the surface here because if OpenGL surfaces are in use, the
2213      * WineD3DDevice might not be usable for 3D yet, so an extra method was created.
2214      * TODO: Test other fourcc formats
2215      */
2216     if(Format == WINED3DFMT_DXT1 || Format == WINED3DFMT_DXT2 || Format == WINED3DFMT_DXT3 ||
2217        Format == WINED3DFMT_DXT4 || Format == WINED3DFMT_DXT5)
2218     {
2219         (*ppSurf)->surface_desc.dwFlags |= DDSD_LINEARSIZE;
2220         if(Format == WINED3DFMT_DXT1)
2221         {
2222             (*ppSurf)->surface_desc.u1.dwLinearSize = max(4, Width) * max(4, Height) / 2;
2223         }
2224         else
2225         {
2226             (*ppSurf)->surface_desc.u1.dwLinearSize = max(4, Width) * max(4, Height);
2227         }
2228     }
2229     else
2230     {
2231         (*ppSurf)->surface_desc.dwFlags |= DDSD_PITCH;
2232         (*ppSurf)->surface_desc.u1.lPitch = IWineD3DSurface_GetPitch((*ppSurf)->WineD3DSurface);
2233     }
2234
2235     /* Application passed a color key? Set it! */
2236     if(pDDSD->dwFlags & DDSD_CKDESTOVERLAY)
2237     {
2238         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2239                                     DDCKEY_DESTOVERLAY,
2240                                     (WINEDDCOLORKEY *) &pDDSD->u3.ddckCKDestOverlay);
2241     }
2242     if(pDDSD->dwFlags & DDSD_CKDESTBLT)
2243     {
2244         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2245                                     DDCKEY_DESTBLT,
2246                                     (WINEDDCOLORKEY *) &pDDSD->ddckCKDestBlt);
2247     }
2248     if(pDDSD->dwFlags & DDSD_CKSRCOVERLAY)
2249     {
2250         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2251                                     DDCKEY_SRCOVERLAY,
2252                                     (WINEDDCOLORKEY *) &pDDSD->ddckCKSrcOverlay);
2253     }
2254     if(pDDSD->dwFlags & DDSD_CKSRCBLT)
2255     {
2256         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2257                                     DDCKEY_SRCBLT,
2258                                     (WINEDDCOLORKEY *) &pDDSD->ddckCKSrcBlt);
2259     }
2260     if ( pDDSD->dwFlags & DDSD_LPSURFACE)
2261     {
2262         hr = IWineD3DSurface_SetMem((*ppSurf)->WineD3DSurface, pDDSD->lpSurface);
2263         if(hr != WINED3D_OK)
2264         {
2265             /* No need for a trace here, wined3d does that for us */
2266             IDirectDrawSurface7_Release(ICOM_INTERFACE((*ppSurf), IDirectDrawSurface7));
2267             return hr;
2268         }
2269     }
2270
2271     return DD_OK;
2272 }
2273 /*****************************************************************************
2274  * CreateAdditionalSurfaces
2275  *
2276  * Creates a new mipmap chain.
2277  *
2278  * Params:
2279  *  root: Root surface to attach the newly created chain to
2280  *  count: number of surfaces to create
2281  *  DDSD: Description of the surface. Intentionally not a pointer to avoid side
2282  *        effects on the caller
2283  *  CubeFaceRoot: Whether the new surface is a root of a cube map face. This
2284  *                creates an additional surface without the mipmapping flags
2285  *
2286  *****************************************************************************/
2287 static HRESULT
2288 CreateAdditionalSurfaces(IDirectDrawImpl *This,
2289                          IDirectDrawSurfaceImpl *root,
2290                          UINT count,
2291                          DDSURFACEDESC2 DDSD,
2292                          BOOL CubeFaceRoot)
2293 {
2294     UINT i, j, level = 0;
2295     HRESULT hr;
2296     IDirectDrawSurfaceImpl *last = root;
2297
2298     for(i = 0; i < count; i++)
2299     {
2300         IDirectDrawSurfaceImpl *object2 = NULL;
2301
2302         /* increase the mipmap level, but only if a mipmap is created
2303          * In this case, also halve the size
2304          */
2305         if(DDSD.ddsCaps.dwCaps & DDSCAPS_MIPMAP && !CubeFaceRoot)
2306         {
2307             level++;
2308             if(DDSD.dwWidth > 1) DDSD.dwWidth /= 2;
2309             if(DDSD.dwHeight > 1) DDSD.dwHeight /= 2;
2310             /* Set the mipmap sublevel flag according to msdn */
2311             DDSD.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2312         }
2313         else
2314         {
2315             DDSD.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2316         }
2317         CubeFaceRoot = FALSE;
2318
2319         hr = IDirectDrawImpl_CreateNewSurface(This,
2320                                               &DDSD,
2321                                               &object2,
2322                                               level);
2323         if(hr != DD_OK)
2324         {
2325             return hr;
2326         }
2327
2328         /* Add the new surface to the complex attachment array */
2329         for(j = 0; j < MAX_COMPLEX_ATTACHED; j++)
2330         {
2331             if(last->complex_array[j]) continue;
2332             last->complex_array[j] = object2;
2333             break;
2334         }
2335         last = object2;
2336
2337         /* Remove the (possible) back buffer cap from the new surface description,
2338          * because only one surface in the flipping chain is a back buffer, one
2339          * is a front buffer, the others are just primary surfaces.
2340          */
2341         DDSD.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2342     }
2343     return DD_OK;
2344 }
2345
2346 /*****************************************************************************
2347  * IDirectDraw7::CreateSurface
2348  *
2349  * Creates a new IDirectDrawSurface object and returns its interface.
2350  *
2351  * The surface connections with wined3d are a bit tricky. Basically it works
2352  * like this:
2353  *
2354  * |------------------------|               |-----------------|
2355  * | DDraw surface          |               | WineD3DSurface  |
2356  * |                        |               |                 |
2357  * |        WineD3DSurface  |-------------->|                 |
2358  * |        Child           |<------------->| Parent          |
2359  * |------------------------|               |-----------------|
2360  *
2361  * The DDraw surface is the parent of the wined3d surface, and it releases
2362  * the WineD3DSurface when the ddraw surface is destroyed.
2363  *
2364  * However, for all surfaces which can be in a container in WineD3D,
2365  * we have to do this. These surfaces are usually complex surfaces,
2366  * so this concerns primary surfaces with a front and a back buffer,
2367  * and textures.
2368  *
2369  * |------------------------|               |-----------------|
2370  * | DDraw surface          |               | Container       |
2371  * |                        |               |                 |
2372  * |                  Child |<------------->| Parent          |
2373  * |                Texture |<------------->|                 |
2374  * |         WineD3DSurface |<----|         |          Levels |<--|
2375  * | Complex connection     |     |         |                 |   |
2376  * |------------------------|     |         |-----------------|   |
2377  *  ^                             |                               |
2378  *  |                             |                               |
2379  *  |                             |                               |
2380  *  |    |------------------|     |         |-----------------|   |
2381  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2382  *  |    |                  |               |                 |   |
2383  *  |    |            Child |<------------->| Parent          |   |
2384  *  |    |                  |               |       Container |<--|
2385  *  |    |------------------|               |-----------------|   |
2386  *  |                                                             |
2387  *  |   |----------------------|                                  |
2388  *  |   | DDraw surface 2      |                                  |
2389  *  |   |                      |                                  |
2390  *  |<->| Complex root   Child |                                  |
2391  *  |   |              Texture |                                  |
2392  *  |   |       WineD3DSurface |<----|                            |
2393  *  |   |----------------------|     |                            |
2394  *  |                                |                            |
2395  *  |    |---------------------|     |      |-----------------|   |
2396  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2397  *  |    |                     |            |                 |   |
2398  *  |    |               Child |<---------->| Parent          |   |
2399  *  |    |---------------------|            |       Container |<--|
2400  *  |                                       |-----------------|   |
2401  *  |                                                             |
2402  *  |             ---More surfaces can follow---                  |
2403  *
2404  * The reason is that the IWineD3DSwapchain(render target container)
2405  * and the IWineD3DTexure(Texture container) release the parents
2406  * of their surface's children, but by releasing the complex root
2407  * the surfaces which are complexly attached to it are destroyed
2408  * too. See IDirectDrawSurface::Release for a more detailed
2409  * explanation.
2410  *
2411  * Params:
2412  *  DDSD: Description of the surface to create
2413  *  Surf: Address to store the interface pointer at
2414  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2415  *            aggregation, so it has to be NULL
2416  *
2417  * Returns:
2418  *  DD_OK on success
2419  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2420  *  DDERR_* if an error occurs
2421  *
2422  *****************************************************************************/
2423 static HRESULT WINAPI
2424 IDirectDrawImpl_CreateSurface(IDirectDraw7 *iface,
2425                               DDSURFACEDESC2 *DDSD,
2426                               IDirectDrawSurface7 **Surf,
2427                               IUnknown *UnkOuter)
2428 {
2429     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
2430     IDirectDrawSurfaceImpl *object = NULL;
2431     HRESULT hr;
2432     LONG extra_surfaces = 0;
2433     DDSURFACEDESC2 desc2;
2434     WINED3DDISPLAYMODE Mode;
2435
2436     TRACE("(%p)->(%p,%p,%p)\n", This, DDSD, Surf, UnkOuter);
2437
2438     /* Some checks before we start */
2439     if (TRACE_ON(ddraw))
2440     {
2441         TRACE(" (%p) Requesting surface desc :\n", This);
2442         DDRAW_dump_surface_desc(DDSD);
2443     }
2444     EnterCriticalSection(&ddraw_cs);
2445
2446     if (UnkOuter != NULL)
2447     {
2448         FIXME("(%p) : outer != NULL?\n", This);
2449         LeaveCriticalSection(&ddraw_cs);
2450         return CLASS_E_NOAGGREGATION; /* unchecked */
2451     }
2452
2453     if (Surf == NULL)
2454     {
2455         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", This);
2456         LeaveCriticalSection(&ddraw_cs);
2457         return E_POINTER; /* unchecked */
2458     }
2459
2460     if (!(DDSD->dwFlags & DDSD_CAPS))
2461     {
2462         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2463         DDSD->dwFlags |= DDSD_CAPS;
2464     }
2465
2466     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2467     {
2468         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2469         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2470     }
2471
2472     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2473     {
2474         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2475         WARN("(%p) Null surface pointer specified, ignore it!\n", This);
2476         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2477     }
2478
2479     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2480        !(This->cooperative_level & DDSCL_EXCLUSIVE))
2481     {
2482         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n", This);
2483         *Surf = NULL;
2484         LeaveCriticalSection(&ddraw_cs);
2485         return DDERR_NOEXCLUSIVEMODE;
2486     }
2487
2488     if(DDSD->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER)) {
2489         WARN("Application tried to create an explicit front or back buffer\n");
2490         LeaveCriticalSection(&ddraw_cs);
2491         return DDERR_INVALIDCAPS;
2492     }
2493     /* Check cube maps but only if the size includes them */
2494     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2495     {
2496         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
2497            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
2498         {
2499             WARN("Cube map faces requested without cube map flag\n");
2500             LeaveCriticalSection(&ddraw_cs);
2501             return DDERR_INVALIDCAPS;
2502         }
2503         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2504            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
2505         {
2506             WARN("Cube map without faces requested\n");
2507             LeaveCriticalSection(&ddraw_cs);
2508             return DDERR_INVALIDPARAMS;
2509         }
2510
2511         /* Quick tests confirm those can be created, but we don't do that yet */
2512         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2513            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
2514         {
2515             FIXME("Partial cube maps not supported yet\n");
2516         }
2517     }
2518
2519     /* According to the msdn this flag is ignored by CreateSurface */
2520     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2521         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2522
2523     /* Modify some flags */
2524     memset(&desc2, 0, sizeof(desc2));
2525     desc2.dwSize = sizeof(desc2);   /* For the struct copy */
2526     DD_STRUCT_COPY_BYSIZE(&desc2, DDSD);
2527     desc2.dwSize = sizeof(desc2);   /* To override a possibly smaller size */
2528     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
2529
2530     /* Get the video mode from WineD3D - we will need it */
2531     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
2532                                        0, /* Swapchain 0 */
2533                                        &Mode);
2534     if(FAILED(hr))
2535     {
2536         ERR("Failed to read display mode from wined3d\n");
2537         switch(This->orig_bpp)
2538         {
2539             case 8:
2540                 Mode.Format = WINED3DFMT_P8;
2541                 break;
2542
2543             case 15:
2544                 Mode.Format = WINED3DFMT_X1R5G5B5;
2545                 break;
2546
2547             case 16:
2548                 Mode.Format = WINED3DFMT_R5G6B5;
2549                 break;
2550
2551             case 24:
2552                 Mode.Format = WINED3DFMT_R8G8B8;
2553                 break;
2554
2555             case 32:
2556                 Mode.Format = WINED3DFMT_X8R8G8B8;
2557                 break;
2558         }
2559         Mode.Width = This->orig_width;
2560         Mode.Height = This->orig_height;
2561     }
2562
2563     /* No pixelformat given? Use the current screen format */
2564     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
2565     {
2566         desc2.dwFlags |= DDSD_PIXELFORMAT;
2567         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
2568
2569         /* Wait: It could be a Z buffer */
2570         if(desc2.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
2571         {
2572             switch(desc2.u2.dwMipMapCount) /* Who had this glorious idea? */
2573             {
2574                 case 15:
2575                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D15S1);
2576                     break;
2577                 case 16:
2578                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D16);
2579                     break;
2580                 case 24:
2581                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D24X8);
2582                     break;
2583                 case 32:
2584                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D32);
2585                     break;
2586                 default:
2587                     ERR("Unknown Z buffer bit depth\n");
2588             }
2589         }
2590         else
2591         {
2592             PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
2593         }
2594     }
2595
2596     /* No Width or no Height? Use the original screen size
2597      */
2598     if(!(desc2.dwFlags & DDSD_WIDTH) ||
2599        !(desc2.dwFlags & DDSD_HEIGHT) )
2600     {
2601         /* Invalid for non-render targets */
2602         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
2603         {
2604             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
2605             *Surf = NULL;
2606             LeaveCriticalSection(&ddraw_cs);
2607             return DDERR_INVALIDPARAMS;
2608         }
2609
2610         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
2611         desc2.dwWidth = Mode.Width;
2612         desc2.dwHeight = Mode.Height;
2613     }
2614
2615     /* Mipmap count fixes */
2616     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2617     {
2618         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
2619         {
2620             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
2621             {
2622                 /* Mipmap count is given, should not be 0 */
2623                 if( desc2.u2.dwMipMapCount == 0 )
2624                 {
2625                     LeaveCriticalSection(&ddraw_cs);
2626                     return DDERR_INVALIDPARAMS;
2627                 }
2628             }
2629             else
2630             {
2631                 /* Undocumented feature: Create sublevels until
2632                  * either the width or the height is 1
2633                  */
2634                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
2635                             desc2.dwWidth : desc2.dwHeight;
2636                 desc2.u2.dwMipMapCount = 0;
2637                 while( min )
2638                 {
2639                     desc2.u2.dwMipMapCount += 1;
2640                     min >>= 1;
2641                 }
2642             }
2643         }
2644         else
2645         {
2646             /* Not-complex mipmap -> Mipmapcount = 1 */
2647             desc2.u2.dwMipMapCount = 1;
2648         }
2649         extra_surfaces = desc2.u2.dwMipMapCount - 1;
2650
2651         /* There's a mipmap count in the created surface in any case */
2652         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
2653     }
2654     /* If no mipmap is given, the texture has only one level */
2655
2656     /* The first surface is a front buffer, the back buffer is created afterwards */
2657     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
2658     {
2659         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
2660     }
2661
2662     /* The root surface in a cube map is positive x */
2663     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2664     {
2665         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
2666         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
2667     }
2668
2669     /* Create the first surface */
2670     hr = IDirectDrawImpl_CreateNewSurface(This, &desc2, &object, 0);
2671     if( hr != DD_OK)
2672     {
2673         ERR("IDirectDrawImpl_CreateNewSurface failed with %08x\n", hr);
2674         LeaveCriticalSection(&ddraw_cs);
2675         return hr;
2676     }
2677     object->is_complex_root = TRUE;
2678
2679     *Surf = ICOM_INTERFACE(object, IDirectDrawSurface7);
2680
2681     /* Create Additional surfaces if necessary
2682      * This applies to Primary surfaces which have a back buffer count
2683      * set, but not to mipmap textures. In case of Mipmap textures,
2684      * wineD3D takes care of the creation of additional surfaces
2685      */
2686     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
2687     {
2688         extra_surfaces = DDSD->dwBackBufferCount;
2689         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
2690         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
2691     }
2692
2693     hr = DD_OK;
2694     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2695     {
2696         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
2697         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
2698         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2699         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
2700         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
2701         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2702         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
2703         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
2704         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2705         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
2706         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
2707         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2708         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
2709         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
2710         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2711         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
2712         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
2713     }
2714
2715     hr |= CreateAdditionalSurfaces(This, object, extra_surfaces, desc2, FALSE);
2716     if(hr != DD_OK)
2717     {
2718         /* This destroys and possibly created surfaces too */
2719         IDirectDrawSurface_Release( ICOM_INTERFACE(object, IDirectDrawSurface7) );
2720         LeaveCriticalSection(&ddraw_cs);
2721         return hr;
2722     }
2723
2724     /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
2725      * But attach the d3ddevice only if the currently created surface was
2726      * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
2727      * The only case I can think of where this doesn't apply is when a
2728      * 2D app was configured by the user to run with OpenGL and it didn't create
2729      * the render target as first surface. In this case the render target creation
2730      * will cause the 3D init.
2731      */
2732     if( (This->ImplType == SURFACE_OPENGL) && !(This->d3d_initialized) &&
2733         desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE) )
2734     {
2735         IDirectDrawSurfaceImpl *target = object, *surface;
2736         struct list *entry;
2737
2738         /* Search for the primary to use as render target */
2739         LIST_FOR_EACH(entry, &This->surface_list)
2740         {
2741             surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
2742             if((surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER)) ==
2743                (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER))
2744             {
2745                 /* found */
2746                 target = surface;
2747                 TRACE("Using primary %p as render target\n", target);
2748                 break;
2749             }
2750         }
2751
2752         TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", This, target);
2753         hr = IDirectDrawImpl_AttachD3DDevice(This, target);
2754         if(hr != D3D_OK)
2755         {
2756             IDirectDrawSurfaceImpl *release_surf;
2757             ERR("IDirectDrawImpl_AttachD3DDevice failed, hr = %x\n", hr);
2758             *Surf = NULL;
2759
2760             /* The before created surface structures are in an incomplete state here.
2761              * WineD3D holds the reference on the IParents, and it released them on the failure
2762              * already. So the regular release method implementation would fail on the attempt
2763              * to destroy either the IParents or the swapchain. So free the surface here.
2764              * The surface structure here is a list, not a tree, because onscreen targets
2765              * cannot be cube textures
2766              */
2767             while(object)
2768             {
2769                 release_surf = object;
2770                 object = object->complex_array[0];
2771                 IDirectDrawSurfaceImpl_Destroy(release_surf);
2772             }
2773             LeaveCriticalSection(&ddraw_cs);
2774             return hr;
2775         }
2776     } else if(!(This->d3d_initialized) && desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) {
2777         IDirectDrawImpl_CreateGDISwapChain(This, object);
2778     }
2779
2780     /* Addref the ddraw interface to keep an reference for each surface */
2781     IDirectDraw7_AddRef(iface);
2782     object->ifaceToRelease = (IUnknown *) iface;
2783
2784     /* Create a WineD3DTexture if a texture was requested */
2785     if(desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
2786     {
2787         UINT levels;
2788         WINED3DFORMAT Format;
2789         WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
2790
2791         This->tex_root = object;
2792
2793         if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2794         {
2795             /* a mipmap is created, create enough levels */
2796             levels = desc2.u2.dwMipMapCount;
2797         }
2798         else
2799         {
2800             /* No mipmap is created, create one level */
2801             levels = 1;
2802         }
2803
2804         /* DDSCAPS_SYSTEMMEMORY textures are in WINED3DPOOL_SYSTEMMEM */
2805         if(DDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
2806         {
2807             Pool = WINED3DPOOL_SYSTEMMEM;
2808         }
2809         /* Should I forward the MANAGED cap to the managed pool ? */
2810
2811         /* Get the format. It's set already by CreateNewSurface */
2812         Format = PixelFormat_DD2WineD3D(&object->surface_desc.u4.ddpfPixelFormat);
2813
2814         /* The surfaces are already created, the callback only
2815          * passes the IWineD3DSurface to WineD3D
2816          */
2817         if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2818         {
2819             hr = IWineD3DDevice_CreateCubeTexture(This->wineD3DDevice,
2820                                                   DDSD->dwWidth, /* Edgelength */
2821                                                   levels,
2822                                                   0, /* usage */
2823                                                   Format,
2824                                                   Pool,
2825                                                   (IWineD3DCubeTexture **) &object->wineD3DTexture,
2826                                                   0, /* SharedHandle */
2827                                                   (IUnknown *) ICOM_INTERFACE(object, IDirectDrawSurface7),
2828                                                   D3D7CB_CreateSurface);
2829         }
2830         else
2831         {
2832             hr = IWineD3DDevice_CreateTexture(This->wineD3DDevice,
2833                                               DDSD->dwWidth, DDSD->dwHeight,
2834                                               levels, /* MipMapCount = Levels */
2835                                               0, /* usage */
2836                                               Format,
2837                                               Pool,
2838                                               (IWineD3DTexture **) &object->wineD3DTexture,
2839                                               0, /* SharedHandle */
2840                                               (IUnknown *) ICOM_INTERFACE(object, IDirectDrawSurface7),
2841                                               D3D7CB_CreateSurface );
2842         }
2843         This->tex_root = NULL;
2844     }
2845
2846     LeaveCriticalSection(&ddraw_cs);
2847     return hr;
2848 }
2849
2850 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
2851 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
2852
2853 static BOOL
2854 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
2855                                     const DDPIXELFORMAT *provided)
2856 {
2857     /* Some flags must be present in both or neither for a match. */
2858     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
2859         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
2860         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
2861
2862     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
2863         return FALSE;
2864
2865     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
2866         return FALSE;
2867
2868     if (requested->dwFlags & DDPF_FOURCC)
2869         if (requested->dwFourCC != provided->dwFourCC)
2870             return FALSE;
2871
2872     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
2873                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
2874         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
2875             return FALSE;
2876
2877     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
2878                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
2879         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
2880             return FALSE;
2881
2882     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
2883         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
2884             return FALSE;
2885
2886     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
2887     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
2888                               |DDPF_BUMPDUDV))
2889         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
2890             return FALSE;
2891
2892     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
2893         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
2894             return FALSE;
2895
2896     return TRUE;
2897 }
2898
2899 static BOOL
2900 IDirectDrawImpl_DDSD_Match(const DDSURFACEDESC2* requested,
2901                            const DDSURFACEDESC2* provided)
2902 {
2903     struct compare_info
2904     {
2905         DWORD flag;
2906         ptrdiff_t offset;
2907         size_t size;
2908     };
2909
2910 #define CMP(FLAG, FIELD)                                \
2911         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
2912           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
2913
2914     static const struct compare_info compare[] =
2915     {
2916         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
2917         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
2918         CMP(CAPS, ddsCaps),
2919         CMP(CKDESTBLT, ddckCKDestBlt),
2920         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
2921         CMP(CKSRCBLT, ddckCKSrcBlt),
2922         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
2923         CMP(HEIGHT, dwHeight),
2924         CMP(LINEARSIZE, u1 /* dwLinearSize */),
2925         CMP(LPSURFACE, lpSurface),
2926         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
2927         CMP(PITCH, u1 /* lPitch */),
2928         /* PIXELFORMAT: manual */
2929         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
2930         CMP(TEXTURESTAGE, dwTextureStage),
2931         CMP(WIDTH, dwWidth),
2932         /* ZBUFFERBITDEPTH: "obsolete" */
2933     };
2934
2935 #undef CMP
2936
2937     unsigned int i;
2938
2939     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
2940         return FALSE;
2941
2942     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
2943     {
2944         if (requested->dwFlags & compare[i].flag
2945             && memcmp((const char *)provided + compare[i].offset,
2946                       (const char *)requested + compare[i].offset,
2947                       compare[i].size) != 0)
2948             return FALSE;
2949     }
2950
2951     if (requested->dwFlags & DDSD_PIXELFORMAT)
2952     {
2953         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
2954                                                 &provided->u4.ddpfPixelFormat))
2955             return FALSE;
2956     }
2957
2958     return TRUE;
2959 }
2960
2961 #undef DDENUMSURFACES_SEARCHTYPE
2962 #undef DDENUMSURFACES_MATCHTYPE
2963
2964 /*****************************************************************************
2965  * IDirectDraw7::EnumSurfaces
2966  *
2967  * Loops through all surfaces attached to this device and calls the
2968  * application callback. This can't be relayed to WineD3DDevice,
2969  * because some WineD3DSurfaces' parents are IParent objects
2970  *
2971  * Params:
2972  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
2973  *  DDSD: Description to filter for
2974  *  Context: Application-provided pointer, it's passed unmodified to the
2975  *           Callback function
2976  *  Callback: Address to call for each surface
2977  *
2978  * Returns:
2979  *  DDERR_INVALIDPARAMS if the callback is NULL
2980  *  DD_OK on success
2981  *
2982  *****************************************************************************/
2983 static HRESULT WINAPI
2984 IDirectDrawImpl_EnumSurfaces(IDirectDraw7 *iface,
2985                              DWORD Flags,
2986                              DDSURFACEDESC2 *DDSD,
2987                              void *Context,
2988                              LPDDENUMSURFACESCALLBACK7 Callback)
2989 {
2990     /* The surface enumeration is handled by WineDDraw,
2991      * because it keeps track of all surfaces attached to
2992      * it. The filtering is done by our callback function,
2993      * because WineDDraw doesn't handle ddraw-like surface
2994      * caps structures
2995      */
2996     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
2997     IDirectDrawSurfaceImpl *surf;
2998     BOOL all, nomatch;
2999     DDSURFACEDESC2 desc;
3000     struct list *entry, *entry2;
3001
3002     all = Flags & DDENUMSURFACES_ALL;
3003     nomatch = Flags & DDENUMSURFACES_NOMATCH;
3004
3005     TRACE("(%p)->(%x,%p,%p,%p)\n", This, Flags, DDSD, Context, Callback);
3006     EnterCriticalSection(&ddraw_cs);
3007
3008     if(!Callback)
3009     {
3010         LeaveCriticalSection(&ddraw_cs);
3011         return DDERR_INVALIDPARAMS;
3012     }
3013
3014     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
3015     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
3016     {
3017         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3018         if (all || (nomatch != IDirectDrawImpl_DDSD_Match(DDSD, &surf->surface_desc)))
3019         {
3020             desc = surf->surface_desc;
3021             IDirectDrawSurface7_AddRef(ICOM_INTERFACE(surf, IDirectDrawSurface7));
3022             if(Callback( ICOM_INTERFACE(surf, IDirectDrawSurface7), &desc, Context) != DDENUMRET_OK)
3023             {
3024                 LeaveCriticalSection(&ddraw_cs);
3025                 return DD_OK;
3026             }
3027         }
3028     }
3029     LeaveCriticalSection(&ddraw_cs);
3030     return DD_OK;
3031 }
3032
3033 static HRESULT WINAPI
3034 findRenderTarget(IDirectDrawSurface7 *surface,
3035                  DDSURFACEDESC2 *desc,
3036                  void *ctx)
3037 {
3038     IDirectDrawSurfaceImpl *surf = ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, surface);
3039     IDirectDrawSurfaceImpl **target = (IDirectDrawSurfaceImpl **) ctx;
3040
3041     if(!surf->isRenderTarget) {
3042         *target = surf;
3043         IDirectDrawSurface7_Release(surface);
3044         return DDENUMRET_CANCEL;
3045     }
3046
3047     /* Recurse into the surface tree */
3048     IDirectDrawSurface7_EnumAttachedSurfaces(surface, ctx, findRenderTarget);
3049
3050     IDirectDrawSurface7_Release(surface);
3051     if(*target) return DDENUMRET_CANCEL;
3052     else return DDENUMRET_OK; /* Continue with the next neighbor surface */
3053 }
3054
3055 /*****************************************************************************
3056  * D3D7CB_CreateRenderTarget
3057  *
3058  * Callback called by WineD3D to create Surfaces for render target usage
3059  * This function takes the D3D target from the IDirectDrawImpl structure,
3060  * and returns the WineD3DSurface. To avoid double usage, the surface
3061  * is marked as render target afterwards
3062  *
3063  * Params
3064  *  device: The WineD3DDevice's parent
3065  *  Width, Height, Format: Dimensions and pixelformat of the render target
3066  *                         Ignored, because the surface already exists
3067  *  MultiSample, MultisampleQuality, Lockable: Ignored for the same reason
3068  *  Lockable: ignored
3069  *  ppSurface: Address to pass the surface pointer back at
3070  *  pSharedHandle: Ignored
3071  *
3072  * Returns:
3073  *  Always returns D3D_OK
3074  *
3075  *****************************************************************************/
3076 static HRESULT WINAPI
3077 D3D7CB_CreateRenderTarget(IUnknown *device, IUnknown *pSuperior,
3078                           UINT Width, UINT Height,
3079                           WINED3DFORMAT Format,
3080                           WINED3DMULTISAMPLE_TYPE MultiSample,
3081                           DWORD MultisampleQuality,
3082                           BOOL Lockable,
3083                           IWineD3DSurface** ppSurface,
3084                           HANDLE* pSharedHandle)
3085 {
3086     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
3087     IDirectDrawSurfaceImpl *d3dSurface = This->d3d_target, *target = NULL;
3088     TRACE("(%p) call back\n", device);
3089
3090     if(d3dSurface->isRenderTarget)
3091     {
3092         IDirectDrawSurface7_EnumAttachedSurfaces(ICOM_INTERFACE(d3dSurface, IDirectDrawSurface7),
3093                                                  &target, findRenderTarget);
3094     }
3095     else
3096     {
3097         target = d3dSurface;
3098     }
3099
3100     if(!target)
3101     {
3102         target = This->d3d_target;
3103         ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", This);
3104     }
3105
3106     /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */
3107
3108     *ppSurface = target->WineD3DSurface;
3109     target->isRenderTarget = TRUE;
3110     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *ppSurface, d3dSurface);
3111     return D3D_OK;
3112 }
3113
3114 static HRESULT WINAPI
3115 D3D7CB_CreateDepthStencilSurface(IUnknown *device,
3116                                  IUnknown *pSuperior,
3117                                  UINT Width,
3118                                  UINT Height,
3119                                  WINED3DFORMAT Format,
3120                                  WINED3DMULTISAMPLE_TYPE MultiSample,
3121                                  DWORD MultisampleQuality,
3122                                  BOOL Discard,
3123                                  IWineD3DSurface** ppSurface,
3124                                  HANDLE* pSharedHandle)
3125 {
3126     /* Create a Depth Stencil surface to make WineD3D happy */
3127     HRESULT hr = D3D_OK;
3128     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
3129     DDSURFACEDESC2 ddsd;
3130
3131     TRACE("(%p) call back\n", device);
3132
3133     *ppSurface = NULL;
3134
3135     /* Create a DirectDraw surface */
3136     memset(&ddsd, 0, sizeof(ddsd));
3137     ddsd.dwSize = sizeof(ddsd);
3138     ddsd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
3139     ddsd.dwFlags = DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
3140     ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
3141     ddsd.dwHeight = Height;
3142     ddsd.dwWidth = Width;
3143     if(Format != 0)
3144     {
3145       PixelFormat_WineD3DtoDD(&ddsd.u4.ddpfPixelFormat, Format);
3146     }
3147     else
3148     {
3149       ddsd.dwFlags ^= DDSD_PIXELFORMAT;
3150     }
3151
3152     This->depthstencil = TRUE;
3153     hr = IDirectDraw7_CreateSurface((IDirectDraw7 *) This,
3154                                     &ddsd,
3155                                     (IDirectDrawSurface7 **) &This->DepthStencilBuffer,
3156                                     NULL);
3157     This->depthstencil = FALSE;
3158     if(FAILED(hr))
3159     {
3160         ERR(" (%p) Creating a DepthStencil Surface failed, result = %x\n", This, hr);
3161         return hr;
3162     }
3163     *ppSurface = This->DepthStencilBuffer->WineD3DSurface;
3164     return D3D_OK;
3165 }
3166
3167 /*****************************************************************************
3168  * D3D7CB_CreateAdditionalSwapChain
3169  *
3170  * Callback function for WineD3D which creates a new WineD3DSwapchain
3171  * interface. It also creates an IParent interface to store that pointer,
3172  * so the WineD3DSwapchain has a parent and can be released when the D3D
3173  * device is destroyed
3174  *****************************************************************************/
3175 static HRESULT WINAPI
3176 D3D7CB_CreateAdditionalSwapChain(IUnknown *device,
3177                                  WINED3DPRESENT_PARAMETERS* pPresentationParameters,
3178                                  IWineD3DSwapChain ** ppSwapChain)
3179 {
3180     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
3181     IParentImpl *object = NULL;
3182     HRESULT res = D3D_OK;
3183     IWineD3DSwapChain *swapchain;
3184     IDirectDrawSurfaceImpl *iterator;
3185     TRACE("(%p) call back\n", device);
3186
3187     object = HeapAlloc(GetProcessHeap(),  HEAP_ZERO_MEMORY, sizeof(IParentImpl));
3188     if (NULL == object)
3189     {
3190         FIXME("Allocation of memory failed\n");
3191         *ppSwapChain = NULL;
3192         return DDERR_OUTOFVIDEOMEMORY;
3193     }
3194
3195     ICOM_INIT_INTERFACE(object, IParent, IParent_Vtbl);
3196     object->ref = 1;
3197
3198     res = IWineD3DDevice_CreateSwapChain(This->wineD3DDevice,
3199                                                    pPresentationParameters, 
3200                                                    &swapchain, 
3201                                                    (IUnknown*) ICOM_INTERFACE(object, IParent),
3202                                                    D3D7CB_CreateRenderTarget,
3203                                                    D3D7CB_CreateDepthStencilSurface,
3204                                                    This->ImplType);
3205     if (res != D3D_OK)
3206     {
3207         FIXME("(%p) call to IWineD3DDevice_CreateSwapChain failed\n", This);
3208         HeapFree(GetProcessHeap(), 0 , object);
3209         *ppSwapChain = NULL;
3210     }
3211     else
3212     {
3213         *ppSwapChain = swapchain;
3214         object->child = (IUnknown *) swapchain;
3215         This->d3d_target->wineD3DSwapChain = swapchain;
3216         iterator = This->d3d_target->complex_array[0];
3217         while(iterator) {
3218             iterator->wineD3DSwapChain = swapchain;
3219             iterator = iterator->complex_array[0];
3220         }
3221     }
3222
3223     return res;
3224 }
3225
3226 static HRESULT IDirectDrawImpl_CreateGDISwapChain(IDirectDrawImpl *This,
3227                                                          IDirectDrawSurfaceImpl *primary) {
3228     HRESULT hr;
3229     WINED3DPRESENT_PARAMETERS presentation_parameters;
3230     HWND window;
3231
3232     window = This->dest_window;
3233
3234     memset(&presentation_parameters, 0, sizeof(presentation_parameters));
3235
3236     /* Use the surface description for the device parameters, not the
3237      * Device settings. The app might render to an offscreen surface
3238      */
3239     presentation_parameters.BackBufferWidth                 = primary->surface_desc.dwWidth;
3240     presentation_parameters.BackBufferHeight                = primary->surface_desc.dwHeight;
3241     presentation_parameters.BackBufferFormat                = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
3242     presentation_parameters.BackBufferCount                 = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT) ? primary->surface_desc.dwBackBufferCount : 0;
3243     presentation_parameters.MultiSampleType                 = WINED3DMULTISAMPLE_NONE;
3244     presentation_parameters.MultiSampleQuality              = 0;
3245     presentation_parameters.SwapEffect                      = WINED3DSWAPEFFECT_FLIP;
3246     presentation_parameters.hDeviceWindow                   = window;
3247     presentation_parameters.Windowed                        = !(This->cooperative_level & DDSCL_FULLSCREEN);
3248     presentation_parameters.EnableAutoDepthStencil          = FALSE; /* Not on GDI swapchains */
3249     presentation_parameters.AutoDepthStencilFormat          = 0;
3250     presentation_parameters.Flags                           = 0;
3251     presentation_parameters.FullScreen_RefreshRateInHz      = WINED3DPRESENT_RATE_DEFAULT; /* Default rate: It's already set */
3252     presentation_parameters.PresentationInterval            = WINED3DPRESENT_INTERVAL_DEFAULT;
3253
3254     This->d3d_target = primary;
3255     hr = IWineD3DDevice_InitGDI(This->wineD3DDevice,
3256                                 &presentation_parameters,
3257                                 D3D7CB_CreateAdditionalSwapChain);
3258     This->d3d_target = NULL;
3259
3260     if (hr != D3D_OK)
3261     {
3262         FIXME("(%p) call to IWineD3DDevice_InitGDI failed\n", This);
3263         primary->wineD3DSwapChain = NULL;
3264     }
3265     return hr;
3266 }
3267
3268 /*****************************************************************************
3269  * IDirectDrawImpl_AttachD3DDevice
3270  *
3271  * Initializes the D3D capabilities of WineD3D
3272  *
3273  * Params:
3274  *  primary: The primary surface for D3D
3275  *
3276  * Returns
3277  *  DD_OK on success,
3278  *  DDERR_* otherwise
3279  *
3280  *****************************************************************************/
3281 static HRESULT
3282 IDirectDrawImpl_AttachD3DDevice(IDirectDrawImpl *This,
3283                                 IDirectDrawSurfaceImpl *primary)
3284 {
3285     HRESULT hr;
3286     HWND                  window = This->dest_window;
3287
3288     WINED3DPRESENT_PARAMETERS localParameters;
3289
3290     TRACE("(%p)->(%p)\n", This, primary);
3291
3292     /* If there's no window, create a hidden window. WineD3D needs it */
3293     if(window == 0 || window == GetDesktopWindow())
3294     {
3295         window = CreateWindowExA(0, This->classname, "Hidden D3D Window",
3296                                  WS_DISABLED, 0, 0,
3297                                  GetSystemMetrics(SM_CXSCREEN),
3298                                  GetSystemMetrics(SM_CYSCREEN),
3299                                  NULL, NULL, GetModuleHandleA(0), NULL);
3300
3301         ShowWindow(window, SW_HIDE);   /* Just to be sure */
3302         WARN("(%p) No window for the Direct3DDevice, created a hidden window. HWND=%p\n", This, window);
3303     }
3304     else
3305     {
3306         TRACE("(%p) Using existing window %p for Direct3D rendering\n", This, window);
3307     }
3308     This->d3d_window = window;
3309
3310     /* Store the future Render Target surface */
3311     This->d3d_target = primary;
3312
3313     /* Use the surface description for the device parameters, not the
3314      * Device settings. The app might render to an offscreen surface
3315      */
3316     localParameters.BackBufferWidth                 = primary->surface_desc.dwWidth;
3317     localParameters.BackBufferHeight                = primary->surface_desc.dwHeight;
3318     localParameters.BackBufferFormat                = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
3319     localParameters.BackBufferCount                 = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT) ? primary->surface_desc.dwBackBufferCount : 0;
3320     localParameters.MultiSampleType                 = WINED3DMULTISAMPLE_NONE;
3321     localParameters.MultiSampleQuality              = 0;
3322     localParameters.SwapEffect                      = WINED3DSWAPEFFECT_COPY;
3323     localParameters.hDeviceWindow                   = window;
3324     localParameters.Windowed                        = !(This->cooperative_level & DDSCL_FULLSCREEN);
3325     localParameters.EnableAutoDepthStencil          = TRUE;
3326     localParameters.AutoDepthStencilFormat          = WINED3DFMT_D16;
3327     localParameters.Flags                           = 0;
3328     localParameters.FullScreen_RefreshRateInHz      = WINED3DPRESENT_RATE_DEFAULT; /* Default rate: It's already set */
3329     localParameters.PresentationInterval            = WINED3DPRESENT_INTERVAL_DEFAULT;
3330
3331     TRACE("Passing mode %d\n", localParameters.BackBufferFormat);
3332
3333     /* Set this NOW, otherwise creating the depth stencil surface will cause a
3334      * recursive loop until ram or emulated video memory is full
3335      */
3336     This->d3d_initialized = TRUE;
3337
3338     hr = IWineD3DDevice_Init3D(This->wineD3DDevice,
3339                                &localParameters,
3340                                D3D7CB_CreateAdditionalSwapChain);
3341     if(FAILED(hr))
3342     {
3343         This->d3d_target = NULL;
3344         This->d3d_initialized = FALSE;
3345         return hr;
3346     }
3347
3348     This->declArraySize = 2;
3349     This->decls = HeapAlloc(GetProcessHeap(),
3350                             HEAP_ZERO_MEMORY,
3351                             sizeof(*This->decls) * This->declArraySize);
3352     if(!This->decls)
3353     {
3354         ERR("Error allocating an array for the converted vertex decls\n");
3355         This->declArraySize = 0;
3356         hr = IWineD3DDevice_Uninit3D(This->wineD3DDevice,
3357                                      D3D7CB_DestroyDepthStencilSurface,
3358                                      D3D7CB_DestroySwapChain);
3359         return E_OUTOFMEMORY;
3360     }
3361
3362     /* Create an Index Buffer parent */
3363     TRACE("(%p) Successfully initialized 3D\n", This);
3364     return DD_OK;
3365 }
3366
3367 /*****************************************************************************
3368  * DirectDrawCreateClipper (DDRAW.@)
3369  *
3370  * Creates a new IDirectDrawClipper object.
3371  *
3372  * Params:
3373  *  Clipper: Address to write the interface pointer to
3374  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3375  *            NULL
3376  *
3377  * Returns:
3378  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3379  *  E_OUTOFMEMORY if allocating the object failed
3380  *
3381  *****************************************************************************/
3382 HRESULT WINAPI
3383 DirectDrawCreateClipper(DWORD Flags,
3384                         LPDIRECTDRAWCLIPPER *Clipper,
3385                         IUnknown *UnkOuter)
3386 {
3387     IDirectDrawClipperImpl* object;
3388     TRACE("(%08x,%p,%p)\n", Flags, Clipper, UnkOuter);
3389
3390     EnterCriticalSection(&ddraw_cs);
3391     if (UnkOuter != NULL)
3392     {
3393         LeaveCriticalSection(&ddraw_cs);
3394         return CLASS_E_NOAGGREGATION;
3395     }
3396
3397     if (!LoadWineD3D())
3398     {
3399         LeaveCriticalSection(&ddraw_cs);
3400         return DDERR_NODIRECTDRAWSUPPORT;
3401     }
3402
3403     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3404                      sizeof(IDirectDrawClipperImpl));
3405     if (object == NULL)
3406     {
3407         LeaveCriticalSection(&ddraw_cs);
3408         return E_OUTOFMEMORY;
3409     }
3410
3411     ICOM_INIT_INTERFACE(object, IDirectDrawClipper, IDirectDrawClipper_Vtbl);
3412     object->ref = 1;
3413     object->wineD3DClipper = pWineDirect3DCreateClipper((IUnknown *) object);
3414     if(!object->wineD3DClipper)
3415     {
3416         HeapFree(GetProcessHeap(), 0, object);
3417         LeaveCriticalSection(&ddraw_cs);
3418         return E_OUTOFMEMORY;
3419     }
3420
3421     *Clipper = (IDirectDrawClipper *) object;
3422     LeaveCriticalSection(&ddraw_cs);
3423     return DD_OK;
3424 }
3425
3426 /*****************************************************************************
3427  * IDirectDraw7::CreateClipper
3428  *
3429  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3430  *
3431  *****************************************************************************/
3432 static HRESULT WINAPI
3433 IDirectDrawImpl_CreateClipper(IDirectDraw7 *iface,
3434                               DWORD Flags,
3435                               IDirectDrawClipper **Clipper,
3436                               IUnknown *UnkOuter)
3437 {
3438     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
3439     TRACE("(%p)->(%x,%p,%p)\n", This, Flags, Clipper, UnkOuter);
3440     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3441 }
3442
3443 /*****************************************************************************
3444  * IDirectDraw7::CreatePalette
3445  *
3446  * Creates a new IDirectDrawPalette object
3447  *
3448  * Params:
3449  *  Flags: The flags for the new clipper
3450  *  ColorTable: Color table to assign to the new clipper
3451  *  Palette: Address to write the interface pointer to
3452  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3453  *            NULL
3454  *
3455  * Returns:
3456  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3457  *  E_OUTOFMEMORY if allocating the object failed
3458  *
3459  *****************************************************************************/
3460 static HRESULT WINAPI
3461 IDirectDrawImpl_CreatePalette(IDirectDraw7 *iface,
3462                               DWORD Flags,
3463                               PALETTEENTRY *ColorTable,
3464                               IDirectDrawPalette **Palette,
3465                               IUnknown *pUnkOuter)
3466 {
3467     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
3468     IDirectDrawPaletteImpl *object;
3469     HRESULT hr = DDERR_GENERIC;
3470     TRACE("(%p)->(%x,%p,%p,%p)\n", This, Flags, ColorTable, Palette, pUnkOuter);
3471
3472     EnterCriticalSection(&ddraw_cs);
3473     if(pUnkOuter != NULL)
3474     {
3475         WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
3476         LeaveCriticalSection(&ddraw_cs);
3477         return CLASS_E_NOAGGREGATION;
3478     }
3479
3480     /* The refcount test shows that a cooplevel is required for this */
3481     if(!This->cooperative_level)
3482     {
3483         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
3484         LeaveCriticalSection(&ddraw_cs);
3485         return DDERR_NOCOOPERATIVELEVELSET;
3486     }
3487
3488     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
3489     if(!object)
3490     {
3491         ERR("Out of memory when allocating memory for a palette implementation\n");
3492         LeaveCriticalSection(&ddraw_cs);
3493         return E_OUTOFMEMORY;
3494     }
3495
3496     ICOM_INIT_INTERFACE(object, IDirectDrawPalette, IDirectDrawPalette_Vtbl);
3497     object->ref = 1;
3498     object->ddraw_owner = This;
3499
3500     hr = IWineD3DDevice_CreatePalette(This->wineD3DDevice, Flags, ColorTable, &object->wineD3DPalette, (IUnknown *) ICOM_INTERFACE(object, IDirectDrawPalette) );
3501     if(hr != DD_OK)
3502     {
3503         HeapFree(GetProcessHeap(), 0, object);
3504         LeaveCriticalSection(&ddraw_cs);
3505         return hr;
3506     }
3507
3508     IDirectDraw7_AddRef(iface);
3509     object->ifaceToRelease = (IUnknown *) iface;
3510     *Palette = ICOM_INTERFACE(object, IDirectDrawPalette);
3511     LeaveCriticalSection(&ddraw_cs);
3512     return DD_OK;
3513 }
3514
3515 /*****************************************************************************
3516  * IDirectDraw7::DuplicateSurface
3517  *
3518  * Duplicates a surface. The surface memory points to the same memory as
3519  * the original surface, and it's released when the last surface referencing
3520  * it is released. I guess that's beyond Wine's surface management right now
3521  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
3522  * test application to implement this)
3523  *
3524  * Params:
3525  *  Src: Address of the source surface
3526  *  Dest: Address to write the new surface pointer to
3527  *
3528  * Returns:
3529  *  See IDirectDraw7::CreateSurface
3530  *
3531  *****************************************************************************/
3532 static HRESULT WINAPI
3533 IDirectDrawImpl_DuplicateSurface(IDirectDraw7 *iface,
3534                                  IDirectDrawSurface7 *Src,
3535                                  IDirectDrawSurface7 **Dest)
3536 {
3537     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
3538     IDirectDrawSurfaceImpl *Surf = ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, Src);
3539
3540     FIXME("(%p)->(%p,%p)\n", This, Surf, Dest);
3541
3542     /* For now, simply create a new, independent surface */
3543     return IDirectDraw7_CreateSurface(iface,
3544                                       &Surf->surface_desc,
3545                                       Dest,
3546                                       NULL);
3547 }
3548
3549 /*****************************************************************************
3550  * IDirectDraw7 VTable
3551  *****************************************************************************/
3552 const IDirectDraw7Vtbl IDirectDraw7_Vtbl =
3553 {
3554     /*** IUnknown ***/
3555     IDirectDrawImpl_QueryInterface,
3556     IDirectDrawImpl_AddRef,
3557     IDirectDrawImpl_Release,
3558     /*** IDirectDraw ***/
3559     IDirectDrawImpl_Compact,
3560     IDirectDrawImpl_CreateClipper,
3561     IDirectDrawImpl_CreatePalette,
3562     IDirectDrawImpl_CreateSurface,
3563     IDirectDrawImpl_DuplicateSurface,
3564     IDirectDrawImpl_EnumDisplayModes,
3565     IDirectDrawImpl_EnumSurfaces,
3566     IDirectDrawImpl_FlipToGDISurface,
3567     IDirectDrawImpl_GetCaps,
3568     IDirectDrawImpl_GetDisplayMode,
3569     IDirectDrawImpl_GetFourCCCodes,
3570     IDirectDrawImpl_GetGDISurface,
3571     IDirectDrawImpl_GetMonitorFrequency,
3572     IDirectDrawImpl_GetScanLine,
3573     IDirectDrawImpl_GetVerticalBlankStatus,
3574     IDirectDrawImpl_Initialize,
3575     IDirectDrawImpl_RestoreDisplayMode,
3576     IDirectDrawImpl_SetCooperativeLevel,
3577     IDirectDrawImpl_SetDisplayMode,
3578     IDirectDrawImpl_WaitForVerticalBlank,
3579     /*** IDirectDraw2 ***/
3580     IDirectDrawImpl_GetAvailableVidMem,
3581     /*** IDirectDraw3 ***/
3582     IDirectDrawImpl_GetSurfaceFromDC,
3583     /*** IDirectDraw4 ***/
3584     IDirectDrawImpl_RestoreAllSurfaces,
3585     IDirectDrawImpl_TestCooperativeLevel,
3586     IDirectDrawImpl_GetDeviceIdentifier,
3587     /*** IDirectDraw7 ***/
3588     IDirectDrawImpl_StartModeTest,
3589     IDirectDrawImpl_EvaluateMode
3590 };
3591
3592 /*****************************************************************************
3593  * IDirectDrawImpl_FindDecl
3594  *
3595  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
3596  * if none was found.
3597  *
3598  * This function is in ddraw.c and the DDraw object space because D3D7
3599  * vertex buffers are created using the IDirect3D interface to the ddraw
3600  * object, so they can be valid across D3D devices(theoretically. The ddraw
3601  * object also owns the wined3d device
3602  *
3603  * Parameters:
3604  *  This: Device
3605  *  fvf: Fvf to find the decl for
3606  *
3607  * Returns:
3608  *  NULL in case of an error, the IWineD3DVertexDeclaration interface for the
3609  *  fvf otherwise.
3610  *
3611  *****************************************************************************/
3612 IWineD3DVertexDeclaration *
3613 IDirectDrawImpl_FindDecl(IDirectDrawImpl *This,
3614                          DWORD fvf)
3615 {
3616     HRESULT hr;
3617     IWineD3DVertexDeclaration* pDecl = NULL;
3618     int p, low, high; /* deliberately signed */
3619     struct FvfToDecl *convertedDecls = This->decls;
3620
3621     TRACE("Searching for declaration for fvf %08x... ", fvf);
3622
3623     low = 0;
3624     high = This->numConvertedDecls - 1;
3625     while(low <= high) {
3626         p = (low + high) >> 1;
3627         TRACE("%d ", p);
3628         if(convertedDecls[p].fvf == fvf) {
3629             TRACE("found %p\n", convertedDecls[p].decl);
3630             return convertedDecls[p].decl;
3631         } else if(convertedDecls[p].fvf < fvf) {
3632             low = p + 1;
3633         } else {
3634             high = p - 1;
3635         }
3636     }
3637     TRACE("not found. Creating and inserting at position %d.\n", low);
3638
3639     hr = IWineD3DDevice_CreateVertexDeclarationFromFVF(This->wineD3DDevice,
3640                                                        &pDecl,
3641                                                        (IUnknown *) ICOM_INTERFACE(This, IDirectDraw7),
3642                                                        fvf);
3643     if (hr != S_OK) return NULL;
3644
3645     if(This->declArraySize == This->numConvertedDecls) {
3646         int grow = max(This->declArraySize / 2, 8);
3647         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
3648                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
3649         if(!convertedDecls) {
3650             /* This will destroy it */
3651             IWineD3DVertexDeclaration_Release(pDecl);
3652             return NULL;
3653         }
3654         This->decls = convertedDecls;
3655         This->declArraySize += grow;
3656     }
3657
3658     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
3659     convertedDecls[low].decl = pDecl;
3660     convertedDecls[low].fvf = fvf;
3661     This->numConvertedDecls++;
3662
3663     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
3664     return pDecl;
3665 }