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