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