ddraw: Implement GetRenderState for D3DRENDERSTATE_TEXTUREHANDLE.
[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);
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                      UINT Width, UINT Height,
1660                      WINED3DFORMAT Format,
1661                      DWORD Usage, WINED3DPOOL Pool, UINT level,
1662                      IWineD3DSurface **Surface,
1663                      HANDLE *SharedHandle)
1664 {
1665     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
1666     IDirectDrawSurfaceImpl *surf = This->tex_root;
1667     int i;
1668     TRACE("(%p) call back. surf=%p\n", device, surf);
1669
1670     /* Find the wanted mipmap. There are enough mipmaps in the chain */
1671     for(i = 0; i < level; i++)
1672         surf = surf->next_complex;
1673
1674     /* Return the surface */
1675     *Surface = surf->WineD3DSurface;
1676
1677     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *Surface, surf);
1678     return D3D_OK;
1679 }
1680
1681 /*****************************************************************************
1682  * IDirectDrawImpl_CreateNewSurface
1683  *
1684  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
1685  * with the passed parameters.
1686  *
1687  * Params:
1688  *  DDSD: Description of the surface to create
1689  *  Surf: Address to store the interface pointer at
1690  *
1691  * Returns:
1692  *  DD_OK on success
1693  *
1694  *****************************************************************************/
1695 static HRESULT WINAPI
1696 IDirectDrawImpl_CreateNewSurface(IDirectDrawImpl *This,
1697                                  DDSURFACEDESC2 *pDDSD,
1698                                  IDirectDrawSurfaceImpl **ppSurf,
1699                                  UINT level)
1700 {
1701     HRESULT hr;
1702     UINT Width = 0, Height = 0;
1703     WINED3DFORMAT Format = WINED3DFMT_UNKNOWN;
1704     WINED3DRESOURCETYPE ResType = WINED3DRTYPE_SURFACE;
1705     DWORD Usage = 0;
1706     WINED3DSURFTYPE ImplType = This->ImplType;
1707     WINED3DSURFACE_DESC Desc;
1708     IUnknown *Parent;
1709     IParentImpl *parImpl = NULL;
1710     WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
1711
1712     /* Dummies for GetDesc */
1713     WINED3DPOOL dummy_d3dpool;
1714     WINED3DMULTISAMPLE_TYPE dummy_mst;
1715     UINT dummy_uint;
1716     DWORD dummy_dword;
1717
1718     if (TRACE_ON(ddraw))
1719     {
1720         TRACE(" (%p) Requesting surface desc :\n", This);
1721         DDRAW_dump_surface_desc(pDDSD);
1722     }
1723
1724     /* Select the surface type, if it wasn't choosen yet */
1725     if(ImplType == SURFACE_UNKNOWN)
1726     {
1727         /* Use GL Surfaces if a D3DDEVICE Surface is requested */
1728         if(pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
1729         {
1730             TRACE("(%p) Choosing GL surfaces because a 3DDEVICE Surface was requested\n", This);
1731             ImplType = SURFACE_OPENGL;
1732         }
1733
1734         /* Otherwise use GDI surfaces for now */
1735         else
1736         {
1737             TRACE("(%p) Choosing GDI surfaces for 2D rendering\n", This);
1738             ImplType = SURFACE_GDI;
1739         }
1740
1741         /* Policy if all surface implementations are available:
1742          * First, check if a default type was set with winecfg. If not,
1743          * try Xrender surfaces, and use them if they work. Next, check if
1744          * accelerated OpenGL is available, and use GL surfaces in this
1745          * case. If all else fails, use GDI surfaces. If a 3DDEVICE surface
1746          * was created, always use OpenGL surfaces.
1747          *
1748          * (Note: Xrender surfaces are not implemented for now, the
1749          * unaccelerated implementation uses GDI to render in Software)
1750          */
1751
1752         /* Store the type. If it needs to be changed, all WineD3DSurfaces have to
1753          * be re-created. This could be done with IDirectDrawSurface7::Restore
1754          */
1755         This->ImplType = ImplType;
1756     }
1757     else
1758     {
1759          if((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE ) && 
1760             (This->ImplType != SURFACE_OPENGL ) && DefaultSurfaceType == SURFACE_UNKNOWN)
1761         {
1762             /* We have to change to OpenGL,
1763              * and re-create all WineD3DSurfaces
1764              */
1765             ImplType = SURFACE_OPENGL;
1766             This->ImplType = ImplType;
1767             TRACE("(%p) Re-creating all surfaces\n", This);
1768             IDirectDrawImpl_RecreateAllSurfaces(This);
1769             TRACE("(%p) Done recreating all surfaces\n", This);
1770         }
1771         else if(This->ImplType != SURFACE_OPENGL)
1772         {
1773             WARN("The application requests a 3D capable surface, but a non-opengl surface was set in the registry\n");
1774             /* Do not fail surface creation, only fail 3D device creation */
1775         }
1776     }
1777
1778     /* Get the correct wined3d usage */
1779     if (pDDSD->ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE |
1780                                  DDSCAPS_BACKBUFFER     |
1781                                  DDSCAPS_3DDEVICE       ) )
1782     {
1783         Usage |= WINED3DUSAGE_RENDERTARGET;
1784
1785         pDDSD->ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY |
1786                                  DDSCAPS_VISIBLE     |
1787                                  DDSCAPS_LOCALVIDMEM;
1788     }
1789     if (pDDSD->ddsCaps.dwCaps & (DDSCAPS_OVERLAY))
1790     {
1791         Usage |= WINED3DUSAGE_OVERLAY;
1792     }
1793     if(This->depthstencil)
1794     {
1795         /* The depth stencil creation callback sets this flag.
1796          * Set the WineD3D usage to let it know that it's a depth
1797          * Stencil surface.
1798          */
1799         Usage |= WINED3DUSAGE_DEPTHSTENCIL;
1800     }
1801     if(pDDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
1802     {
1803         Pool = WINED3DPOOL_SYSTEMMEM;
1804     }
1805
1806     Format = PixelFormat_DD2WineD3D(&pDDSD->u4.ddpfPixelFormat);
1807     if(Format == WINED3DFMT_UNKNOWN)
1808     {
1809         ERR("Unsupported / Unknown pixelformat\n");
1810         return DDERR_INVALIDPIXELFORMAT;
1811     }
1812
1813     /* Create the Surface object */
1814     *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
1815     if(!*ppSurf)
1816     {
1817         ERR("(%p) Error allocating memory for a surface\n", This);
1818         return DDERR_OUTOFVIDEOMEMORY;
1819     }
1820     ICOM_INIT_INTERFACE(*ppSurf, IDirectDrawSurface7, IDirectDrawSurface7_Vtbl);
1821     ICOM_INIT_INTERFACE(*ppSurf, IDirectDrawSurface3, IDirectDrawSurface3_Vtbl);
1822     ICOM_INIT_INTERFACE(*ppSurf, IDirectDrawGammaControl, IDirectDrawGammaControl_Vtbl);
1823     ICOM_INIT_INTERFACE(*ppSurf, IDirect3DTexture2, IDirect3DTexture2_Vtbl);
1824     ICOM_INIT_INTERFACE(*ppSurf, IDirect3DTexture, IDirect3DTexture1_Vtbl);
1825     (*ppSurf)->ref = 1;
1826     (*ppSurf)->version = 7;
1827     (*ppSurf)->ddraw = This;
1828     (*ppSurf)->surface_desc.dwSize = sizeof(DDSURFACEDESC2);
1829     (*ppSurf)->surface_desc.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1830     DD_STRUCT_COPY_BYSIZE(&(*ppSurf)->surface_desc, pDDSD);
1831
1832     /* Surface attachments */
1833     (*ppSurf)->next_attached = NULL;
1834     (*ppSurf)->first_attached = *ppSurf;
1835
1836     (*ppSurf)->next_complex = NULL;
1837     (*ppSurf)->first_complex = *ppSurf;
1838
1839     /* Needed to re-create the surface on an implementation change */
1840     (*ppSurf)->ImplType = ImplType;
1841
1842     /* For D3DDevice creation */
1843     (*ppSurf)->isRenderTarget = FALSE;
1844
1845     /* A trace message for debugging */
1846     TRACE("(%p) Created IDirectDrawSurface implementation structure at %p\n", This, *ppSurf);
1847
1848     if(pDDSD->ddsCaps.dwCaps & ( DDSCAPS_PRIMARYSURFACE | DDSCAPS_TEXTURE | DDSCAPS_3DDEVICE) )
1849     {
1850         /* Render targets and textures need a IParent interface,
1851          * because WineD3D will destroy them when the swapchain
1852          * is released
1853          */
1854         parImpl = HeapAlloc(GetProcessHeap(), 0, sizeof(IParentImpl));
1855         if(!parImpl)
1856         {
1857             ERR("Out of memory when allocating memory for a IParent implementation\n");
1858             return DDERR_OUTOFMEMORY;
1859         }
1860         parImpl->ref = 1;
1861         ICOM_INIT_INTERFACE(parImpl, IParent, IParent_Vtbl);
1862         Parent = (IUnknown *) ICOM_INTERFACE(parImpl, IParent);
1863         TRACE("Using IParent interface %p as parent\n", parImpl);
1864     }
1865     else
1866     {
1867         /* Use the surface as parent */
1868         Parent = (IUnknown *) ICOM_INTERFACE(*ppSurf, IDirectDrawSurface7);
1869         TRACE("Using Surface interface %p as parent\n", *ppSurf);
1870     }
1871
1872     /* Now create the WineD3D Surface */
1873     hr = IWineD3DDevice_CreateSurface(This->wineD3DDevice,
1874                                       pDDSD->dwWidth,
1875                                       pDDSD->dwHeight,
1876                                       Format,
1877                                       TRUE /* Lockable */,
1878                                       FALSE /* Discard */,
1879                                       level,
1880                                       &(*ppSurf)->WineD3DSurface,
1881                                       ResType, Usage,
1882                                       Pool,
1883                                       WINED3DMULTISAMPLE_NONE,
1884                                       0 /* MultiSampleQuality */,
1885                                       0 /* SharedHandle */,
1886                                       ImplType,
1887                                       Parent);
1888
1889     if(hr != D3D_OK)
1890     {
1891         ERR("IWineD3DDevice::CreateSurface failed. hr = %08x\n", hr);
1892         return hr;
1893     }
1894
1895     /* Set the child of the parent implementation if it exists */
1896     if(parImpl)
1897     {
1898         parImpl->child = (IUnknown *) (*ppSurf)->WineD3DSurface;
1899         /* The IParent releases the WineD3DSurface, and
1900          * the ddraw surface does that too. Hold a reference
1901          */
1902         IWineD3DSurface_AddRef((*ppSurf)->WineD3DSurface);
1903     }
1904
1905     /* Increase the surface counter, and attach the surface */
1906     InterlockedIncrement(&This->surfaces);
1907     list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
1908
1909     /* Here we could store all created surfaces in the DirectDrawImpl structure,
1910      * But this could also be delegated to WineDDraw, as it keeps track of all its
1911      * resources. Not implemented for now, as there are more important things ;)
1912      */
1913
1914     /* Get the pixel format of the WineD3DSurface and store it.
1915      * Don't use the Format choosen above, WineD3D might have
1916      * changed it
1917      */
1918     Desc.Format = &Format;
1919     Desc.Type = &ResType;
1920     Desc.Usage = &Usage;
1921     Desc.Pool = &dummy_d3dpool;
1922     Desc.Size = &dummy_uint;
1923     Desc.MultiSampleType = &dummy_mst;
1924     Desc.MultiSampleQuality = &dummy_dword;
1925     Desc.Width = &Width;
1926     Desc.Height = &Height;
1927
1928     (*ppSurf)->surface_desc.dwFlags |= DDSD_PIXELFORMAT;
1929     hr = IWineD3DSurface_GetDesc((*ppSurf)->WineD3DSurface, &Desc);
1930     if(hr != D3D_OK)
1931     {
1932         ERR("IWineD3DSurface::GetDesc failed\n");
1933         IDirectDrawSurface7_Release( (IDirectDrawSurface7 *) *ppSurf);
1934         return hr;
1935     }
1936
1937     if(Format == WINED3DFMT_UNKNOWN)
1938     {
1939         FIXME("IWineD3DSurface::GetDesc returned WINED3DFMT_UNKNOWN\n");
1940     }
1941     PixelFormat_WineD3DtoDD( &(*ppSurf)->surface_desc.u4.ddpfPixelFormat, Format);
1942
1943     /* Anno 1602 stores the pitch right after surface creation, so make sure it's there.
1944      * I can't LockRect() the surface here because if OpenGL surfaces are in use, the
1945      * WineD3DDevice might not be useable for 3D yet, so an extra method was created
1946      */
1947     (*ppSurf)->surface_desc.dwFlags |= DDSD_PITCH;
1948     (*ppSurf)->surface_desc.u1.lPitch = IWineD3DSurface_GetPitch((*ppSurf)->WineD3DSurface);
1949
1950     /* Application passed a color key? Set it! */
1951     if(pDDSD->dwFlags & DDSD_CKDESTOVERLAY)
1952     {
1953         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
1954                                     DDCKEY_DESTOVERLAY,
1955                                     &pDDSD->u3.ddckCKDestOverlay);
1956     }
1957     if(pDDSD->dwFlags & DDSD_CKDESTBLT)
1958     {
1959         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
1960                                     DDCKEY_DESTBLT,
1961                                     &pDDSD->ddckCKDestBlt);
1962     }
1963     if(pDDSD->dwFlags & DDSD_CKSRCOVERLAY)
1964     {
1965         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
1966                                     DDCKEY_SRCOVERLAY,
1967                                     &pDDSD->ddckCKSrcOverlay);
1968     }
1969     if(pDDSD->dwFlags & DDSD_CKSRCBLT)
1970     {
1971         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
1972                                     DDCKEY_SRCBLT,
1973                                     &pDDSD->ddckCKSrcBlt);
1974     }
1975     if ( pDDSD->dwFlags & DDSD_LPSURFACE)
1976     {
1977         hr = IWineD3DSurface_SetMem((*ppSurf)->WineD3DSurface, pDDSD->lpSurface);
1978         if(hr != WINED3D_OK)
1979         {
1980             /* No need for a trace here, wined3d does that for us */
1981             IDirectDrawSurface7_Release(ICOM_INTERFACE((*ppSurf), IDirectDrawSurface7));
1982             return hr;
1983         }
1984     }
1985
1986     return DD_OK;
1987 }
1988
1989 /*****************************************************************************
1990  * IDirectDraw7::CreateSurface
1991  *
1992  * Creates a new IDirectDrawSurface object and returns its interface.
1993  *
1994  * The surface connections with wined3d are a bit tricky. Basically it works
1995  * like this:
1996  *
1997  * |------------------------|               |-----------------|
1998  * | DDraw surface          |               | WineD3DSurface  |
1999  * |                        |               |                 |
2000  * |        WineD3DSurface  |-------------->|                 |
2001  * |        Child           |<------------->| Parent          |
2002  * |------------------------|               |-----------------|
2003  *
2004  * The DDraw surface is the parent of the wined3d surface, and it releases
2005  * the WineD3DSurface when the ddraw surface is destroyed.
2006  *
2007  * However, for all surfaces which can be in a container in WineD3D,
2008  * we have to do this. These surfaces are ususally complex surfaces,
2009  * so this concerns primary surfaces with a front and a back buffer,
2010  * and textures.
2011  *
2012  * |------------------------|               |-----------------|
2013  * | DDraw surface          |               | Containter      |
2014  * |                        |               |                 |
2015  * |                  Child |<------------->| Parent          |
2016  * |                Texture |<------------->|                 |
2017  * |         WineD3DSurface |<----|         |          Levels |<--|
2018  * | Complex connection     |     |         |                 |   |
2019  * |------------------------|     |         |-----------------|   |
2020  *  ^                             |                               |
2021  *  |                             |                               |
2022  *  |                             |                               |
2023  *  |    |------------------|     |         |-----------------|   |
2024  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2025  *  |    |                  |               |                 |   |
2026  *  |    |            Child |<------------->| Parent          |   |
2027  *  |    |                  |               |       Container |<--|
2028  *  |    |------------------|               |-----------------|   |
2029  *  |                                                             |
2030  *  |   |----------------------|                                  |
2031  *  |   | DDraw surface 2      |                                  |
2032  *  |   |                      |                                  |
2033  *  |<->| Complex root   Child |                                  |
2034  *  |   |              Texture |                                  |
2035  *  |   |       WineD3DSurface |<----|                            |
2036  *  |   |----------------------|     |                            |
2037  *  |                                |                            |
2038  *  |    |---------------------|     |      |-----------------|   |
2039  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2040  *  |    |                     |            |                 |   |
2041  *  |    |               Child |<---------->| Parent          |   |
2042  *  |    |---------------------|            |       Container |<--|
2043  *  |                                       |-----------------|   |
2044  *  |                                                             |
2045  *  |             ---More surfaces can follow---                  |
2046  *
2047  * The reason is that the IWineD3DSwapchain(render target container)
2048  * and the IWineD3DTexure(Texture container) release the parents
2049  * of their surface's children, but by releasing the complex root
2050  * the surfaces which are complexly attached to it are destroyed
2051  * too. See IDirectDrawSurface::Release for a more detailed
2052  * explanation.
2053  *
2054  * Params:
2055  *  DDSD: Description of the surface to create
2056  *  Surf: Address to store the interface pointer at
2057  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2058  *            aggregation, so it has to be NULL
2059  *
2060  * Returns:
2061  *  DD_OK on success
2062  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2063  *  DDERR_* if an error occurs
2064  *
2065  *****************************************************************************/
2066 static HRESULT WINAPI
2067 IDirectDrawImpl_CreateSurface(IDirectDraw7 *iface,
2068                               DDSURFACEDESC2 *DDSD,
2069                               IDirectDrawSurface7 **Surf,
2070                               IUnknown *UnkOuter)
2071 {
2072     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
2073     IDirectDrawSurfaceImpl *object = NULL;
2074     HRESULT hr;
2075     LONG extra_surfaces = 0, i;
2076     DDSURFACEDESC2 desc2;
2077     UINT level = 0;
2078     WINED3DDISPLAYMODE Mode;
2079
2080     TRACE("(%p)->(%p,%p,%p)\n", This, DDSD, Surf, UnkOuter);
2081
2082     /* Some checks before we start */
2083     if (TRACE_ON(ddraw))
2084     {
2085         TRACE(" (%p) Requesting surface desc :\n", This);
2086         DDRAW_dump_surface_desc(DDSD);
2087     }
2088
2089     if (UnkOuter != NULL)
2090     {
2091         FIXME("(%p) : outer != NULL?\n", This);
2092         return CLASS_E_NOAGGREGATION; /* unchecked */
2093     }
2094
2095     if (!(DDSD->dwFlags & DDSD_CAPS))
2096     {
2097         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2098         DDSD->dwFlags |= DDSD_CAPS;
2099     }
2100     if (DDSD->ddsCaps.dwCaps == 0)
2101     {
2102         /* This has been checked on real Windows */
2103         DDSD->ddsCaps.dwCaps = DDSCAPS_LOCALVIDMEM | DDSCAPS_VIDEOMEMORY;
2104     }
2105
2106     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2107     {
2108         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2109         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2110     }
2111
2112     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2113     {
2114         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2115         WARN("(%p) Null surface pointer specified, ignore it!\n", This);
2116         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2117     }
2118
2119     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2120        !(This->cooperative_level & DDSCL_EXCLUSIVE))
2121     {
2122         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n", This);
2123         *Surf = NULL;
2124         return DDERR_NOEXCLUSIVEMODE;
2125     }
2126
2127     if (Surf == NULL)
2128     {
2129         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", This);
2130         return E_POINTER; /* unchecked */
2131     }
2132
2133     /* According to the msdn this flag is ignored by CreateSurface */
2134     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2135         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2136
2137     /* Modify some flags */
2138     memset(&desc2, 0, sizeof(desc2));
2139     desc2.dwSize = sizeof(desc2);   /* For the struct copy */
2140     DD_STRUCT_COPY_BYSIZE(&desc2, DDSD);
2141     desc2.dwSize = sizeof(desc2);   /* To override a possibly smaller size */
2142     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
2143
2144     /* Get the video mode from WineD3D - we will need it */
2145     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
2146                                        0, /* Swapchain 0 */
2147                                        &Mode);
2148     if(FAILED(hr))
2149     {
2150         ERR("Failed to read display mode from wined3d\n");
2151         switch(This->orig_bpp)
2152         {
2153             case 8:
2154                 Mode.Format = WINED3DFMT_P8;
2155                 break;
2156
2157             case 15:
2158                 Mode.Format = WINED3DFMT_X1R5G5B5;
2159                 break;
2160
2161             case 16:
2162                 Mode.Format = WINED3DFMT_R5G6B5;
2163                 break;
2164
2165             case 24:
2166                 Mode.Format = WINED3DFMT_R8G8B8;
2167                 break;
2168
2169             case 32:
2170                 Mode.Format = WINED3DFMT_X8R8G8B8;
2171                 break;
2172         }
2173         Mode.Width = This->orig_width;
2174         Mode.Height = This->orig_height;
2175     }
2176
2177     /* No pixelformat given? Use the current screen format */
2178     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
2179     {
2180         desc2.dwFlags |= DDSD_PIXELFORMAT;
2181         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
2182
2183         /* Wait: It could be a Z buffer */
2184         if(desc2.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
2185         {
2186             switch(desc2.u2.dwMipMapCount) /* Who had this glorious idea? */
2187             {
2188                 case 15:
2189                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D15S1);
2190                     break;
2191                 case 16:
2192                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D16);
2193                     break;
2194                 case 24:
2195                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D24X8);
2196                     break;
2197                 case 32:
2198                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D32);
2199                     break;
2200                 default:
2201                     ERR("Unknown Z buffer bit depth\n");
2202             }
2203         }
2204         else
2205         {
2206             PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
2207         }
2208     }
2209
2210     /* No Width or no Height? Use the current window size or
2211      * the original screen size
2212      */
2213     if(!(desc2.dwFlags & DDSD_WIDTH) ||
2214        !(desc2.dwFlags & DDSD_HEIGHT) )
2215     {
2216         HWND window;
2217
2218         /* Fallback: From WineD3D / original mode */
2219         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
2220         desc2.dwWidth = Mode.Width;
2221         desc2.dwHeight = Mode.Height;
2222
2223         hr = IWineD3DDevice_GetHWND(This->wineD3DDevice,
2224                                     &window);
2225         if( (hr == D3D_OK) && (window != 0) )
2226         {
2227             RECT rect;
2228             if(GetWindowRect(window, &rect) )
2229             {
2230                 /* This is a hack until I find a better solution */
2231                 if( (rect.right - rect.left) <= 1 ||
2232                     (rect.bottom - rect.top) <= 1 )
2233                 {
2234                     FIXME("Wanted to get surface dimensions from window %p, but it has only \
2235                            a size of %dx%d. Using full screen dimensions\n",
2236                            window, rect.right - rect.left, rect.bottom - rect.top);
2237                 }
2238                 else
2239                 {
2240                     /* Not sure if this is correct */
2241                     desc2.dwWidth = rect.right - rect.left;
2242                     desc2.dwHeight = rect.bottom - rect.top;
2243                     TRACE("Using window %p's dimensions: %dx%d\n", window, desc2.dwWidth, desc2.dwHeight);
2244                 }
2245             }
2246         }
2247     }
2248
2249     /* Mipmap count fixes */
2250     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2251     {
2252         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
2253         {
2254             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
2255             {
2256                 /* Mipmap count is given, nothing to do */
2257             }
2258             else
2259             {
2260                 /* Undocumented feature: Create sublevels until
2261                  * either the width or the height is 1
2262                  */
2263                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
2264                             desc2.dwWidth : desc2.dwHeight;
2265                 desc2.u2.dwMipMapCount = 0;
2266                 while( min )
2267                 {
2268                     desc2.u2.dwMipMapCount += 1;
2269                     min >>= 1;
2270                 }
2271             }
2272         }
2273         else
2274         {
2275             /* Not-complex mipmap -> Mipmapcount = 1 */
2276             desc2.u2.dwMipMapCount = 1;
2277         }
2278         extra_surfaces = desc2.u2.dwMipMapCount - 1;
2279
2280         /* There's a mipmap count in the created surface in any case */
2281         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
2282     }
2283     /* If no mipmap is given, the texture has only one level */
2284
2285     /* The first surface is a front buffer, the back buffer is created afterwards */
2286     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
2287     {
2288         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
2289     }
2290
2291     /* Create the first surface */
2292     hr = IDirectDrawImpl_CreateNewSurface(This, &desc2, &object, 0);
2293     if( hr != DD_OK)
2294     {
2295         ERR("IDirectDrawImpl_CreateNewSurface failed with %08x\n", hr);
2296         return hr;
2297     }
2298
2299     *Surf = ICOM_INTERFACE(object, IDirectDrawSurface7);
2300
2301     /* Create Additional surfaces if necessary
2302      * This applies to Primary surfaces which have a back buffer count
2303      * set, but not to mipmap textures. In case of Mipmap textures,
2304      * wineD3D takes care of the creation of additional surfaces
2305      */
2306     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
2307     {
2308         extra_surfaces = DDSD->dwBackBufferCount;
2309         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
2310         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
2311     }
2312     /* Set the DDSCAPS2_MIPMAPSUBLEVEL flag on mipmap sublevels according to the msdn */
2313     if(DDSD->ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2314     {
2315         desc2.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2316     }
2317
2318     for(i = 0; i < extra_surfaces; i++)
2319     {
2320         IDirectDrawSurfaceImpl *object2 = NULL;
2321         IDirectDrawSurfaceImpl *iterator;
2322
2323         /* increase the mipmap level, but only if a mipmap is created
2324          * In this case, also halve the size
2325          */
2326         if(DDSD->ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2327         {
2328             level++;
2329             if(desc2.dwWidth > 1) desc2.dwWidth /= 2;
2330             if(desc2.dwHeight > 1) desc2.dwHeight /= 2;
2331         }
2332
2333         hr = IDirectDrawImpl_CreateNewSurface(This,
2334                                               &desc2,
2335                                               &object2,
2336                                               level);
2337         if(hr != DD_OK)
2338         {
2339             /* This destroys and possibly created surfaces too */
2340             IDirectDrawSurface_Release( ICOM_INTERFACE(object, IDirectDrawSurface7) );
2341             return hr;
2342         }
2343
2344         /* Add the new surface to the complex attachment list */
2345         object2->first_complex = object;
2346         object2->next_complex = NULL;
2347         iterator = object;
2348         while(iterator->next_complex) iterator = iterator->next_complex;
2349         iterator->next_complex = object2;
2350
2351         /* Remove the (possible) back buffer cap from the new surface description,
2352          * because only one surface in the flipping chain is a back buffer, one
2353          * is a front buffer, the others are just primary surfaces.
2354          */
2355         desc2.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2356     }
2357
2358     /* Addref the ddraw interface to keep an reference for each surface */
2359     IDirectDraw7_AddRef(iface);
2360     object->ifaceToRelease = (IUnknown *) iface;
2361
2362     /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
2363      * But attach the d3ddevice only if the currently created surface was
2364      * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
2365      * The only case I can think of where this doesn't apply is when a
2366      * 2D app was configured by the user to run with OpenGL and it didn't create
2367      * the render target as first surface. In this case the render target creation
2368      * will cause the 3D init.
2369      */
2370     if( (This->ImplType == SURFACE_OPENGL) && !(This->d3d_initialized) &&
2371         desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE) )
2372     {
2373         IDirectDrawSurfaceImpl *target = object, *surface;
2374         struct list *entry;
2375
2376         /* Search for the primary to use as render target */
2377         LIST_FOR_EACH(entry, &This->surface_list)
2378         {
2379             surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
2380             if(surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
2381             {
2382                 /* found */
2383                 target = surface;
2384                 TRACE("Using primary %p as render target\n", target);
2385                 break;
2386             }
2387         }
2388
2389         TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", This, target);
2390         hr = IDirectDrawImpl_AttachD3DDevice(This, target->first_complex);
2391         if(hr != D3D_OK)
2392         {
2393             ERR("IDirectDrawImpl_AttachD3DDevice failed, hr = %x\n", hr);
2394         }
2395     }
2396
2397     /* Create a WineD3DTexture if a texture was requested */
2398     if(DDSD->ddsCaps.dwCaps & DDSCAPS_TEXTURE)
2399     {
2400         UINT levels;
2401         WINED3DFORMAT Format;
2402         WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
2403
2404         This->tex_root = object;
2405
2406         if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2407         {
2408             /* a mipmap is created, create enough levels */
2409             levels = desc2.u2.dwMipMapCount;
2410         }
2411         else
2412         {
2413             /* No mipmap is created, create one level */
2414             levels = 1;
2415         }
2416
2417         /* DDSCAPS_SYSTEMMEMORY textures are in WINED3DPOOL_SYSTEMMEM */
2418         if(DDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
2419         {
2420             Pool = WINED3DPOOL_SYSTEMMEM;
2421         }
2422         /* Should I forward the MANEGED cap to the managed pool ? */
2423
2424         /* Get the format. It's set already by CreateNewSurface */
2425         Format = PixelFormat_DD2WineD3D(&object->surface_desc.u4.ddpfPixelFormat);
2426
2427         /* The surfaces are already created, the callback only
2428          * passes the IWineD3DSurface to WineD3D
2429          */
2430         hr = IWineD3DDevice_CreateTexture( This->wineD3DDevice,
2431                                            DDSD->dwWidth, DDSD->dwHeight,
2432                                            levels, /* MipMapCount = Levels */
2433                                            0, /* usage */
2434                                            Format,
2435                                            Pool,
2436                                            &object->wineD3DTexture,
2437                                            0, /* SharedHandle */
2438                                            (IUnknown *) ICOM_INTERFACE(object, IDirectDrawSurface7),
2439                                            D3D7CB_CreateSurface );
2440         This->tex_root = NULL;
2441     }
2442
2443     return hr;
2444 }
2445
2446 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
2447 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
2448
2449 static BOOL
2450 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
2451                                     const DDPIXELFORMAT *provided)
2452 {
2453     /* Some flags must be present in both or neither for a match. */
2454     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
2455         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
2456         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
2457
2458     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
2459         return FALSE;
2460
2461     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
2462         return FALSE;
2463
2464     if (requested->dwFlags & DDPF_FOURCC)
2465         if (requested->dwFourCC != provided->dwFourCC)
2466             return FALSE;
2467
2468     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
2469                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
2470         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
2471             return FALSE;
2472
2473     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
2474                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
2475         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
2476             return FALSE;
2477
2478     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
2479         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
2480             return FALSE;
2481
2482     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
2483     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
2484                               |DDPF_BUMPDUDV))
2485         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
2486             return FALSE;
2487
2488     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
2489         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
2490             return FALSE;
2491
2492     return TRUE;
2493 }
2494
2495 static BOOL
2496 IDirectDrawImpl_DDSD_Match(const DDSURFACEDESC2* requested,
2497                            const DDSURFACEDESC2* provided)
2498 {
2499     struct compare_info
2500     {
2501         DWORD flag;
2502         ptrdiff_t offset;
2503         size_t size;
2504     };
2505
2506 #define CMP(FLAG, FIELD)                                \
2507         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
2508           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
2509
2510     static const struct compare_info compare[] =
2511     {
2512         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
2513         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
2514         CMP(CAPS, ddsCaps),
2515         CMP(CKDESTBLT, ddckCKDestBlt),
2516         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
2517         CMP(CKSRCBLT, ddckCKSrcBlt),
2518         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
2519         CMP(HEIGHT, dwHeight),
2520         CMP(LINEARSIZE, u1 /* dwLinearSize */),
2521         CMP(LPSURFACE, lpSurface),
2522         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
2523         CMP(PITCH, u1 /* lPitch */),
2524         /* PIXELFORMAT: manual */
2525         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
2526         CMP(TEXTURESTAGE, dwTextureStage),
2527         CMP(WIDTH, dwWidth),
2528         /* ZBUFFERBITDEPTH: "obsolete" */
2529     };
2530
2531 #undef CMP
2532
2533     unsigned int i;
2534
2535     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
2536         return FALSE;
2537
2538     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
2539     {
2540         if (requested->dwFlags & compare[i].flag
2541             && memcmp((const char *)provided + compare[i].offset,
2542                       (const char *)requested + compare[i].offset,
2543                       compare[i].size) != 0)
2544             return FALSE;
2545     }
2546
2547     if (requested->dwFlags & DDSD_PIXELFORMAT)
2548     {
2549         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
2550                                                 &provided->u4.ddpfPixelFormat))
2551             return FALSE;
2552     }
2553
2554     return TRUE;
2555 }
2556
2557 #undef DDENUMSURFACES_SEARCHTYPE
2558 #undef DDENUMSURFACES_MATCHTYPE
2559
2560 /*****************************************************************************
2561  * IDirectDraw7::EnumSurfaces
2562  *
2563  * Loops through all surfaces attached to this device and calls the
2564  * application callback. This can't be relayed to WineD3DDevice,
2565  * because some WineD3DSurfaces' parents are IParent objects
2566  *
2567  * Params:
2568  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
2569  *  DDSD: Description to filter for
2570  *  Context: Application-provided pointer, it's passed unmodified to the
2571  *           Callback function
2572  *  Callback: Address to call for each surface
2573  *
2574  * Returns:
2575  *  DDERR_INVALIDPARAMS if the callback is NULL
2576  *  DD_OK on success
2577  *
2578  *****************************************************************************/
2579 static HRESULT WINAPI
2580 IDirectDrawImpl_EnumSurfaces(IDirectDraw7 *iface,
2581                              DWORD Flags,
2582                              DDSURFACEDESC2 *DDSD,
2583                              void *Context,
2584                              LPDDENUMSURFACESCALLBACK7 Callback)
2585 {
2586     /* The surface enumeration is handled by WineDDraw,
2587      * because it keeps track of all surfaces attached to
2588      * it. The filtering is done by our callback function,
2589      * because WineDDraw doesn't handle ddraw-like surface
2590      * caps structures
2591      */
2592     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
2593     IDirectDrawSurfaceImpl *surf;
2594     BOOL all, nomatch;
2595     DDSURFACEDESC2 desc;
2596     struct list *entry, *entry2;
2597
2598     all = Flags & DDENUMSURFACES_ALL;
2599     nomatch = Flags & DDENUMSURFACES_NOMATCH;
2600
2601     TRACE("(%p)->(%x,%p,%p,%p)\n", This, Flags, DDSD, Context, Callback);
2602
2603     if(!Callback)
2604         return DDERR_INVALIDPARAMS;
2605
2606     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
2607     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
2608     {
2609         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
2610         if (all || (nomatch != IDirectDrawImpl_DDSD_Match(DDSD, &surf->surface_desc)))
2611         {
2612             desc = surf->surface_desc;
2613             IDirectDrawSurface7_AddRef(ICOM_INTERFACE(surf, IDirectDrawSurface7));
2614             if(Callback( ICOM_INTERFACE(surf, IDirectDrawSurface7), &desc, Context) != DDENUMRET_OK)
2615                 return DD_OK;
2616         }
2617     }
2618     return DD_OK;
2619 }
2620
2621 /*****************************************************************************
2622  * D3D7CB_CreateRenderTarget
2623  *
2624  * Callback called by WineD3D to create Surfaces for render target usage
2625  * This function takes the D3D target from the IDirectDrawImpl structure,
2626  * and returns the WineD3DSurface. To avoid double usage, the surface
2627  * is marked as render target afterwards
2628  *
2629  * Params
2630  *  device: The WineD3DDevice's parent
2631  *  Width, Height, Format: Dimensions and pixelformat of the render target
2632  *                         Ignored, because the surface already exists
2633  *  MultiSample, MultisampleQuality, Lockable: Ignored for the same reason
2634  *  Lockable: ignored
2635  *  ppSurface: Address to pass the surface pointer back at
2636  *  pSharedHandle: Ignored
2637  *
2638  * Returns:
2639  *  Always returns D3D_OK
2640  *
2641  *****************************************************************************/
2642 static HRESULT WINAPI
2643 D3D7CB_CreateRenderTarget(IUnknown *device, UINT Width, UINT Height,
2644                           WINED3DFORMAT Format,
2645                           WINED3DMULTISAMPLE_TYPE MultiSample,
2646                           DWORD MultisampleQuality,
2647                           BOOL Lockable,
2648                           IWineD3DSurface** ppSurface,
2649                           HANDLE* pSharedHandle)
2650 {
2651     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
2652     IDirectDrawSurfaceImpl *d3dSurface = (IDirectDrawSurfaceImpl *) This->d3d_target->first_complex;
2653     TRACE("(%p) call back\n", device);
2654
2655     /* Loop through the complex chain and try to find unused primary surfaces */
2656     while(d3dSurface->isRenderTarget)
2657     {
2658         d3dSurface = d3dSurface->next_complex;
2659         if(!d3dSurface) break;
2660     }
2661     if(!d3dSurface)
2662     {
2663         d3dSurface = This->d3d_target;
2664         ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", This);
2665     }
2666
2667     /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */
2668
2669     *ppSurface = d3dSurface->WineD3DSurface;
2670     d3dSurface->isRenderTarget = TRUE;
2671     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *ppSurface, d3dSurface);
2672     return D3D_OK;
2673 }
2674
2675 static HRESULT WINAPI
2676 D3D7CB_CreateDepthStencilSurface(IUnknown *device,
2677                                  UINT Width,
2678                                  UINT Height,
2679                                  WINED3DFORMAT Format,
2680                                  WINED3DMULTISAMPLE_TYPE MultiSample,
2681                                  DWORD MultisampleQuality,
2682                                  BOOL Discard,
2683                                  IWineD3DSurface** ppSurface,
2684                                  HANDLE* pSharedHandle)
2685 {
2686     /* Create a Depth Stencil surface to make WineD3D happy */
2687     HRESULT hr = D3D_OK;
2688     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
2689     DDSURFACEDESC2 ddsd;
2690
2691     TRACE("(%p) call back\n", device);
2692
2693     *ppSurface = NULL;
2694
2695     /* Create a DirectDraw surface */
2696     memset(&ddsd, 0, sizeof(ddsd));
2697     ddsd.dwSize = sizeof(ddsd);
2698     ddsd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2699     ddsd.dwFlags = DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
2700     ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
2701     ddsd.dwHeight = Height;
2702     ddsd.dwWidth = Width;
2703     if(Format != 0)
2704     {
2705       PixelFormat_WineD3DtoDD(&ddsd.u4.ddpfPixelFormat, Format);
2706     }
2707     else
2708     {
2709       ddsd.dwFlags ^= DDSD_PIXELFORMAT;
2710     }
2711
2712     This->depthstencil = TRUE;
2713     hr = IDirectDraw7_CreateSurface((IDirectDraw7 *) This,
2714                                     &ddsd,
2715                                     (IDirectDrawSurface7 **) &This->DepthStencilBuffer,
2716                                     NULL);
2717     This->depthstencil = FALSE;
2718     if(FAILED(hr))
2719     {
2720         ERR(" (%p) Creating a DepthStencil Surface failed, result = %x\n", This, hr);
2721         return hr;
2722     }
2723     *ppSurface = This->DepthStencilBuffer->WineD3DSurface;
2724     return D3D_OK;
2725 }
2726
2727 /*****************************************************************************
2728  * D3D7CB_CreateAdditionalSwapChain
2729  *
2730  * Callback function for WineD3D which creates a new WineD3DSwapchain
2731  * interface. It also creates an IParent interface to store that pointer,
2732  * so the WineD3DSwapchain has a parent and can be released when the D3D
2733  * device is destroyed
2734  *****************************************************************************/
2735 static HRESULT WINAPI
2736 D3D7CB_CreateAdditionalSwapChain(IUnknown *device,
2737                                  WINED3DPRESENT_PARAMETERS* pPresentationParameters,
2738                                  IWineD3DSwapChain ** ppSwapChain)
2739 {
2740     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, device);
2741     IParentImpl *object = NULL;
2742     HRESULT res = D3D_OK;
2743     IWineD3DSwapChain *swapchain;
2744     TRACE("(%p) call back\n", device);
2745
2746     object = HeapAlloc(GetProcessHeap(),  HEAP_ZERO_MEMORY, sizeof(IParentImpl));
2747     if (NULL == object)
2748     {
2749         FIXME("Allocation of memory failed\n");
2750         *ppSwapChain = NULL;
2751         return DDERR_OUTOFVIDEOMEMORY;
2752     }
2753
2754     ICOM_INIT_INTERFACE(object, IParent, IParent_Vtbl);
2755     object->ref = 1;
2756
2757     res = IWineD3DDevice_CreateAdditionalSwapChain(This->wineD3DDevice,
2758                                                    pPresentationParameters, 
2759                                                    &swapchain, 
2760                                                    (IUnknown*) ICOM_INTERFACE(object, IParent),
2761                                                    D3D7CB_CreateRenderTarget,
2762                                                    D3D7CB_CreateDepthStencilSurface);
2763     if (res != D3D_OK)
2764     {
2765         FIXME("(%p) call to IWineD3DDevice_CreateAdditionalSwapChain failed\n", This);
2766         HeapFree(GetProcessHeap(), 0 , object);
2767         *ppSwapChain = NULL;
2768     }
2769     else
2770     {
2771         *ppSwapChain = swapchain;
2772         object->child = (IUnknown *) swapchain;
2773     }
2774
2775     return res;
2776 }
2777
2778 /*****************************************************************************
2779  * IDirectDrawImpl_AttachD3DDevice
2780  *
2781  * Initializes the D3D capabilities of WineD3D
2782  *
2783  * Params:
2784  *  primary: The primary surface for D3D
2785  *
2786  * Returns
2787  *  DD_OK on success,
2788  *  DDERR_* otherwise
2789  *
2790  *****************************************************************************/
2791 static HRESULT WINAPI
2792 IDirectDrawImpl_AttachD3DDevice(IDirectDrawImpl *This,
2793                                 IDirectDrawSurfaceImpl *primary)
2794 {
2795     HRESULT hr;
2796     UINT                  BackBufferCount = 0;
2797     HWND                  window;
2798
2799     WINED3DPRESENT_PARAMETERS localParameters;
2800     BOOL isWindowed, EnableAutoDepthStencil;
2801     WINED3DFORMAT AutoDepthStencilFormat;
2802     WINED3DMULTISAMPLE_TYPE MultiSampleType;
2803     WINED3DSWAPEFFECT  SwapEffect;
2804     DWORD Flags, MultiSampleQuality;
2805     UINT FullScreen_RefreshRateInHz, PresentationInterval;
2806     WINED3DDISPLAYMODE Mode;
2807
2808     TRACE("(%p)->(%p)\n", This, primary);
2809
2810     /* Get the window */
2811     hr = IWineD3DDevice_GetHWND(This->wineD3DDevice,
2812                                 &window);
2813     if(hr != D3D_OK)
2814     {
2815         ERR("IWineD3DDevice::GetHWND failed\n");
2816         return hr;
2817     }
2818
2819     /* If there's no window, create a hidden window. WineD3D needs it */
2820     if(window == 0)
2821     {
2822         window = CreateWindowExA(0, This->classname, "Hidden D3D Window",
2823                                  WS_DISABLED, 0, 0,
2824                                  GetSystemMetrics(SM_CXSCREEN),
2825                                  GetSystemMetrics(SM_CYSCREEN),
2826                                  NULL, NULL, GetModuleHandleA(0), NULL);
2827
2828         ShowWindow(window, SW_HIDE);   /* Just to be sure */
2829         WARN("(%p) No window for the Direct3DDevice, created a hidden window. HWND=%p\n", This, window);
2830         This->d3d_window = window;
2831     }
2832     else
2833     {
2834         TRACE("(%p) Using existing window %p for Direct3D rendering\n", This, window);
2835     }
2836
2837     /* use the surface description for the device parameters, not the
2838      * Device settings. The app might render to an offscreen surface
2839      */
2840     Mode.Width = primary->surface_desc.dwWidth;
2841     Mode.Height = primary->surface_desc.dwHeight;
2842     Mode.Format = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2843
2844     if(primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2845     {
2846         BackBufferCount = primary->surface_desc.dwBackBufferCount;
2847     }
2848
2849     /* Store the future Render Target surface */
2850     This->d3d_target = primary;
2851
2852     isWindowed = !(This->cooperative_level & DDSCL_FULLSCREEN);
2853     EnableAutoDepthStencil = FALSE;
2854     AutoDepthStencilFormat = WINED3DFMT_D16;
2855     MultiSampleType = WINED3DMULTISAMPLE_NONE;
2856     SwapEffect = WINED3DSWAPEFFECT_COPY;
2857     Flags = 0;
2858     MultiSampleQuality = 0;
2859     FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT; /* Default rate: It's already set */
2860     PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2861
2862     TRACE("Passing mode %d\n", Mode.Format);
2863
2864     localParameters.BackBufferWidth                = &Mode.Width;
2865     localParameters.BackBufferHeight               = &Mode.Height;
2866     localParameters.BackBufferFormat               = (WINED3DFORMAT *) &Mode.Format;
2867     localParameters.BackBufferCount                = (UINT *) &BackBufferCount;
2868     localParameters.MultiSampleType                = &MultiSampleType;
2869     localParameters.MultiSampleQuality             = &MultiSampleQuality;
2870     localParameters.SwapEffect                     = &SwapEffect;
2871     localParameters.hDeviceWindow                  = &window;
2872     localParameters.Windowed                       = &isWindowed;
2873     localParameters.EnableAutoDepthStencil         = &EnableAutoDepthStencil;
2874     localParameters.AutoDepthStencilFormat         = &AutoDepthStencilFormat;
2875     localParameters.Flags                          = &Flags;
2876     localParameters.FullScreen_RefreshRateInHz     = &FullScreen_RefreshRateInHz;
2877     localParameters.PresentationInterval           = &PresentationInterval;
2878
2879     /* Set this NOW, otherwise creating the depth stencil surface will cause a
2880      * recursive loop until ram or emulated video memory is full
2881      */
2882     This->d3d_initialized = TRUE;
2883
2884     hr = IWineD3DDevice_Init3D(This->wineD3DDevice,
2885                                &localParameters,
2886                                D3D7CB_CreateAdditionalSwapChain);
2887     if(FAILED(hr))
2888     {
2889         This->wineD3DDevice = NULL;
2890         return hr;
2891     }
2892
2893     /* Create an Index Buffer parent */
2894     TRACE("(%p) Successfully initialized 3D\n", This);
2895     return DD_OK;
2896 }
2897
2898 /*****************************************************************************
2899  * DirectDrawCreateClipper (DDRAW.@)
2900  *
2901  * Creates a new IDirectDrawClipper object.
2902  *
2903  * Params:
2904  *  Clipper: Address to write the interface pointer to
2905  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
2906  *            NULL
2907  *
2908  * Returns:
2909  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2910  *  E_OUTOFMEMORY if allocating the object failed
2911  *
2912  *****************************************************************************/
2913 HRESULT WINAPI
2914 DirectDrawCreateClipper(DWORD Flags,
2915                         IDirectDrawClipper **Clipper,
2916                         IUnknown *UnkOuter)
2917 {
2918     IDirectDrawClipperImpl* object;
2919     TRACE("(%08x,%p,%p)\n", Flags, Clipper, UnkOuter);
2920
2921     if (UnkOuter != NULL) return CLASS_E_NOAGGREGATION;
2922
2923     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2924                      sizeof(IDirectDrawClipperImpl));
2925     if (object == NULL) return E_OUTOFMEMORY;
2926
2927     ICOM_INIT_INTERFACE(object, IDirectDrawClipper, IDirectDrawClipper_Vtbl);
2928     object->ref = 1;
2929     object->hWnd = 0;
2930     object->ddraw_owner = NULL;
2931
2932     *Clipper = (IDirectDrawClipper *) object;
2933     return DD_OK;
2934 }
2935
2936 /*****************************************************************************
2937  * IDirectDraw7::CreateClipper
2938  *
2939  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
2940  *
2941  *****************************************************************************/
2942 static HRESULT WINAPI
2943 IDirectDrawImpl_CreateClipper(IDirectDraw7 *iface,
2944                               DWORD Flags,
2945                               IDirectDrawClipper **Clipper,
2946                               IUnknown *UnkOuter)
2947 {
2948     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
2949     TRACE("(%p)->(%x,%p,%p)\n", This, Flags, Clipper, UnkOuter);
2950     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
2951 }
2952
2953 /*****************************************************************************
2954  * IDirectDraw7::CreatePalette
2955  *
2956  * Creates a new IDirectDrawPalette object
2957  *
2958  * Params:
2959  *  Flags: The flags for the new clipper
2960  *  ColorTable: Color table to assign to the new clipper
2961  *  Palette: Address to write the interface pointer to
2962  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
2963  *            NULL
2964  *
2965  * Returns:
2966  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2967  *  E_OUTOFMEMORY if allocating the object failed
2968  *
2969  *****************************************************************************/
2970 static HRESULT WINAPI
2971 IDirectDrawImpl_CreatePalette(IDirectDraw7 *iface,
2972                               DWORD Flags,
2973                               PALETTEENTRY *ColorTable,
2974                               IDirectDrawPalette **Palette,
2975                               IUnknown *pUnkOuter)
2976 {
2977     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
2978     IDirectDrawPaletteImpl *object;
2979     HRESULT hr = DDERR_GENERIC;
2980     TRACE("(%p)->(%x,%p,%p,%p)\n", This, Flags, ColorTable, Palette, pUnkOuter);
2981
2982     if(pUnkOuter != NULL)
2983     {
2984         WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
2985         return CLASS_E_NOAGGREGATION;
2986     }
2987
2988     /* The refcount test shows that a cooplevel is required for this */
2989     if(!This->cooperative_level)
2990     {
2991         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
2992         return DDERR_NOCOOPERATIVELEVELSET;
2993     }
2994
2995     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
2996     if(!object)
2997     {
2998         ERR("Out of memory when allocating memory for a palette implementation\n");
2999         return E_OUTOFMEMORY;
3000     }
3001
3002     ICOM_INIT_INTERFACE(object, IDirectDrawPalette, IDirectDrawPalette_Vtbl);
3003     object->ref = 1;
3004     object->ddraw_owner = This;
3005
3006     hr = IWineD3DDevice_CreatePalette(This->wineD3DDevice, Flags, ColorTable, &object->wineD3DPalette, (IUnknown *) ICOM_INTERFACE(object, IDirectDrawPalette) );
3007     if(hr != DD_OK)
3008     {
3009         HeapFree(GetProcessHeap(), 0, object);
3010         return hr;
3011     }
3012
3013     IDirectDraw7_AddRef(iface);
3014     object->ifaceToRelease = (IUnknown *) iface;
3015     *Palette = ICOM_INTERFACE(object, IDirectDrawPalette);
3016     return DD_OK;
3017 }
3018
3019 /*****************************************************************************
3020  * IDirectDraw7::DuplicateSurface
3021  *
3022  * Duplicates a surface. The surface memory points to the same memory as
3023  * the original surface, and it's released when the last surface referencing
3024  * it is released. I guess that's beyond Wine's surface management right now
3025  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
3026  * test application to implement this)
3027  *
3028  * Params:
3029  *  Src: Address of the source surface
3030  *  Dest: Address to write the new surface pointer to
3031  *
3032  * Returns:
3033  *  See IDirectDraw7::CreateSurface
3034  *
3035  *****************************************************************************/
3036 static HRESULT WINAPI
3037 IDirectDrawImpl_DuplicateSurface(IDirectDraw7 *iface,
3038                                  IDirectDrawSurface7 *Src,
3039                                  IDirectDrawSurface7 **Dest)
3040 {
3041     ICOM_THIS_FROM(IDirectDrawImpl, IDirectDraw7, iface);
3042     IDirectDrawSurfaceImpl *Surf = ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, Src);
3043
3044     FIXME("(%p)->(%p,%p)\n", This, Surf, Dest);
3045
3046     /* For now, simply create a new, independent surface */
3047     return IDirectDraw7_CreateSurface(iface,
3048                                       &Surf->surface_desc,
3049                                       Dest,
3050                                       NULL);
3051 }
3052
3053 /*****************************************************************************
3054  * IDirectDraw7 VTable
3055  *****************************************************************************/
3056 const IDirectDraw7Vtbl IDirectDraw7_Vtbl =
3057 {
3058     /*** IUnknown ***/
3059     IDirectDrawImpl_QueryInterface,
3060     IDirectDrawImpl_AddRef,
3061     IDirectDrawImpl_Release,
3062     /*** IDirectDraw ***/
3063     IDirectDrawImpl_Compact,
3064     IDirectDrawImpl_CreateClipper,
3065     IDirectDrawImpl_CreatePalette,
3066     IDirectDrawImpl_CreateSurface,
3067     IDirectDrawImpl_DuplicateSurface,
3068     IDirectDrawImpl_EnumDisplayModes,
3069     IDirectDrawImpl_EnumSurfaces,
3070     IDirectDrawImpl_FlipToGDISurface,
3071     IDirectDrawImpl_GetCaps,
3072     IDirectDrawImpl_GetDisplayMode,
3073     IDirectDrawImpl_GetFourCCCodes,
3074     IDirectDrawImpl_GetGDISurface,
3075     IDirectDrawImpl_GetMonitorFrequency,
3076     IDirectDrawImpl_GetScanLine,
3077     IDirectDrawImpl_GetVerticalBlankStatus,
3078     IDirectDrawImpl_Initialize,
3079     IDirectDrawImpl_RestoreDisplayMode,
3080     IDirectDrawImpl_SetCooperativeLevel,
3081     IDirectDrawImpl_SetDisplayMode,
3082     IDirectDrawImpl_WaitForVerticalBlank,
3083     /*** IDirectDraw2 ***/
3084     IDirectDrawImpl_GetAvailableVidMem,
3085     /*** IDirectDraw7 ***/
3086     IDirectDrawImpl_GetSurfaceFromDC,
3087     IDirectDrawImpl_RestoreAllSurfaces,
3088     IDirectDrawImpl_TestCooperativeLevel,
3089     IDirectDrawImpl_GetDeviceIdentifier,
3090     /*** IDirectDraw7 ***/
3091     IDirectDrawImpl_StartModeTest,
3092     IDirectDrawImpl_EvaluateMode
3093 };