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