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