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