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