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