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