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