usp10: Correct lookahead offset in Coverage-based Chaining Context Glyph Substitution.
[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  * Copyright 2008 Denver Gingerich
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include "ddraw_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
29
30 /* Device identifier. Don't relay it to WineD3D */
31 static const DDDEVICEIDENTIFIER2 deviceidentifier =
32 {
33     "display",
34     "DirectDraw HAL",
35     { { 0x00010001, 0x00010001 } },
36     0, 0, 0, 0,
37     /* a8373c10-7ac4-4deb-849a-009844d08b2d */
38     {0xa8373c10,0x7ac4,0x4deb, {0x84,0x9a,0x00,0x98,0x44,0xd0,0x8b,0x2d}},
39     0
40 };
41
42 static void STDMETHODCALLTYPE ddraw_null_wined3d_object_destroyed(void *parent) {}
43
44 const struct wined3d_parent_ops ddraw_null_wined3d_parent_ops =
45 {
46     ddraw_null_wined3d_object_destroyed,
47 };
48
49 static inline IDirectDrawImpl *impl_from_IDirectDraw(IDirectDraw *iface)
50 {
51     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw_iface);
52 }
53
54 static inline IDirectDrawImpl *impl_from_IDirectDraw2(IDirectDraw2 *iface)
55 {
56     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw2_iface);
57 }
58
59 static inline IDirectDrawImpl *impl_from_IDirectDraw3(IDirectDraw3 *iface)
60 {
61     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw3_iface);
62 }
63
64 static inline IDirectDrawImpl *impl_from_IDirectDraw4(IDirectDraw4 *iface)
65 {
66     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw4_iface);
67 }
68
69 static inline IDirectDrawImpl *impl_from_IDirectDraw7(IDirectDraw7 *iface)
70 {
71     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw7_iface);
72 }
73
74 static inline IDirectDrawImpl *impl_from_IDirect3D(IDirect3D *iface)
75 {
76     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D_iface);
77 }
78
79 static inline IDirectDrawImpl *impl_from_IDirect3D2(IDirect3D2 *iface)
80 {
81     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D2_iface);
82 }
83
84 static inline IDirectDrawImpl *impl_from_IDirect3D3(IDirect3D3 *iface)
85 {
86     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D3_iface);
87 }
88
89 static inline IDirectDrawImpl *impl_from_IDirect3D7(IDirect3D7 *iface)
90 {
91     return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D7_iface);
92 }
93
94 /*****************************************************************************
95  * IUnknown Methods
96  *****************************************************************************/
97
98 /*****************************************************************************
99  * IDirectDraw7::QueryInterface
100  *
101  * Queries different interfaces of the DirectDraw object. It can return
102  * IDirectDraw interfaces in version 1, 2, 4 and 7, and IDirect3D interfaces
103  * in version 1, 2, 3 and 7. An IDirect3DDevice can be created with this
104  * method.
105  * The returned interface is AddRef()-ed before it's returned
106  *
107  * Used for version 1, 2, 4 and 7
108  *
109  * Params:
110  *  refiid: Interface ID asked for
111  *  obj: Used to return the interface pointer
112  *
113  * Returns:
114  *  S_OK if an interface was found
115  *  E_NOINTERFACE if the requested interface wasn't found
116  *
117  *****************************************************************************/
118 static HRESULT WINAPI ddraw7_QueryInterface(IDirectDraw7 *iface, REFIID refiid, void **obj)
119 {
120     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
121
122     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(refiid), obj);
123
124     /* Can change surface impl type */
125     EnterCriticalSection(&ddraw_cs);
126
127     /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
128     *obj = NULL;
129
130     if(!refiid)
131     {
132         LeaveCriticalSection(&ddraw_cs);
133         return DDERR_INVALIDPARAMS;
134     }
135
136     /* Check DirectDraw Interfaces */
137     if ( IsEqualGUID( &IID_IUnknown, refiid ) ||
138          IsEqualGUID( &IID_IDirectDraw7, refiid ) )
139     {
140         *obj = This;
141         TRACE("(%p) Returning IDirectDraw7 interface at %p\n", This, *obj);
142     }
143     else if ( IsEqualGUID( &IID_IDirectDraw4, refiid ) )
144     {
145         *obj = &This->IDirectDraw4_iface;
146         TRACE("(%p) Returning IDirectDraw4 interface at %p\n", This, *obj);
147     }
148     else if ( IsEqualGUID( &IID_IDirectDraw3, refiid ) )
149     {
150         /* This Interface exists in ddrawex.dll, it is implemented in a wrapper */
151         WARN("IDirectDraw3 is not valid in ddraw.dll\n");
152         *obj = NULL;
153         LeaveCriticalSection(&ddraw_cs);
154         return E_NOINTERFACE;
155     }
156     else if ( IsEqualGUID( &IID_IDirectDraw2, refiid ) )
157     {
158         *obj = &This->IDirectDraw2_iface;
159         TRACE("(%p) Returning IDirectDraw2 interface at %p\n", This, *obj);
160     }
161     else if ( IsEqualGUID( &IID_IDirectDraw, refiid ) )
162     {
163         *obj = &This->IDirectDraw_iface;
164         TRACE("(%p) Returning IDirectDraw interface at %p\n", This, *obj);
165     }
166
167     /* Direct3D
168      * The refcount unit test revealed that an IDirect3D7 interface can only be queried
169      * from a DirectDraw object that was created as an IDirectDraw7 interface. No idea
170      * who had this idea and why. The older interfaces can query and IDirect3D version
171      * because they are all created as IDirectDraw(1). This isn't really crucial behavior,
172      * and messy to implement with the common creation function, so it has been left out here.
173      */
174     else if ( IsEqualGUID( &IID_IDirect3D  , refiid ) ||
175               IsEqualGUID( &IID_IDirect3D2 , refiid ) ||
176               IsEqualGUID( &IID_IDirect3D3 , refiid ) ||
177               IsEqualGUID( &IID_IDirect3D7 , refiid ) )
178     {
179         /* Check the surface implementation */
180         if(This->ImplType == SURFACE_UNKNOWN)
181         {
182             /* Apps may create the IDirect3D Interface before the primary surface.
183              * set the surface implementation */
184             This->ImplType = SURFACE_OPENGL;
185             TRACE("(%p) Choosing OpenGL surfaces because a Direct3D interface was requested\n", This);
186         }
187         else if(This->ImplType != SURFACE_OPENGL && DefaultSurfaceType == SURFACE_UNKNOWN)
188         {
189             ERR("(%p) The App is requesting a D3D device, but a non-OpenGL surface type was choosen. Prepare for trouble!\n", This);
190             ERR(" (%p) You may want to contact wine-devel for help\n", This);
191             /* Should I assert(0) here??? */
192         }
193         else if(This->ImplType != SURFACE_OPENGL)
194         {
195             WARN("The app requests a Direct3D interface, but non-opengl surfaces where set in winecfg\n");
196             /* Do not abort here, only reject 3D Device creation */
197         }
198
199         if ( IsEqualGUID( &IID_IDirect3D  , refiid ) )
200         {
201             This->d3dversion = 1;
202             *obj = &This->IDirect3D_iface;
203             TRACE(" returning Direct3D interface at %p.\n", *obj);
204         }
205         else if ( IsEqualGUID( &IID_IDirect3D2  , refiid ) )
206         {
207             This->d3dversion = 2;
208             *obj = &This->IDirect3D2_iface;
209             TRACE(" returning Direct3D2 interface at %p.\n", *obj);
210         }
211         else if ( IsEqualGUID( &IID_IDirect3D3  , refiid ) )
212         {
213             This->d3dversion = 3;
214             *obj = &This->IDirect3D3_iface;
215             TRACE(" returning Direct3D3 interface at %p.\n", *obj);
216         }
217         else if(IsEqualGUID( &IID_IDirect3D7  , refiid ))
218         {
219             This->d3dversion = 7;
220             *obj = &This->IDirect3D7_iface;
221             TRACE(" returning Direct3D7 interface at %p.\n", *obj);
222         }
223     }
224     /* Unknown interface */
225     else
226     {
227         ERR("(%p)->(%s, %p): No interface found\n", This, debugstr_guid(refiid), obj);
228         LeaveCriticalSection(&ddraw_cs);
229         return E_NOINTERFACE;
230     }
231
232     IUnknown_AddRef( (IUnknown *) *obj );
233     LeaveCriticalSection(&ddraw_cs);
234     return S_OK;
235 }
236
237 static HRESULT WINAPI ddraw4_QueryInterface(IDirectDraw4 *iface, REFIID riid, void **object)
238 {
239     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
240
241     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
242
243     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
244 }
245
246 static HRESULT WINAPI ddraw3_QueryInterface(IDirectDraw3 *iface, REFIID riid, void **object)
247 {
248     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
249
250     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
251
252     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
253 }
254
255 static HRESULT WINAPI ddraw2_QueryInterface(IDirectDraw2 *iface, REFIID riid, void **object)
256 {
257     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
258
259     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
260
261     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
262 }
263
264 static HRESULT WINAPI ddraw1_QueryInterface(IDirectDraw *iface, REFIID riid, void **object)
265 {
266     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
267
268     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
269
270     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
271 }
272
273 static HRESULT WINAPI d3d7_QueryInterface(IDirect3D7 *iface, REFIID riid, void **object)
274 {
275     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
276
277     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
278
279     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
280 }
281
282 static HRESULT WINAPI d3d3_QueryInterface(IDirect3D3 *iface, REFIID riid, void **object)
283 {
284     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
285
286     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
287
288     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
289 }
290
291 static HRESULT WINAPI d3d2_QueryInterface(IDirect3D2 *iface, REFIID riid, void **object)
292 {
293     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
294
295     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
296
297     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
298 }
299
300 static HRESULT WINAPI d3d1_QueryInterface(IDirect3D *iface, REFIID riid, void **object)
301 {
302     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
303
304     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
305
306     return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
307 }
308
309 /*****************************************************************************
310  * IDirectDraw7::AddRef
311  *
312  * Increases the interfaces refcount, basically
313  *
314  * DDraw refcounting is a bit tricky. The different DirectDraw interface
315  * versions have individual refcounts, but the IDirect3D interfaces do not.
316  * All interfaces are from one object, that means calling QueryInterface on an
317  * IDirectDraw7 interface for an IDirectDraw4 interface does not create a new
318  * IDirectDrawImpl object.
319  *
320  * That means all AddRef and Release implementations of IDirectDrawX work
321  * with their own counter, and IDirect3DX::AddRef thunk to IDirectDraw (1),
322  * except of IDirect3D7 which thunks to IDirectDraw7
323  *
324  * Returns: The new refcount
325  *
326  *****************************************************************************/
327 static ULONG WINAPI ddraw7_AddRef(IDirectDraw7 *iface)
328 {
329     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
330     ULONG ref = InterlockedIncrement(&This->ref7);
331
332     TRACE("%p increasing refcount to %u.\n", This, ref);
333
334     if(ref == 1) InterlockedIncrement(&This->numIfaces);
335
336     return ref;
337 }
338
339 static ULONG WINAPI ddraw4_AddRef(IDirectDraw4 *iface)
340 {
341     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
342     ULONG ref = InterlockedIncrement(&This->ref4);
343
344     TRACE("%p increasing refcount to %u.\n", This, ref);
345
346     if (ref == 1) InterlockedIncrement(&This->numIfaces);
347
348     return ref;
349 }
350
351 static ULONG WINAPI ddraw3_AddRef(IDirectDraw3 *iface)
352 {
353     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
354     ULONG ref = InterlockedIncrement(&This->ref3);
355
356     TRACE("%p increasing refcount to %u.\n", This, ref);
357
358     if (ref == 1) InterlockedIncrement(&This->numIfaces);
359
360     return ref;
361 }
362
363 static ULONG WINAPI ddraw2_AddRef(IDirectDraw2 *iface)
364 {
365     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
366     ULONG ref = InterlockedIncrement(&This->ref2);
367
368     TRACE("%p increasing refcount to %u.\n", This, ref);
369
370     if (ref == 1) InterlockedIncrement(&This->numIfaces);
371
372     return ref;
373 }
374
375 static ULONG WINAPI ddraw1_AddRef(IDirectDraw *iface)
376 {
377     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
378     ULONG ref = InterlockedIncrement(&This->ref1);
379
380     TRACE("%p increasing refcount to %u.\n", This, ref);
381
382     if (ref == 1) InterlockedIncrement(&This->numIfaces);
383
384     return ref;
385 }
386
387 static ULONG WINAPI d3d7_AddRef(IDirect3D7 *iface)
388 {
389     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
390
391     TRACE("iface %p.\n", iface);
392
393     return ddraw7_AddRef(&This->IDirectDraw7_iface);
394 }
395
396 static ULONG WINAPI d3d3_AddRef(IDirect3D3 *iface)
397 {
398     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
399
400     TRACE("iface %p.\n", iface);
401
402     return ddraw1_AddRef(&This->IDirectDraw_iface);
403 }
404
405 static ULONG WINAPI d3d2_AddRef(IDirect3D2 *iface)
406 {
407     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
408
409     TRACE("iface %p.\n", iface);
410
411     return ddraw1_AddRef(&This->IDirectDraw_iface);
412 }
413
414 static ULONG WINAPI d3d1_AddRef(IDirect3D *iface)
415 {
416     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
417
418     TRACE("iface %p.\n", iface);
419
420     return ddraw1_AddRef(&This->IDirectDraw_iface);
421 }
422
423 /*****************************************************************************
424  * ddraw_destroy
425  *
426  * Destroys a ddraw object if all refcounts are 0. This is to share code
427  * between the IDirectDrawX::Release functions
428  *
429  * Params:
430  *  This: DirectDraw object to destroy
431  *
432  *****************************************************************************/
433 static void ddraw_destroy(IDirectDrawImpl *This)
434 {
435     IDirectDraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, NULL, DDSCL_NORMAL);
436     IDirectDraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
437
438     /* Destroy the device window if we created one */
439     if(This->devicewindow != 0)
440     {
441         TRACE(" (%p) Destroying the device window %p\n", This, This->devicewindow);
442         DestroyWindow(This->devicewindow);
443         This->devicewindow = 0;
444     }
445
446     EnterCriticalSection(&ddraw_cs);
447     list_remove(&This->ddraw_list_entry);
448     LeaveCriticalSection(&ddraw_cs);
449
450     /* Release the attached WineD3D stuff */
451     wined3d_device_decref(This->wined3d_device);
452     wined3d_decref(This->wineD3D);
453
454     /* Now free the object */
455     HeapFree(GetProcessHeap(), 0, This);
456 }
457
458 /*****************************************************************************
459  * IDirectDraw7::Release
460  *
461  * Decreases the refcount. If the refcount falls to 0, the object is destroyed
462  *
463  * Returns: The new refcount
464  *****************************************************************************/
465 static ULONG WINAPI ddraw7_Release(IDirectDraw7 *iface)
466 {
467     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
468     ULONG ref = InterlockedDecrement(&This->ref7);
469
470     TRACE("%p decreasing refcount to %u.\n", This, ref);
471
472     if (!ref && !InterlockedDecrement(&This->numIfaces))
473         ddraw_destroy(This);
474
475     return ref;
476 }
477
478 static ULONG WINAPI ddraw4_Release(IDirectDraw4 *iface)
479 {
480     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
481     ULONG ref = InterlockedDecrement(&This->ref4);
482
483     TRACE("%p decreasing refcount to %u.\n", This, ref);
484
485     if (!ref && !InterlockedDecrement(&This->numIfaces))
486         ddraw_destroy(This);
487
488     return ref;
489 }
490
491 static ULONG WINAPI ddraw3_Release(IDirectDraw3 *iface)
492 {
493     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
494     ULONG ref = InterlockedDecrement(&This->ref3);
495
496     TRACE("%p decreasing refcount to %u.\n", This, ref);
497
498     if (!ref && !InterlockedDecrement(&This->numIfaces))
499         ddraw_destroy(This);
500
501     return ref;
502 }
503
504 static ULONG WINAPI ddraw2_Release(IDirectDraw2 *iface)
505 {
506     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
507     ULONG ref = InterlockedDecrement(&This->ref2);
508
509     TRACE("%p decreasing refcount to %u.\n", This, ref);
510
511     if (!ref && !InterlockedDecrement(&This->numIfaces))
512         ddraw_destroy(This);
513
514     return ref;
515 }
516
517 static ULONG WINAPI ddraw1_Release(IDirectDraw *iface)
518 {
519     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
520     ULONG ref = InterlockedDecrement(&This->ref1);
521
522     TRACE("%p decreasing refcount to %u.\n", This, ref);
523
524     if (!ref && !InterlockedDecrement(&This->numIfaces))
525         ddraw_destroy(This);
526
527     return ref;
528 }
529
530 static ULONG WINAPI d3d7_Release(IDirect3D7 *iface)
531 {
532     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
533
534     TRACE("iface %p.\n", iface);
535
536     return ddraw7_Release(&This->IDirectDraw7_iface);
537 }
538
539 static ULONG WINAPI d3d3_Release(IDirect3D3 *iface)
540 {
541     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
542
543     TRACE("iface %p.\n", iface);
544
545     return ddraw1_Release(&This->IDirectDraw_iface);
546 }
547
548 static ULONG WINAPI d3d2_Release(IDirect3D2 *iface)
549 {
550     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
551
552     TRACE("iface %p.\n", iface);
553
554     return ddraw1_Release(&This->IDirectDraw_iface);
555 }
556
557 static ULONG WINAPI d3d1_Release(IDirect3D *iface)
558 {
559     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
560
561     TRACE("iface %p.\n", iface);
562
563     return ddraw1_Release(&This->IDirectDraw_iface);
564 }
565
566 /*****************************************************************************
567  * IDirectDraw methods
568  *****************************************************************************/
569
570 /*****************************************************************************
571  * IDirectDraw7::SetCooperativeLevel
572  *
573  * Sets the cooperative level for the DirectDraw object, and the window
574  * assigned to it. The cooperative level determines the general behavior
575  * of the DirectDraw application
576  *
577  * Warning: This is quite tricky, as it's not really documented which
578  * cooperative levels can be combined with each other. If a game fails
579  * after this function, try to check the cooperative levels passed on
580  * Windows, and if it returns something different.
581  *
582  * If you think that this function caused the failure because it writes a
583  * fixme, be sure to run again with a +ddraw trace.
584  *
585  * What is known about cooperative levels (See the ddraw modes test):
586  * DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN must be used with each other
587  * DDSCL_NORMAL is not compatible with DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN
588  * DDSCL_SETFOCUSWINDOW can be passed only in DDSCL_NORMAL mode, but after that
589  * DDSCL_FULLSCREEN can be activated
590  * DDSCL_SETFOCUSWINDOW may only be used with DDSCL_NOWINDOWCHANGES
591  *
592  * Handled flags: DDSCL_NORMAL, DDSCL_FULLSCREEN, DDSCL_EXCLUSIVE,
593  *                DDSCL_SETFOCUSWINDOW (partially),
594  *                DDSCL_MULTITHREADED (work in progress)
595  *
596  * Unhandled flags, which should be implemented
597  *  DDSCL_SETDEVICEWINDOW: Sets a window specially used for rendering (I don't
598  *  expect any difference to a normal window for wine)
599  *  DDSCL_CREATEDEVICEWINDOW: Tells ddraw to create its own window for
600  *  rendering (Possible test case: Half-Life)
601  *
602  * Unsure about these: DDSCL_FPUSETUP DDSCL_FPURESERVE
603  *
604  * These don't seem very important for wine:
605  *  DDSCL_ALLOWREBOOT, DDSCL_NOWINDOWCHANGES, DDSCL_ALLOWMODEX
606  *
607  * Returns:
608  *  DD_OK if the cooperative level was set successfully
609  *  DDERR_INVALIDPARAMS if the passed cooperative level combination is invalid
610  *  DDERR_HWNDALREADYSET if DDSCL_SETFOCUSWINDOW is passed in exclusive mode
611  *   (Probably others too, have to investigate)
612  *
613  *****************************************************************************/
614 static HRESULT WINAPI ddraw7_SetCooperativeLevel(IDirectDraw7 *iface, HWND hwnd, DWORD cooplevel)
615 {
616     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
617     HWND window;
618
619     TRACE("iface %p, window %p, flags %#x.\n", iface, hwnd, cooplevel);
620     DDRAW_dump_cooperativelevel(cooplevel);
621
622     EnterCriticalSection(&ddraw_cs);
623
624     /* Get the old window */
625     window = This->dest_window;
626
627     /* Tests suggest that we need one of them: */
628     if(!(cooplevel & (DDSCL_SETFOCUSWINDOW |
629                       DDSCL_NORMAL         |
630                       DDSCL_EXCLUSIVE      )))
631     {
632         TRACE("Incorrect cooplevel flags, returning DDERR_INVALIDPARAMS\n");
633         LeaveCriticalSection(&ddraw_cs);
634         return DDERR_INVALIDPARAMS;
635     }
636
637     /* Handle those levels first which set various hwnds */
638     if(cooplevel & DDSCL_SETFOCUSWINDOW)
639     {
640         /* This isn't compatible with a lot of flags */
641         if(cooplevel & ( DDSCL_MULTITHREADED      |
642                          DDSCL_CREATEDEVICEWINDOW |
643                          DDSCL_FPUSETUP           |
644                          DDSCL_FPUPRESERVE        |
645                          DDSCL_ALLOWREBOOT        |
646                          DDSCL_ALLOWMODEX         |
647                          DDSCL_SETDEVICEWINDOW    |
648                          DDSCL_NORMAL             |
649                          DDSCL_EXCLUSIVE          |
650                          DDSCL_FULLSCREEN         ) )
651         {
652             TRACE("Called with incompatible flags, returning DDERR_INVALIDPARAMS\n");
653             LeaveCriticalSection(&ddraw_cs);
654             return DDERR_INVALIDPARAMS;
655         }
656
657         if( (This->cooperative_level & DDSCL_EXCLUSIVE) && window )
658         {
659             TRACE("Setting DDSCL_SETFOCUSWINDOW with an already set window, returning DDERR_HWNDALREADYSET\n");
660             LeaveCriticalSection(&ddraw_cs);
661             return DDERR_HWNDALREADYSET;
662         }
663
664         This->focuswindow = hwnd;
665         /* Won't use the hwnd param for anything else */
666         hwnd = NULL;
667
668         /* Use the focus window for drawing too */
669         This->dest_window = This->focuswindow;
670
671         /* Destroy the device window, if we have one */
672         if(This->devicewindow)
673         {
674             DestroyWindow(This->devicewindow);
675             This->devicewindow = NULL;
676         }
677
678         LeaveCriticalSection(&ddraw_cs);
679         return DD_OK;
680     }
681
682     if(cooplevel & DDSCL_EXCLUSIVE)
683     {
684         if( !(cooplevel & DDSCL_FULLSCREEN) || !hwnd )
685         {
686             TRACE("(%p) DDSCL_EXCLUSIVE needs DDSCL_FULLSCREEN and a window\n", This);
687             LeaveCriticalSection(&ddraw_cs);
688             return DDERR_INVALIDPARAMS;
689         }
690     }
691     else if( !(cooplevel & DDSCL_NORMAL) )
692     {
693         TRACE("(%p) SetCooperativeLevel needs at least SetFocusWindow or Exclusive or Normal mode\n", This);
694         LeaveCriticalSection(&ddraw_cs);
695         return DDERR_INVALIDPARAMS;
696     }
697
698     if ((This->cooperative_level & DDSCL_EXCLUSIVE)
699             && (hwnd != window || !(cooplevel & DDSCL_EXCLUSIVE)))
700         wined3d_device_release_focus_window(This->wined3d_device);
701
702     if ((cooplevel & DDSCL_FULLSCREEN) != (This->cooperative_level & DDSCL_FULLSCREEN) || hwnd != window)
703     {
704         if (This->cooperative_level & DDSCL_FULLSCREEN)
705             wined3d_device_restore_fullscreen_window(This->wined3d_device, window);
706
707         if (cooplevel & DDSCL_FULLSCREEN)
708         {
709             WINED3DDISPLAYMODE display_mode;
710
711             wined3d_get_adapter_display_mode(This->wineD3D, WINED3DADAPTER_DEFAULT, &display_mode);
712             wined3d_device_setup_fullscreen_window(This->wined3d_device, hwnd,
713                     display_mode.Width, display_mode.Height);
714         }
715     }
716
717     if ((cooplevel & DDSCL_EXCLUSIVE)
718             && (hwnd != window || !(This->cooperative_level & DDSCL_EXCLUSIVE)))
719     {
720         HRESULT hr = wined3d_device_acquire_focus_window(This->wined3d_device, hwnd);
721         if (FAILED(hr))
722         {
723             ERR("Failed to acquire focus window, hr %#x.\n", hr);
724             LeaveCriticalSection(&ddraw_cs);
725             return hr;
726         }
727     }
728
729     /* Don't override focus windows or private device windows */
730     if (hwnd && !This->focuswindow && !This->devicewindow && (hwnd != window))
731         This->dest_window = hwnd;
732
733     if(cooplevel & DDSCL_CREATEDEVICEWINDOW)
734     {
735         /* Don't create a device window if a focus window is set */
736         if( !(This->focuswindow) )
737         {
738             HWND devicewindow = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "DDraw device window",
739                     WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
740                     NULL, NULL, NULL, NULL);
741             if (!devicewindow)
742             {
743                 ERR("Failed to create window, last error %#x.\n", GetLastError());
744                 LeaveCriticalSection(&ddraw_cs);
745                 return E_FAIL;
746             }
747
748             ShowWindow(devicewindow, SW_SHOW);   /* Just to be sure */
749             TRACE("(%p) Created a DDraw device window. HWND=%p\n", This, devicewindow);
750
751             This->devicewindow = devicewindow;
752             This->dest_window = devicewindow;
753         }
754     }
755
756     if (cooplevel & DDSCL_MULTITHREADED && !(This->cooperative_level & DDSCL_MULTITHREADED))
757         wined3d_device_set_multithreaded(This->wined3d_device);
758
759     /* Unhandled flags */
760     if(cooplevel & DDSCL_ALLOWREBOOT)
761         WARN("(%p) Unhandled flag DDSCL_ALLOWREBOOT, harmless\n", This);
762     if(cooplevel & DDSCL_ALLOWMODEX)
763         WARN("(%p) Unhandled flag DDSCL_ALLOWMODEX, harmless\n", This);
764     if(cooplevel & DDSCL_FPUSETUP)
765         WARN("(%p) Unhandled flag DDSCL_FPUSETUP, harmless\n", This);
766
767     /* Store the cooperative_level */
768     This->cooperative_level = cooplevel;
769     TRACE("SetCooperativeLevel retuning DD_OK\n");
770     LeaveCriticalSection(&ddraw_cs);
771     return DD_OK;
772 }
773
774 static HRESULT WINAPI ddraw4_SetCooperativeLevel(IDirectDraw4 *iface, HWND window, DWORD flags)
775 {
776     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
777
778     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
779
780     return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
781 }
782
783 static HRESULT WINAPI ddraw3_SetCooperativeLevel(IDirectDraw3 *iface, HWND window, DWORD flags)
784 {
785     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
786
787     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
788
789     return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
790 }
791
792 static HRESULT WINAPI ddraw2_SetCooperativeLevel(IDirectDraw2 *iface, HWND window, DWORD flags)
793 {
794     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
795
796     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
797
798     return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
799 }
800
801 static HRESULT WINAPI ddraw1_SetCooperativeLevel(IDirectDraw *iface, HWND window, DWORD flags)
802 {
803     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
804
805     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
806
807     return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
808 }
809
810 /*****************************************************************************
811  *
812  * Helper function for SetDisplayMode and RestoreDisplayMode
813  *
814  * Implements DirectDraw's SetDisplayMode, but ignores the value of
815  * ForceRefreshRate, since it is already handled by
816  * ddraw7_SetDisplayMode.  RestoreDisplayMode can use this function
817  * without worrying that ForceRefreshRate will override the refresh rate.  For
818  * argument and return value documentation, see
819  * ddraw7_SetDisplayMode.
820  *
821  *****************************************************************************/
822 static HRESULT ddraw_set_display_mode(IDirectDrawImpl *ddraw, DWORD Width, DWORD Height,
823         DWORD BPP, DWORD RefreshRate, DWORD Flags)
824 {
825     enum wined3d_format_id format;
826     WINED3DDISPLAYMODE Mode;
827     HRESULT hr;
828
829     TRACE("ddraw %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n", ddraw, Width,
830             Height, BPP, RefreshRate, Flags);
831
832     EnterCriticalSection(&ddraw_cs);
833     if( !Width || !Height )
834     {
835         ERR("Width %u, Height %u, what to do?\n", Width, Height);
836         /* It looks like Need for Speed Porsche Unleashed expects DD_OK here */
837         LeaveCriticalSection(&ddraw_cs);
838         return DD_OK;
839     }
840
841     switch(BPP)
842     {
843         case 8:  format = WINED3DFMT_P8_UINT;          break;
844         case 15: format = WINED3DFMT_B5G5R5X1_UNORM;   break;
845         case 16: format = WINED3DFMT_B5G6R5_UNORM;     break;
846         case 24: format = WINED3DFMT_B8G8R8_UNORM;     break;
847         case 32: format = WINED3DFMT_B8G8R8X8_UNORM;   break;
848         default: format = WINED3DFMT_UNKNOWN;          break;
849     }
850
851     if (FAILED(hr = wined3d_device_get_display_mode(ddraw->wined3d_device, 0, &Mode)))
852     {
853         ERR("Failed to get current display mode, hr %#x.\n", hr);
854     }
855     else if (Mode.Width == Width
856             && Mode.Height == Height
857             && Mode.Format == format
858             && Mode.RefreshRate == RefreshRate)
859     {
860         TRACE("Skipping redundant mode setting call.\n");
861         LeaveCriticalSection(&ddraw_cs);
862         return DD_OK;
863     }
864
865     /* Check the exclusive mode
866     if(!(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
867         return DDERR_NOEXCLUSIVEMODE;
868      * This is WRONG. Don't know if the SDK is completely
869      * wrong and if there are any conditions when DDERR_NOEXCLUSIVE
870      * is returned, but Half-Life 1.1.1.1 (Steam version)
871      * depends on this
872      */
873
874     Mode.Width = Width;
875     Mode.Height = Height;
876     Mode.RefreshRate = RefreshRate;
877     Mode.Format = format;
878
879     /* TODO: The possible return values from msdn suggest that
880      * the screen mode can't be changed if a surface is locked
881      * or some drawing is in progress
882      */
883
884     /* TODO: Lose the primary surface */
885     hr = wined3d_device_set_display_mode(ddraw->wined3d_device, 0, &Mode);
886     wined3d_device_restore_fullscreen_window(ddraw->wined3d_device, ddraw->dest_window);
887     wined3d_device_setup_fullscreen_window(ddraw->wined3d_device, ddraw->dest_window, Width, Height);
888     LeaveCriticalSection(&ddraw_cs);
889     switch(hr)
890     {
891         case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
892         default:                            return hr;
893     }
894 }
895
896 /*****************************************************************************
897  * IDirectDraw7::SetDisplayMode
898  *
899  * Sets the display screen resolution, color depth and refresh frequency
900  * when in fullscreen mode (in theory).
901  * Possible return values listed in the SDK suggest that this method fails
902  * when not in fullscreen mode, but this is wrong. Windows 2000 happily sets
903  * the display mode in DDSCL_NORMAL mode without an hwnd specified.
904  * It seems to be valid to pass 0 for With and Height, this has to be tested
905  * It could mean that the current video mode should be left as-is. (But why
906  * call it then?)
907  *
908  * Params:
909  *  Height, Width: Screen dimension
910  *  BPP: Color depth in Bits per pixel
911  *  Refreshrate: Screen refresh rate
912  *  Flags: Other stuff
913  *
914  * Returns
915  *  DD_OK on success
916  *
917  *****************************************************************************/
918 static HRESULT WINAPI ddraw7_SetDisplayMode(IDirectDraw7 *iface, DWORD Width, DWORD Height,
919         DWORD BPP, DWORD RefreshRate, DWORD Flags)
920 {
921     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
922
923     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
924             iface, Width, Height, BPP, RefreshRate, Flags);
925
926     if (force_refresh_rate != 0)
927     {
928         TRACE("ForceRefreshRate overriding passed-in refresh rate (%u Hz) to %u Hz\n",
929                 RefreshRate, force_refresh_rate);
930         RefreshRate = force_refresh_rate;
931     }
932
933     return ddraw_set_display_mode(This, Width, Height, BPP, RefreshRate, Flags);
934 }
935
936 static HRESULT WINAPI ddraw4_SetDisplayMode(IDirectDraw4 *iface, DWORD width, DWORD height,
937         DWORD bpp, DWORD refresh_rate, DWORD flags)
938 {
939     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
940
941     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
942             iface, width, height, bpp, refresh_rate, flags);
943
944     return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
945 }
946
947 static HRESULT WINAPI ddraw3_SetDisplayMode(IDirectDraw3 *iface, DWORD width, DWORD height,
948         DWORD bpp, DWORD refresh_rate, DWORD flags)
949 {
950     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
951
952     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
953             iface, width, height, bpp, refresh_rate, flags);
954
955     return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
956 }
957
958 static HRESULT WINAPI ddraw2_SetDisplayMode(IDirectDraw2 *iface,
959         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
960 {
961     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
962
963     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
964             iface, width, height, bpp, refresh_rate, flags);
965
966     return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
967 }
968
969 static HRESULT WINAPI ddraw1_SetDisplayMode(IDirectDraw *iface, DWORD width, DWORD height, DWORD bpp)
970 {
971     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
972
973     TRACE("iface %p, width %u, height %u, bpp %u.\n", iface, width, height, bpp);
974
975     return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, 0, 0);
976 }
977
978 /*****************************************************************************
979  * IDirectDraw7::RestoreDisplayMode
980  *
981  * Restores the display mode to what it was at creation time. Basically.
982  *
983  * A problem arises when there are 2 DirectDraw objects using the same hwnd:
984  *  -> DD_1 finds the screen at 1400x1050x32 when created, sets it to 640x480x16
985  *  -> DD_2 is created, finds the screen at 640x480x16, sets it to 1024x768x32
986  *  -> DD_1 is released. The screen should be left at 1024x768x32.
987  *  -> DD_2 is released. The screen should be set to 1400x1050x32
988  * This case is unhandled right now, but Empire Earth does it this way.
989  * (But perhaps there is something in SetCooperativeLevel to prevent this)
990  *
991  * The msdn says that this method resets the display mode to what it was before
992  * SetDisplayMode was called. What if SetDisplayModes is called 2 times??
993  *
994  * Returns
995  *  DD_OK on success
996  *  DDERR_NOEXCLUSIVE mode if the device isn't in fullscreen mode
997  *
998  *****************************************************************************/
999 static HRESULT WINAPI ddraw7_RestoreDisplayMode(IDirectDraw7 *iface)
1000 {
1001     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1002
1003     TRACE("iface %p.\n", iface);
1004
1005     return ddraw_set_display_mode(This, This->orig_width, This->orig_height, This->orig_bpp, 0, 0);
1006 }
1007
1008 static HRESULT WINAPI ddraw4_RestoreDisplayMode(IDirectDraw4 *iface)
1009 {
1010     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1011
1012     TRACE("iface %p.\n", iface);
1013
1014     return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1015 }
1016
1017 static HRESULT WINAPI ddraw3_RestoreDisplayMode(IDirectDraw3 *iface)
1018 {
1019     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1020
1021     TRACE("iface %p.\n", iface);
1022
1023     return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1024 }
1025
1026 static HRESULT WINAPI ddraw2_RestoreDisplayMode(IDirectDraw2 *iface)
1027 {
1028     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1029
1030     TRACE("iface %p.\n", iface);
1031
1032     return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1033 }
1034
1035 static HRESULT WINAPI ddraw1_RestoreDisplayMode(IDirectDraw *iface)
1036 {
1037     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1038
1039     TRACE("iface %p.\n", iface);
1040
1041     return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1042 }
1043
1044 /*****************************************************************************
1045  * IDirectDraw7::GetCaps
1046  *
1047  * Returns the drives capabilities
1048  *
1049  * Used for version 1, 2, 4 and 7
1050  *
1051  * Params:
1052  *  DriverCaps: Structure to write the Hardware accelerated caps to
1053  *  HelCaps: Structure to write the emulation caps to
1054  *
1055  * Returns
1056  *  This implementation returns DD_OK only
1057  *
1058  *****************************************************************************/
1059 static HRESULT WINAPI ddraw7_GetCaps(IDirectDraw7 *iface, DDCAPS *DriverCaps, DDCAPS *HELCaps)
1060 {
1061     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1062     DDCAPS caps;
1063     WINED3DCAPS winecaps;
1064     HRESULT hr;
1065     DDSCAPS2 ddscaps = {0, 0, 0, 0};
1066
1067     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, DriverCaps, HELCaps);
1068
1069     /* One structure must be != NULL */
1070     if( (!DriverCaps) && (!HELCaps) )
1071     {
1072         ERR("(%p) Invalid params to ddraw7_GetCaps\n", This);
1073         return DDERR_INVALIDPARAMS;
1074     }
1075
1076     memset(&caps, 0, sizeof(caps));
1077     memset(&winecaps, 0, sizeof(winecaps));
1078     caps.dwSize = sizeof(caps);
1079     EnterCriticalSection(&ddraw_cs);
1080     hr = wined3d_device_get_device_caps(This->wined3d_device, &winecaps);
1081     if (FAILED(hr))
1082     {
1083         WARN("IWineD3DDevice::GetDeviceCaps failed\n");
1084         LeaveCriticalSection(&ddraw_cs);
1085         return hr;
1086     }
1087
1088     hr = IDirectDraw7_GetAvailableVidMem(iface, &ddscaps, &caps.dwVidMemTotal, &caps.dwVidMemFree);
1089     LeaveCriticalSection(&ddraw_cs);
1090     if(FAILED(hr)) {
1091         WARN("IDirectDraw7::GetAvailableVidMem failed\n");
1092         return hr;
1093     }
1094
1095     caps.dwCaps = winecaps.DirectDrawCaps.Caps;
1096     caps.dwCaps2 = winecaps.DirectDrawCaps.Caps2;
1097     caps.dwCKeyCaps = winecaps.DirectDrawCaps.CKeyCaps;
1098     caps.dwFXCaps = winecaps.DirectDrawCaps.FXCaps;
1099     caps.dwPalCaps = winecaps.DirectDrawCaps.PalCaps;
1100     caps.ddsCaps.dwCaps = winecaps.DirectDrawCaps.ddsCaps;
1101     caps.dwSVBCaps = winecaps.DirectDrawCaps.SVBCaps;
1102     caps.dwSVBCKeyCaps = winecaps.DirectDrawCaps.SVBCKeyCaps;
1103     caps.dwSVBFXCaps = winecaps.DirectDrawCaps.SVBFXCaps;
1104     caps.dwVSBCaps = winecaps.DirectDrawCaps.VSBCaps;
1105     caps.dwVSBCKeyCaps = winecaps.DirectDrawCaps.VSBCKeyCaps;
1106     caps.dwVSBFXCaps = winecaps.DirectDrawCaps.VSBFXCaps;
1107     caps.dwSSBCaps = winecaps.DirectDrawCaps.SSBCaps;
1108     caps.dwSSBCKeyCaps = winecaps.DirectDrawCaps.SSBCKeyCaps;
1109     caps.dwSSBFXCaps = winecaps.DirectDrawCaps.SSBFXCaps;
1110
1111     /* Even if WineD3D supports 3D rendering, remove the cap if ddraw is configured
1112      * not to use it
1113      */
1114     if(DefaultSurfaceType == SURFACE_GDI) {
1115         caps.dwCaps &= ~DDCAPS_3D;
1116         caps.ddsCaps.dwCaps &= ~(DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER);
1117     }
1118     if(winecaps.DirectDrawCaps.StrideAlign != 0) {
1119         caps.dwCaps |= DDCAPS_ALIGNSTRIDE;
1120         caps.dwAlignStrideAlign = winecaps.DirectDrawCaps.StrideAlign;
1121     }
1122
1123     if(DriverCaps)
1124     {
1125         DD_STRUCT_COPY_BYSIZE(DriverCaps, &caps);
1126         if (TRACE_ON(ddraw))
1127         {
1128             TRACE("Driver Caps :\n");
1129             DDRAW_dump_DDCAPS(DriverCaps);
1130         }
1131
1132     }
1133     if(HELCaps)
1134     {
1135         DD_STRUCT_COPY_BYSIZE(HELCaps, &caps);
1136         if (TRACE_ON(ddraw))
1137         {
1138             TRACE("HEL Caps :\n");
1139             DDRAW_dump_DDCAPS(HELCaps);
1140         }
1141     }
1142
1143     return DD_OK;
1144 }
1145
1146 static HRESULT WINAPI ddraw4_GetCaps(IDirectDraw4 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1147 {
1148     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1149
1150     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1151
1152     return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1153 }
1154
1155 static HRESULT WINAPI ddraw3_GetCaps(IDirectDraw3 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1156 {
1157     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1158
1159     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1160
1161     return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1162 }
1163
1164 static HRESULT WINAPI ddraw2_GetCaps(IDirectDraw2 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1165 {
1166     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1167
1168     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1169
1170     return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1171 }
1172
1173 static HRESULT WINAPI ddraw1_GetCaps(IDirectDraw *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1174 {
1175     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1176
1177     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1178
1179     return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1180 }
1181
1182 /*****************************************************************************
1183  * IDirectDraw7::Compact
1184  *
1185  * No idea what it does, MSDN says it's not implemented.
1186  *
1187  * Returns
1188  *  DD_OK, but this is unchecked
1189  *
1190  *****************************************************************************/
1191 static HRESULT WINAPI ddraw7_Compact(IDirectDraw7 *iface)
1192 {
1193     TRACE("iface %p.\n", iface);
1194
1195     return DD_OK;
1196 }
1197
1198 static HRESULT WINAPI ddraw4_Compact(IDirectDraw4 *iface)
1199 {
1200     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1201
1202     TRACE("iface %p.\n", iface);
1203
1204     return ddraw7_Compact(&This->IDirectDraw7_iface);
1205 }
1206
1207 static HRESULT WINAPI ddraw3_Compact(IDirectDraw3 *iface)
1208 {
1209     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1210
1211     TRACE("iface %p.\n", iface);
1212
1213     return ddraw7_Compact(&This->IDirectDraw7_iface);
1214 }
1215
1216 static HRESULT WINAPI ddraw2_Compact(IDirectDraw2 *iface)
1217 {
1218     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1219
1220     TRACE("iface %p.\n", iface);
1221
1222     return ddraw7_Compact(&This->IDirectDraw7_iface);
1223 }
1224
1225 static HRESULT WINAPI ddraw1_Compact(IDirectDraw *iface)
1226 {
1227     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1228
1229     TRACE("iface %p.\n", iface);
1230
1231     return ddraw7_Compact(&This->IDirectDraw7_iface);
1232 }
1233
1234 /*****************************************************************************
1235  * IDirectDraw7::GetDisplayMode
1236  *
1237  * Returns information about the current display mode
1238  *
1239  * Exists in Version 1, 2, 4 and 7
1240  *
1241  * Params:
1242  *  DDSD: Address of a surface description structure to write the info to
1243  *
1244  * Returns
1245  *  DD_OK
1246  *
1247  *****************************************************************************/
1248 static HRESULT WINAPI ddraw7_GetDisplayMode(IDirectDraw7 *iface, DDSURFACEDESC2 *DDSD)
1249 {
1250     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1251     HRESULT hr;
1252     WINED3DDISPLAYMODE Mode;
1253     DWORD Size;
1254
1255     TRACE("iface %p, surface_desc %p.\n", iface, DDSD);
1256
1257     EnterCriticalSection(&ddraw_cs);
1258     /* This seems sane */
1259     if (!DDSD)
1260     {
1261         LeaveCriticalSection(&ddraw_cs);
1262         return DDERR_INVALIDPARAMS;
1263     }
1264
1265     /* The necessary members of LPDDSURFACEDESC and LPDDSURFACEDESC2 are equal,
1266      * so one method can be used for all versions (Hopefully) */
1267     hr = wined3d_device_get_display_mode(This->wined3d_device, 0, &Mode);
1268     if (FAILED(hr))
1269     {
1270         ERR(" (%p) IWineD3DDevice::GetDisplayMode returned %08x\n", This, hr);
1271         LeaveCriticalSection(&ddraw_cs);
1272         return hr;
1273     }
1274
1275     Size = DDSD->dwSize;
1276     memset(DDSD, 0, Size);
1277
1278     DDSD->dwSize = Size;
1279     DDSD->dwFlags |= DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_PITCH | DDSD_REFRESHRATE;
1280     DDSD->dwWidth = Mode.Width;
1281     DDSD->dwHeight = Mode.Height;
1282     DDSD->u2.dwRefreshRate = 60;
1283     DDSD->ddsCaps.dwCaps = 0;
1284     DDSD->u4.ddpfPixelFormat.dwSize = sizeof(DDSD->u4.ddpfPixelFormat);
1285     PixelFormat_WineD3DtoDD(&DDSD->u4.ddpfPixelFormat, Mode.Format);
1286     DDSD->u1.lPitch = Mode.Width * DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount / 8;
1287
1288     if(TRACE_ON(ddraw))
1289     {
1290         TRACE("Returning surface desc :\n");
1291         DDRAW_dump_surface_desc(DDSD);
1292     }
1293
1294     LeaveCriticalSection(&ddraw_cs);
1295     return DD_OK;
1296 }
1297
1298 static HRESULT WINAPI ddraw4_GetDisplayMode(IDirectDraw4 *iface, DDSURFACEDESC2 *surface_desc)
1299 {
1300     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1301
1302     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1303
1304     return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, surface_desc);
1305 }
1306
1307 static HRESULT WINAPI ddraw3_GetDisplayMode(IDirectDraw3 *iface, DDSURFACEDESC *surface_desc)
1308 {
1309     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1310
1311     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1312
1313     return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1314 }
1315
1316 static HRESULT WINAPI ddraw2_GetDisplayMode(IDirectDraw2 *iface, DDSURFACEDESC *surface_desc)
1317 {
1318     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1319
1320     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1321
1322     return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1323 }
1324
1325 static HRESULT WINAPI ddraw1_GetDisplayMode(IDirectDraw *iface, DDSURFACEDESC *surface_desc)
1326 {
1327     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1328
1329     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1330
1331     return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1332 }
1333
1334 /*****************************************************************************
1335  * IDirectDraw7::GetFourCCCodes
1336  *
1337  * Returns an array of supported FourCC codes.
1338  *
1339  * Exists in Version 1, 2, 4 and 7
1340  *
1341  * Params:
1342  *  NumCodes: Contains the number of Codes that Codes can carry. Returns the number
1343  *            of enumerated codes
1344  *  Codes: Pointer to an array of DWORDs where the supported codes are written
1345  *         to
1346  *
1347  * Returns
1348  *  Always returns DD_OK, as it's a stub for now
1349  *
1350  *****************************************************************************/
1351 static HRESULT WINAPI ddraw7_GetFourCCCodes(IDirectDraw7 *iface, DWORD *NumCodes, DWORD *Codes)
1352 {
1353     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1354     static const enum wined3d_format_id formats[] =
1355     {
1356         WINED3DFMT_YUY2, WINED3DFMT_UYVY, WINED3DFMT_YV12,
1357         WINED3DFMT_DXT1, WINED3DFMT_DXT2, WINED3DFMT_DXT3, WINED3DFMT_DXT4, WINED3DFMT_DXT5,
1358         WINED3DFMT_ATI2N, WINED3DFMT_NVHU, WINED3DFMT_NVHS
1359     };
1360     DWORD count = 0, i, outsize;
1361     HRESULT hr;
1362     WINED3DDISPLAYMODE d3ddm;
1363     WINED3DSURFTYPE type = This->ImplType;
1364
1365     TRACE("iface %p, codes_count %p, codes %p.\n", iface, NumCodes, Codes);
1366
1367     wined3d_device_get_display_mode(This->wined3d_device, 0, &d3ddm);
1368
1369     outsize = NumCodes && Codes ? *NumCodes : 0;
1370
1371     if(type == SURFACE_UNKNOWN) type = SURFACE_GDI;
1372
1373     for (i = 0; i < (sizeof(formats) / sizeof(formats[0])); ++i)
1374     {
1375         hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, WINED3DDEVTYPE_HAL,
1376                 d3ddm.Format, 0, WINED3DRTYPE_SURFACE, formats[i], type);
1377         if (SUCCEEDED(hr))
1378         {
1379             if (count < outsize)
1380                 Codes[count] = formats[i];
1381             ++count;
1382         }
1383     }
1384     if(NumCodes) {
1385         TRACE("Returning %u FourCC codes\n", count);
1386         *NumCodes = count;
1387     }
1388
1389     return DD_OK;
1390 }
1391
1392 static HRESULT WINAPI ddraw4_GetFourCCCodes(IDirectDraw4 *iface, DWORD *codes_count, DWORD *codes)
1393 {
1394     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1395
1396     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1397
1398     return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1399 }
1400
1401 static HRESULT WINAPI ddraw3_GetFourCCCodes(IDirectDraw3 *iface, DWORD *codes_count, DWORD *codes)
1402 {
1403     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1404
1405     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1406
1407     return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1408 }
1409
1410 static HRESULT WINAPI ddraw2_GetFourCCCodes(IDirectDraw2 *iface, DWORD *codes_count, DWORD *codes)
1411 {
1412     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1413
1414     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1415
1416     return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1417 }
1418
1419 static HRESULT WINAPI ddraw1_GetFourCCCodes(IDirectDraw *iface, DWORD *codes_count, DWORD *codes)
1420 {
1421     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1422
1423     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1424
1425     return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1426 }
1427
1428 /*****************************************************************************
1429  * IDirectDraw7::GetMonitorFrequency
1430  *
1431  * Returns the monitor's frequency
1432  *
1433  * Exists in Version 1, 2, 4 and 7
1434  *
1435  * Params:
1436  *  Freq: Pointer to a DWORD to write the frequency to
1437  *
1438  * Returns
1439  *  Always returns DD_OK
1440  *
1441  *****************************************************************************/
1442 static HRESULT WINAPI ddraw7_GetMonitorFrequency(IDirectDraw7 *iface, DWORD *Freq)
1443 {
1444     FIXME("iface %p, frequency %p stub!\n", iface, Freq);
1445
1446     /* Ideally this should be in WineD3D, as it concerns the screen setup,
1447      * but for now this should make the games happy
1448      */
1449     *Freq = 60;
1450     return DD_OK;
1451 }
1452
1453 static HRESULT WINAPI ddraw4_GetMonitorFrequency(IDirectDraw4 *iface, DWORD *frequency)
1454 {
1455     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1456
1457     TRACE("iface %p, frequency %p.\n", iface, frequency);
1458
1459     return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1460 }
1461
1462 static HRESULT WINAPI ddraw3_GetMonitorFrequency(IDirectDraw3 *iface, DWORD *frequency)
1463 {
1464     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1465
1466     TRACE("iface %p, frequency %p.\n", iface, frequency);
1467
1468     return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1469 }
1470
1471 static HRESULT WINAPI ddraw2_GetMonitorFrequency(IDirectDraw2 *iface, DWORD *frequency)
1472 {
1473     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1474
1475     TRACE("iface %p, frequency %p.\n", iface, frequency);
1476
1477     return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1478 }
1479
1480 static HRESULT WINAPI ddraw1_GetMonitorFrequency(IDirectDraw *iface, DWORD *frequency)
1481 {
1482     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1483
1484     TRACE("iface %p, frequency %p.\n", iface, frequency);
1485
1486     return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1487 }
1488
1489 /*****************************************************************************
1490  * IDirectDraw7::GetVerticalBlankStatus
1491  *
1492  * Returns the Vertical blank status of the monitor. This should be in WineD3D
1493  * too basically, but as it's a semi stub, I didn't create a function there
1494  *
1495  * Params:
1496  *  status: Pointer to a BOOL to be filled with the vertical blank status
1497  *
1498  * Returns
1499  *  DD_OK on success
1500  *  DDERR_INVALIDPARAMS if status is NULL
1501  *
1502  *****************************************************************************/
1503 static HRESULT WINAPI ddraw7_GetVerticalBlankStatus(IDirectDraw7 *iface, BOOL *status)
1504 {
1505     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1506
1507     TRACE("iface %p, status %p.\n", iface, status);
1508
1509     /* This looks sane, the MSDN suggests it too */
1510     EnterCriticalSection(&ddraw_cs);
1511     if(!status)
1512     {
1513         LeaveCriticalSection(&ddraw_cs);
1514         return DDERR_INVALIDPARAMS;
1515     }
1516
1517     *status = This->fake_vblank;
1518     This->fake_vblank = !This->fake_vblank;
1519     LeaveCriticalSection(&ddraw_cs);
1520     return DD_OK;
1521 }
1522
1523 static HRESULT WINAPI ddraw4_GetVerticalBlankStatus(IDirectDraw4 *iface, BOOL *status)
1524 {
1525     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1526
1527     TRACE("iface %p, status %p.\n", iface, status);
1528
1529     return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1530 }
1531
1532 static HRESULT WINAPI ddraw3_GetVerticalBlankStatus(IDirectDraw3 *iface, BOOL *status)
1533 {
1534     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1535
1536     TRACE("iface %p, status %p.\n", iface, status);
1537
1538     return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1539 }
1540
1541 static HRESULT WINAPI ddraw2_GetVerticalBlankStatus(IDirectDraw2 *iface, BOOL *status)
1542 {
1543     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1544
1545     TRACE("iface %p, status %p.\n", iface, status);
1546
1547     return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1548 }
1549
1550 static HRESULT WINAPI ddraw1_GetVerticalBlankStatus(IDirectDraw *iface, BOOL *status)
1551 {
1552     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1553
1554     TRACE("iface %p, status %p.\n", iface, status);
1555
1556     return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1557 }
1558
1559 /*****************************************************************************
1560  * IDirectDraw7::GetAvailableVidMem
1561  *
1562  * Returns the total and free video memory
1563  *
1564  * Params:
1565  *  Caps: Specifies the memory type asked for
1566  *  total: Pointer to a DWORD to be filled with the total memory
1567  *  free: Pointer to a DWORD to be filled with the free memory
1568  *
1569  * Returns
1570  *  DD_OK on success
1571  *  DDERR_INVALIDPARAMS of free and total are NULL
1572  *
1573  *****************************************************************************/
1574 static HRESULT WINAPI ddraw7_GetAvailableVidMem(IDirectDraw7 *iface, DDSCAPS2 *Caps, DWORD *total,
1575         DWORD *free)
1576 {
1577     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1578
1579     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, Caps, total, free);
1580
1581     if(TRACE_ON(ddraw))
1582     {
1583         TRACE("(%p) Asked for memory with description: ", This);
1584         DDRAW_dump_DDSCAPS2(Caps);
1585     }
1586     EnterCriticalSection(&ddraw_cs);
1587
1588     /* Todo: System memory vs local video memory vs non-local video memory
1589      * The MSDN also mentions differences between texture memory and other
1590      * resources, but that's not important
1591      */
1592
1593     if( (!total) && (!free) )
1594     {
1595         LeaveCriticalSection(&ddraw_cs);
1596         return DDERR_INVALIDPARAMS;
1597     }
1598
1599     if (total)
1600         *total = This->total_vidmem;
1601     if (free)
1602         *free = wined3d_device_get_available_texture_mem(This->wined3d_device);
1603
1604     LeaveCriticalSection(&ddraw_cs);
1605     return DD_OK;
1606 }
1607
1608 static HRESULT WINAPI ddraw4_GetAvailableVidMem(IDirectDraw4 *iface,
1609         DDSCAPS2 *caps, DWORD *total, DWORD *free)
1610 {
1611     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1612
1613     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1614
1615     return ddraw7_GetAvailableVidMem(&This->IDirectDraw7_iface, caps, total, free);
1616 }
1617
1618 static HRESULT WINAPI ddraw3_GetAvailableVidMem(IDirectDraw3 *iface, DDSCAPS *caps, DWORD *total,
1619         DWORD *free)
1620 {
1621     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1622     DDSCAPS2 caps2;
1623
1624     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1625
1626     DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1627     return ddraw7_GetAvailableVidMem(&This->IDirectDraw7_iface, &caps2, total, free);
1628 }
1629
1630 static HRESULT WINAPI ddraw2_GetAvailableVidMem(IDirectDraw2 *iface,
1631         DDSCAPS *caps, DWORD *total, DWORD *free)
1632 {
1633     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1634     DDSCAPS2 caps2;
1635
1636     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1637
1638     DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1639     return ddraw7_GetAvailableVidMem(&This->IDirectDraw7_iface, &caps2, total, free);
1640 }
1641
1642 /*****************************************************************************
1643  * IDirectDraw7::Initialize
1644  *
1645  * Initializes a DirectDraw interface.
1646  *
1647  * Params:
1648  *  GUID: Interface identifier. Well, don't know what this is really good
1649  *   for
1650  *
1651  * Returns
1652  *  Returns DD_OK on the first call,
1653  *  DDERR_ALREADYINITIALIZED on repeated calls
1654  *
1655  *****************************************************************************/
1656 static HRESULT WINAPI ddraw7_Initialize(IDirectDraw7 *iface, GUID *Guid)
1657 {
1658     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1659
1660     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(Guid));
1661
1662     if(This->initialized)
1663     {
1664         return DDERR_ALREADYINITIALIZED;
1665     }
1666     else
1667     {
1668         return DD_OK;
1669     }
1670 }
1671
1672 static HRESULT WINAPI ddraw4_Initialize(IDirectDraw4 *iface, GUID *guid)
1673 {
1674     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1675
1676     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1677
1678     return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1679 }
1680
1681 static HRESULT WINAPI ddraw3_Initialize(IDirectDraw3 *iface, GUID *guid)
1682 {
1683     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1684
1685     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1686
1687     return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1688 }
1689
1690 static HRESULT WINAPI ddraw2_Initialize(IDirectDraw2 *iface, GUID *guid)
1691 {
1692     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1693
1694     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1695
1696     return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1697 }
1698
1699 static HRESULT WINAPI ddraw1_Initialize(IDirectDraw *iface, GUID *guid)
1700 {
1701     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1702
1703     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1704
1705     return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1706 }
1707
1708 static HRESULT WINAPI d3d1_Initialize(IDirect3D *iface, REFIID riid)
1709 {
1710     TRACE("iface %p, riid %s.\n", iface, debugstr_guid(riid));
1711
1712     return D3D_OK;
1713 }
1714
1715 /*****************************************************************************
1716  * IDirectDraw7::FlipToGDISurface
1717  *
1718  * "Makes the surface that the GDI writes to the primary surface"
1719  * Looks like some windows specific thing we don't have to care about.
1720  * According to MSDN it permits GDI dialog boxes in FULLSCREEN mode. Good to
1721  * show error boxes ;)
1722  * Well, just return DD_OK.
1723  *
1724  * Returns:
1725  *  Always returns DD_OK
1726  *
1727  *****************************************************************************/
1728 static HRESULT WINAPI ddraw7_FlipToGDISurface(IDirectDraw7 *iface)
1729 {
1730     FIXME("iface %p stub!\n", iface);
1731
1732     return DD_OK;
1733 }
1734
1735 static HRESULT WINAPI ddraw4_FlipToGDISurface(IDirectDraw4 *iface)
1736 {
1737     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1738
1739     TRACE("iface %p.\n", iface);
1740
1741     return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1742 }
1743
1744 static HRESULT WINAPI ddraw3_FlipToGDISurface(IDirectDraw3 *iface)
1745 {
1746     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1747
1748     TRACE("iface %p.\n", iface);
1749
1750     return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1751 }
1752
1753 static HRESULT WINAPI ddraw2_FlipToGDISurface(IDirectDraw2 *iface)
1754 {
1755     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1756
1757     TRACE("iface %p.\n", iface);
1758
1759     return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1760 }
1761
1762 static HRESULT WINAPI ddraw1_FlipToGDISurface(IDirectDraw *iface)
1763 {
1764     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1765
1766     TRACE("iface %p.\n", iface);
1767
1768     return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1769 }
1770
1771 /*****************************************************************************
1772  * IDirectDraw7::WaitForVerticalBlank
1773  *
1774  * This method allows applications to get in sync with the vertical blank
1775  * interval.
1776  * The wormhole demo in the DirectX 7 sdk uses this call, and it doesn't
1777  * redraw the screen, most likely because of this stub
1778  *
1779  * Parameters:
1780  *  Flags: one of DDWAITVB_BLOCKBEGIN, DDWAITVB_BLOCKBEGINEVENT
1781  *         or DDWAITVB_BLOCKEND
1782  *  h: Not used, according to MSDN
1783  *
1784  * Returns:
1785  *  Always returns DD_OK
1786  *
1787  *****************************************************************************/
1788 static HRESULT WINAPI ddraw7_WaitForVerticalBlank(IDirectDraw7 *iface, DWORD Flags, HANDLE event)
1789 {
1790     static BOOL hide;
1791
1792     TRACE("iface %p, flags %#x, event %p.\n", iface, Flags, event);
1793
1794     /* This function is called often, so print the fixme only once */
1795     if(!hide)
1796     {
1797         FIXME("iface %p, flags %#x, event %p stub!\n", iface, Flags, event);
1798         hide = TRUE;
1799     }
1800
1801     /* MSDN says DDWAITVB_BLOCKBEGINEVENT is not supported */
1802     if(Flags & DDWAITVB_BLOCKBEGINEVENT)
1803         return DDERR_UNSUPPORTED; /* unchecked */
1804
1805     return DD_OK;
1806 }
1807
1808 static HRESULT WINAPI ddraw4_WaitForVerticalBlank(IDirectDraw4 *iface, DWORD flags, HANDLE event)
1809 {
1810     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1811
1812     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1813
1814     return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1815 }
1816
1817 static HRESULT WINAPI ddraw3_WaitForVerticalBlank(IDirectDraw3 *iface, DWORD flags, HANDLE event)
1818 {
1819     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1820
1821     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1822
1823     return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1824 }
1825
1826 static HRESULT WINAPI ddraw2_WaitForVerticalBlank(IDirectDraw2 *iface, DWORD flags, HANDLE event)
1827 {
1828     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1829
1830     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1831
1832     return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1833 }
1834
1835 static HRESULT WINAPI ddraw1_WaitForVerticalBlank(IDirectDraw *iface, DWORD flags, HANDLE event)
1836 {
1837     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1838
1839     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1840
1841     return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1842 }
1843
1844 /*****************************************************************************
1845  * IDirectDraw7::GetScanLine
1846  *
1847  * Returns the scan line that is being drawn on the monitor
1848  *
1849  * Parameters:
1850  *  Scanline: Address to write the scan line value to
1851  *
1852  * Returns:
1853  *  Always returns DD_OK
1854  *
1855  *****************************************************************************/
1856 static HRESULT WINAPI ddraw7_GetScanLine(IDirectDraw7 *iface, DWORD *Scanline)
1857 {
1858     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1859     static BOOL hide = FALSE;
1860     WINED3DDISPLAYMODE Mode;
1861
1862     TRACE("iface %p, line %p.\n", iface, Scanline);
1863
1864     /* This function is called often, so print the fixme only once */
1865     EnterCriticalSection(&ddraw_cs);
1866     if(!hide)
1867     {
1868         FIXME("iface %p, line %p partial stub!\n", iface, Scanline);
1869         hide = TRUE;
1870     }
1871
1872     wined3d_device_get_display_mode(This->wined3d_device, 0, &Mode);
1873
1874     /* Fake the line sweeping of the monitor */
1875     /* FIXME: We should synchronize with a source to keep the refresh rate */
1876     *Scanline = This->cur_scanline++;
1877     /* Assume 20 scan lines in the vertical blank */
1878     if (This->cur_scanline >= Mode.Height + 20)
1879         This->cur_scanline = 0;
1880
1881     LeaveCriticalSection(&ddraw_cs);
1882     return DD_OK;
1883 }
1884
1885 static HRESULT WINAPI ddraw4_GetScanLine(IDirectDraw4 *iface, DWORD *line)
1886 {
1887     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1888
1889     TRACE("iface %p, line %p.\n", iface, line);
1890
1891     return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1892 }
1893
1894 static HRESULT WINAPI ddraw3_GetScanLine(IDirectDraw3 *iface, DWORD *line)
1895 {
1896     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1897
1898     TRACE("iface %p, line %p.\n", iface, line);
1899
1900     return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1901 }
1902
1903 static HRESULT WINAPI ddraw2_GetScanLine(IDirectDraw2 *iface, DWORD *line)
1904 {
1905     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1906
1907     TRACE("iface %p, line %p.\n", iface, line);
1908
1909     return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1910 }
1911
1912 static HRESULT WINAPI ddraw1_GetScanLine(IDirectDraw *iface, DWORD *line)
1913 {
1914     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
1915
1916     TRACE("iface %p, line %p.\n", iface, line);
1917
1918     return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1919 }
1920
1921 /*****************************************************************************
1922  * IDirectDraw7::TestCooperativeLevel
1923  *
1924  * Informs the application about the state of the video adapter, depending
1925  * on the cooperative level
1926  *
1927  * Returns:
1928  *  DD_OK if the device is in a sane state
1929  *  DDERR_NOEXCLUSIVEMODE or DDERR_EXCLUSIVEMODEALREADYSET
1930  *  if the state is not correct(See below)
1931  *
1932  *****************************************************************************/
1933 static HRESULT WINAPI ddraw7_TestCooperativeLevel(IDirectDraw7 *iface)
1934 {
1935     TRACE("iface %p.\n", iface);
1936
1937     return DD_OK;
1938 }
1939
1940 static HRESULT WINAPI ddraw4_TestCooperativeLevel(IDirectDraw4 *iface)
1941 {
1942     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
1943
1944     TRACE("iface %p.\n", iface);
1945
1946     return ddraw7_TestCooperativeLevel(&This->IDirectDraw7_iface);
1947 }
1948
1949 /*****************************************************************************
1950  * IDirectDraw7::GetGDISurface
1951  *
1952  * Returns the surface that GDI is treating as the primary surface.
1953  * For Wine this is the front buffer
1954  *
1955  * Params:
1956  *  GDISurface: Address to write the surface pointer to
1957  *
1958  * Returns:
1959  *  DD_OK if the surface was found
1960  *  DDERR_NOTFOUND if the GDI surface wasn't found
1961  *
1962  *****************************************************************************/
1963 static HRESULT WINAPI ddraw7_GetGDISurface(IDirectDraw7 *iface, IDirectDrawSurface7 **GDISurface)
1964 {
1965     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1966     struct wined3d_surface *wined3d_surface;
1967     IDirectDrawSurface7 *ddsurf;
1968     HRESULT hr;
1969     DDSCAPS2 ddsCaps;
1970
1971     TRACE("iface %p, surface %p.\n", iface, GDISurface);
1972
1973     /* Get the back buffer from the wineD3DDevice and search its
1974      * attached surfaces for the front buffer. */
1975     EnterCriticalSection(&ddraw_cs);
1976     hr = wined3d_device_get_back_buffer(This->wined3d_device,
1977             0, 0, WINED3DBACKBUFFER_TYPE_MONO, &wined3d_surface);
1978     if (FAILED(hr) || !wined3d_surface)
1979     {
1980         ERR("IWineD3DDevice::GetBackBuffer failed\n");
1981         LeaveCriticalSection(&ddraw_cs);
1982         return DDERR_NOTFOUND;
1983     }
1984
1985     ddsurf = wined3d_surface_get_parent(wined3d_surface);
1986     wined3d_surface_decref(wined3d_surface);
1987
1988     /* Find the front buffer */
1989     ddsCaps.dwCaps = DDSCAPS_FRONTBUFFER;
1990     hr = IDirectDrawSurface7_GetAttachedSurface(ddsurf,
1991                                                 &ddsCaps,
1992                                                 GDISurface);
1993     if(hr != DD_OK)
1994     {
1995         ERR("IDirectDrawSurface7::GetAttachedSurface failed, hr = %x\n", hr);
1996     }
1997
1998     /* The AddRef is OK this time */
1999     LeaveCriticalSection(&ddraw_cs);
2000     return hr;
2001 }
2002
2003 static HRESULT WINAPI ddraw4_GetGDISurface(IDirectDraw4 *iface, IDirectDrawSurface4 **surface)
2004 {
2005     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2006
2007     TRACE("iface %p, surface %p.\n", iface, surface);
2008
2009     return ddraw7_GetGDISurface(&This->IDirectDraw7_iface, (IDirectDrawSurface7 **)surface);
2010 }
2011
2012 static HRESULT WINAPI ddraw3_GetGDISurface(IDirectDraw3 *iface, IDirectDrawSurface **surface)
2013 {
2014     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
2015     IDirectDrawSurface7 *surface7;
2016     HRESULT hr;
2017
2018     TRACE("iface %p, surface %p.\n", iface, surface);
2019
2020     hr = ddraw7_GetGDISurface(&This->IDirectDraw7_iface, &surface7);
2021     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
2022
2023     return hr;
2024 }
2025
2026 static HRESULT WINAPI ddraw2_GetGDISurface(IDirectDraw2 *iface, IDirectDrawSurface **surface)
2027 {
2028     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
2029     IDirectDrawSurface7 *surface7;
2030     HRESULT hr;
2031
2032     TRACE("iface %p, surface %p.\n", iface, surface);
2033
2034     hr = ddraw7_GetGDISurface(&This->IDirectDraw7_iface, &surface7);
2035     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
2036
2037     return hr;
2038 }
2039
2040 static HRESULT WINAPI ddraw1_GetGDISurface(IDirectDraw *iface, IDirectDrawSurface **surface)
2041 {
2042     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
2043     IDirectDrawSurface7 *surface7;
2044     HRESULT hr;
2045
2046     TRACE("iface %p, surface %p.\n", iface, surface);
2047
2048     hr = ddraw7_GetGDISurface(&This->IDirectDraw7_iface, &surface7);
2049     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
2050
2051     return hr;
2052 }
2053
2054 struct displaymodescallback_context
2055 {
2056     LPDDENUMMODESCALLBACK func;
2057     void *context;
2058 };
2059
2060 static HRESULT CALLBACK EnumDisplayModesCallbackThunk(DDSURFACEDESC2 *surface_desc, void *context)
2061 {
2062     struct displaymodescallback_context *cbcontext = context;
2063     DDSURFACEDESC desc;
2064
2065     memcpy(&desc, surface_desc, sizeof(desc));
2066     desc.dwSize = sizeof(desc);
2067
2068     return cbcontext->func(&desc, cbcontext->context);
2069 }
2070
2071 /*****************************************************************************
2072  * IDirectDraw7::EnumDisplayModes
2073  *
2074  * Enumerates the supported Display modes. The modes can be filtered with
2075  * the DDSD parameter.
2076  *
2077  * Params:
2078  *  Flags: can be DDEDM_REFRESHRATES and DDEDM_STANDARDVGAMODES. For old ddraw
2079  *         versions (3 and older?) this is reserved and must be 0.
2080  *  DDSD: Surface description to filter the modes
2081  *  Context: Pointer passed back to the callback function
2082  *  cb: Application-provided callback function
2083  *
2084  * Returns:
2085  *  DD_OK on success
2086  *  DDERR_INVALIDPARAMS if the callback wasn't set
2087  *
2088  *****************************************************************************/
2089 static HRESULT WINAPI ddraw7_EnumDisplayModes(IDirectDraw7 *iface, DWORD Flags,
2090         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMMODESCALLBACK2 cb)
2091 {
2092     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
2093     unsigned int modenum, fmt;
2094     WINED3DDISPLAYMODE mode;
2095     DDSURFACEDESC2 callback_sd;
2096     WINED3DDISPLAYMODE *enum_modes = NULL;
2097     unsigned enum_mode_count = 0, enum_mode_array_size = 0;
2098     DDPIXELFORMAT pixelformat;
2099
2100     static const enum wined3d_format_id checkFormatList[] =
2101     {
2102         WINED3DFMT_B8G8R8X8_UNORM,
2103         WINED3DFMT_B5G6R5_UNORM,
2104         WINED3DFMT_P8_UINT,
2105     };
2106
2107     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2108             iface, Flags, DDSD, Context, cb);
2109
2110     EnterCriticalSection(&ddraw_cs);
2111     /* This looks sane */
2112     if(!cb)
2113     {
2114         LeaveCriticalSection(&ddraw_cs);
2115         return DDERR_INVALIDPARAMS;
2116     }
2117
2118     if(!(Flags & DDEDM_REFRESHRATES))
2119     {
2120         enum_mode_array_size = 16;
2121         enum_modes = HeapAlloc(GetProcessHeap(), 0, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
2122         if (!enum_modes)
2123         {
2124             ERR("Out of memory\n");
2125             LeaveCriticalSection(&ddraw_cs);
2126             return DDERR_OUTOFMEMORY;
2127         }
2128     }
2129
2130     pixelformat.dwSize = sizeof(pixelformat);
2131     for(fmt = 0; fmt < (sizeof(checkFormatList) / sizeof(checkFormatList[0])); fmt++)
2132     {
2133         modenum = 0;
2134         while (wined3d_enum_adapter_modes(This->wineD3D, WINED3DADAPTER_DEFAULT,
2135                 checkFormatList[fmt], modenum++, &mode) == WINED3D_OK)
2136         {
2137             PixelFormat_WineD3DtoDD(&pixelformat, mode.Format);
2138             if(DDSD)
2139             {
2140                 if(DDSD->dwFlags & DDSD_WIDTH && mode.Width != DDSD->dwWidth) continue;
2141                 if(DDSD->dwFlags & DDSD_HEIGHT && mode.Height != DDSD->dwHeight) continue;
2142                 if(DDSD->dwFlags & DDSD_REFRESHRATE && mode.RefreshRate != DDSD->u2.dwRefreshRate) continue;
2143                 if (DDSD->dwFlags & DDSD_PIXELFORMAT &&
2144                         pixelformat.u1.dwRGBBitCount != DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount) continue;
2145             }
2146
2147             if(!(Flags & DDEDM_REFRESHRATES))
2148             {
2149                 /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
2150                  * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
2151                  * to be reduced to a single unique result in such case.
2152                  */
2153                 BOOL found = FALSE;
2154                 unsigned i;
2155
2156                 for (i = 0; i < enum_mode_count; i++)
2157                 {
2158                     if(enum_modes[i].Width == mode.Width && enum_modes[i].Height == mode.Height &&
2159                        enum_modes[i].Format == mode.Format)
2160                     {
2161                         found = TRUE;
2162                         break;
2163                     }
2164                 }
2165
2166                 if(found) continue;
2167             }
2168
2169             memset(&callback_sd, 0, sizeof(callback_sd));
2170             callback_sd.dwSize = sizeof(callback_sd);
2171             callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2172
2173             callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH|DDSD_REFRESHRATE;
2174             if(Flags & DDEDM_REFRESHRATES)
2175             {
2176                 callback_sd.u2.dwRefreshRate = mode.RefreshRate;
2177             }
2178
2179             callback_sd.dwWidth = mode.Width;
2180             callback_sd.dwHeight = mode.Height;
2181
2182             callback_sd.u4.ddpfPixelFormat=pixelformat;
2183
2184             /* Calc pitch and DWORD align like MSDN says */
2185             callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.Width;
2186             callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;
2187
2188             TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
2189               callback_sd.u2.dwRefreshRate);
2190
2191             if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
2192             {
2193                 TRACE("Application asked to terminate the enumeration\n");
2194                 HeapFree(GetProcessHeap(), 0, enum_modes);
2195                 LeaveCriticalSection(&ddraw_cs);
2196                 return DD_OK;
2197             }
2198
2199             if(!(Flags & DDEDM_REFRESHRATES))
2200             {
2201                 if (enum_mode_count == enum_mode_array_size)
2202                 {
2203                     WINED3DDISPLAYMODE *new_enum_modes;
2204
2205                     enum_mode_array_size *= 2;
2206                     new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
2207
2208                     if (!new_enum_modes)
2209                     {
2210                         ERR("Out of memory\n");
2211                         HeapFree(GetProcessHeap(), 0, enum_modes);
2212                         LeaveCriticalSection(&ddraw_cs);
2213                         return DDERR_OUTOFMEMORY;
2214                     }
2215
2216                     enum_modes = new_enum_modes;
2217                 }
2218
2219                 enum_modes[enum_mode_count++] = mode;
2220             }
2221         }
2222     }
2223
2224     TRACE("End of enumeration\n");
2225     HeapFree(GetProcessHeap(), 0, enum_modes);
2226     LeaveCriticalSection(&ddraw_cs);
2227     return DD_OK;
2228 }
2229
2230 static HRESULT WINAPI ddraw4_EnumDisplayModes(IDirectDraw4 *iface, DWORD flags,
2231         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMMODESCALLBACK2 callback)
2232 {
2233     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2234
2235     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2236             iface, flags, surface_desc, context, callback);
2237
2238     return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, surface_desc, context, callback);
2239 }
2240
2241 static HRESULT WINAPI ddraw3_EnumDisplayModes(IDirectDraw3 *iface, DWORD flags,
2242         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2243 {
2244     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
2245     struct displaymodescallback_context cbcontext;
2246
2247     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2248             iface, flags, surface_desc, context, callback);
2249
2250     cbcontext.func = callback;
2251     cbcontext.context = context;
2252
2253     return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
2254             &cbcontext, EnumDisplayModesCallbackThunk);
2255 }
2256
2257 static HRESULT WINAPI ddraw2_EnumDisplayModes(IDirectDraw2 *iface, DWORD flags,
2258         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2259 {
2260     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
2261     struct displaymodescallback_context cbcontext;
2262
2263     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2264             iface, flags, surface_desc, context, callback);
2265
2266     cbcontext.func = callback;
2267     cbcontext.context = context;
2268
2269     return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
2270             &cbcontext, EnumDisplayModesCallbackThunk);
2271 }
2272
2273 static HRESULT WINAPI ddraw1_EnumDisplayModes(IDirectDraw *iface, DWORD flags,
2274         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2275 {
2276     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
2277     struct displaymodescallback_context cbcontext;
2278
2279     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2280             iface, flags, surface_desc, context, callback);
2281
2282     cbcontext.func = callback;
2283     cbcontext.context = context;
2284
2285     return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
2286             &cbcontext, EnumDisplayModesCallbackThunk);
2287 }
2288
2289 /*****************************************************************************
2290  * IDirectDraw7::EvaluateMode
2291  *
2292  * Used with IDirectDraw7::StartModeTest to test video modes.
2293  * EvaluateMode is used to pass or fail a mode, and continue with the next
2294  * mode
2295  *
2296  * Params:
2297  *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
2298  *  Timeout: Returns the amount of seconds left before the mode would have
2299  *           been failed automatically
2300  *
2301  * Returns:
2302  *  This implementation always DD_OK, because it's a stub
2303  *
2304  *****************************************************************************/
2305 static HRESULT WINAPI ddraw7_EvaluateMode(IDirectDraw7 *iface, DWORD Flags, DWORD *Timeout)
2306 {
2307     FIXME("iface %p, flags %#x, timeout %p stub!\n", iface, Flags, Timeout);
2308
2309     /* When implementing this, implement it in WineD3D */
2310
2311     return DD_OK;
2312 }
2313
2314 /*****************************************************************************
2315  * IDirectDraw7::GetDeviceIdentifier
2316  *
2317  * Returns the device identifier, which gives information about the driver
2318  * Our device identifier is defined at the beginning of this file.
2319  *
2320  * Params:
2321  *  DDDI: Address for the returned structure
2322  *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
2323  *
2324  * Returns:
2325  *  On success it returns DD_OK
2326  *  DDERR_INVALIDPARAMS if DDDI is NULL
2327  *
2328  *****************************************************************************/
2329 static HRESULT WINAPI ddraw7_GetDeviceIdentifier(IDirectDraw7 *iface,
2330         DDDEVICEIDENTIFIER2 *DDDI, DWORD Flags)
2331 {
2332     TRACE("iface %p, device_identifier %p, flags %#x.\n", iface, DDDI, Flags);
2333
2334     if(!DDDI)
2335         return DDERR_INVALIDPARAMS;
2336
2337     /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
2338      * host adapter, if there's a secondary 3D adapter. This doesn't apply
2339      * to any modern hardware, nor is it interesting for Wine, so ignore it.
2340      * Size of DDDEVICEIDENTIFIER2 may be aligned to 8 bytes and thus 4
2341      * bytes too long. So only copy the relevant part of the structure
2342      */
2343
2344     memcpy(DDDI, &deviceidentifier, FIELD_OFFSET(DDDEVICEIDENTIFIER2, dwWHQLLevel) + sizeof(DWORD));
2345     return DD_OK;
2346 }
2347
2348 static HRESULT WINAPI ddraw4_GetDeviceIdentifier(IDirectDraw4 *iface,
2349         DDDEVICEIDENTIFIER *identifier, DWORD flags)
2350 {
2351     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2352     DDDEVICEIDENTIFIER2 identifier2;
2353     HRESULT hr;
2354
2355     TRACE("iface %p, identifier %p, flags %#x.\n", iface, identifier, flags);
2356
2357     hr = ddraw7_GetDeviceIdentifier(&This->IDirectDraw7_iface, &identifier2, flags);
2358     DDRAW_Convert_DDDEVICEIDENTIFIER_2_To_1(&identifier2, identifier);
2359
2360     return hr;
2361 }
2362
2363 /*****************************************************************************
2364  * IDirectDraw7::GetSurfaceFromDC
2365  *
2366  * Returns the Surface for a GDI device context handle.
2367  * Is this related to IDirectDrawSurface::GetDC ???
2368  *
2369  * Params:
2370  *  hdc: hdc to return the surface for
2371  *  Surface: Address to write the surface pointer to
2372  *
2373  * Returns:
2374  *  Always returns DD_OK because it's a stub
2375  *
2376  *****************************************************************************/
2377 static HRESULT WINAPI ddraw7_GetSurfaceFromDC(IDirectDraw7 *iface, HDC hdc,
2378         IDirectDrawSurface7 **Surface)
2379 {
2380     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
2381     struct wined3d_surface *wined3d_surface;
2382     HRESULT hr;
2383
2384     TRACE("iface %p, dc %p, surface %p.\n", iface, hdc, Surface);
2385
2386     if (!Surface) return E_INVALIDARG;
2387
2388     hr = wined3d_device_get_surface_from_dc(This->wined3d_device, hdc, &wined3d_surface);
2389     if (FAILED(hr))
2390     {
2391         TRACE("No surface found for dc %p.\n", hdc);
2392         *Surface = NULL;
2393         return DDERR_NOTFOUND;
2394     }
2395
2396     *Surface = wined3d_surface_get_parent(wined3d_surface);
2397     IDirectDrawSurface7_AddRef(*Surface);
2398     TRACE("Returning surface %p.\n", Surface);
2399     return DD_OK;
2400 }
2401
2402 static HRESULT WINAPI ddraw4_GetSurfaceFromDC(IDirectDraw4 *iface, HDC dc,
2403         IDirectDrawSurface4 **surface)
2404 {
2405     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2406     IDirectDrawSurface7 *surface7;
2407     HRESULT hr;
2408
2409     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2410
2411     if (!surface) return E_INVALIDARG;
2412
2413     hr = ddraw7_GetSurfaceFromDC(&This->IDirectDraw7_iface, dc, &surface7);
2414     *surface = surface7 ? (IDirectDrawSurface4 *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
2415
2416     return hr;
2417 }
2418
2419 static HRESULT WINAPI ddraw3_GetSurfaceFromDC(IDirectDraw3 *iface, HDC dc,
2420         IDirectDrawSurface **surface)
2421 {
2422     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
2423
2424     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2425
2426     return ddraw7_GetSurfaceFromDC(&This->IDirectDraw7_iface, dc, (IDirectDrawSurface7 **)surface);
2427 }
2428
2429 /*****************************************************************************
2430  * IDirectDraw7::RestoreAllSurfaces
2431  *
2432  * Calls the restore method of all surfaces
2433  *
2434  * Params:
2435  *
2436  * Returns:
2437  *  Always returns DD_OK because it's a stub
2438  *
2439  *****************************************************************************/
2440 static HRESULT WINAPI ddraw7_RestoreAllSurfaces(IDirectDraw7 *iface)
2441 {
2442     FIXME("iface %p stub!\n", iface);
2443
2444     /* This isn't hard to implement: Enumerate all WineD3D surfaces,
2445      * get their parent and call their restore method. Do not implement
2446      * it in WineD3D, as restoring a surface means re-creating the
2447      * WineD3DDSurface
2448      */
2449     return DD_OK;
2450 }
2451
2452 static HRESULT WINAPI ddraw4_RestoreAllSurfaces(IDirectDraw4 *iface)
2453 {
2454     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2455
2456     TRACE("iface %p.\n", iface);
2457
2458     return ddraw7_RestoreAllSurfaces(&This->IDirectDraw7_iface);
2459 }
2460
2461 /*****************************************************************************
2462  * IDirectDraw7::StartModeTest
2463  *
2464  * Tests the specified video modes to update the system registry with
2465  * refresh rate information. StartModeTest starts the mode test,
2466  * EvaluateMode is used to fail or pass a mode. If EvaluateMode
2467  * isn't called within 15 seconds, the mode is failed automatically
2468  *
2469  * As refresh rates are handled by the X server, I don't think this
2470  * Method is important
2471  *
2472  * Params:
2473  *  Modes: An array of mode specifications
2474  *  NumModes: The number of modes in Modes
2475  *  Flags: Some flags...
2476  *
2477  * Returns:
2478  *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
2479  *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
2480  *  otherwise DD_OK
2481  *
2482  *****************************************************************************/
2483 static HRESULT WINAPI ddraw7_StartModeTest(IDirectDraw7 *iface, SIZE *Modes, DWORD NumModes, DWORD Flags)
2484 {
2485     FIXME("iface %p, modes %p, mode_count %u, flags %#x partial stub!\n",
2486             iface, Modes, NumModes, Flags);
2487
2488     /* This looks sane */
2489     if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;
2490
2491     /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
2492      * As it is not, DDERR_TESTFINISHED is returned
2493      * (hopefully that's correct
2494      *
2495     if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
2496      * well, that value doesn't (yet) exist in the wine headers, so ignore it
2497      */
2498
2499     return DD_OK;
2500 }
2501
2502 /*****************************************************************************
2503  * ddraw_recreate_surfaces_cb
2504  *
2505  * Enumeration callback for ddraw_recreate_surface.
2506  * It re-recreates the WineD3DSurface. It's pretty straightforward
2507  *
2508  *****************************************************************************/
2509 HRESULT WINAPI ddraw_recreate_surfaces_cb(IDirectDrawSurface7 *surf, DDSURFACEDESC2 *desc, void *Context)
2510 {
2511     IDirectDrawSurfaceImpl *surfImpl = (IDirectDrawSurfaceImpl *)surf;
2512     struct wined3d_resource_desc wined3d_desc;
2513     struct wined3d_resource *wined3d_resource;
2514     IDirectDrawImpl *This = surfImpl->ddraw;
2515     struct wined3d_surface *wined3d_surface;
2516     struct wined3d_swapchain *swapchain;
2517     struct wined3d_clipper *clipper;
2518     void *parent;
2519     HRESULT hr;
2520
2521     TRACE("surface %p, surface_desc %p, context %p.\n",
2522             surf, desc, Context);
2523
2524     /* For the enumeration */
2525     IDirectDrawSurface7_Release(surf);
2526
2527     if(surfImpl->ImplType == This->ImplType) return DDENUMRET_OK; /* Continue */
2528
2529     /* Get the objects */
2530     swapchain = surfImpl->wined3d_swapchain;
2531     surfImpl->wined3d_swapchain = NULL;
2532     wined3d_surface = surfImpl->wined3d_surface;
2533
2534     /* get the clipper */
2535     clipper = wined3d_surface_get_clipper(wined3d_surface);
2536
2537     /* Get the surface properties */
2538     wined3d_resource = wined3d_surface_get_resource(wined3d_surface);
2539     wined3d_resource_get_desc(wined3d_resource, &wined3d_desc);
2540
2541     parent = wined3d_surface_get_parent(wined3d_surface);
2542     hr = wined3d_surface_create(This->wined3d_device, wined3d_desc.width, wined3d_desc.height,
2543             wined3d_desc.format, TRUE, FALSE, surfImpl->mipmap_level, wined3d_desc.usage, wined3d_desc.pool,
2544             wined3d_desc.multisample_type, wined3d_desc.multisample_quality, This->ImplType,
2545             parent, &ddraw_surface_wined3d_parent_ops, &surfImpl->wined3d_surface);
2546     if (FAILED(hr))
2547     {
2548         surfImpl->wined3d_surface = wined3d_surface;
2549         return hr;
2550     }
2551
2552     wined3d_surface_set_clipper(surfImpl->wined3d_surface, clipper);
2553
2554     /* TODO: Copy the surface content, except for render targets */
2555
2556     /* If there's a swapchain, it owns the wined3d surfaces. So Destroy
2557      * the swapchain
2558      */
2559     if (swapchain)
2560     {
2561         /* The backbuffers have the swapchain set as well, but the primary
2562          * owns it and destroys it. */
2563         if (surfImpl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
2564             wined3d_device_uninit_gdi(This->wined3d_device);
2565         surfImpl->isRenderTarget = FALSE;
2566     }
2567     else
2568     {
2569         if (!wined3d_surface_decref(wined3d_surface))
2570             TRACE("Surface released successful, next surface\n");
2571         else
2572             ERR("Something's still holding the old WineD3DSurface\n");
2573     }
2574
2575     surfImpl->ImplType = This->ImplType;
2576
2577     return DDENUMRET_OK;
2578 }
2579
2580 /*****************************************************************************
2581  * ddraw_recreate_surfaces
2582  *
2583  * A function, that converts all wineD3DSurfaces to the new implementation type
2584  * It enumerates all surfaces with IWineD3DDevice::EnumSurfaces, creates a
2585  * new WineD3DSurface, copies the content and releases the old surface
2586  *
2587  *****************************************************************************/
2588 static HRESULT ddraw_recreate_surfaces(IDirectDrawImpl *This)
2589 {
2590     DDSURFACEDESC2 desc;
2591     TRACE("(%p): Switch to implementation %d\n", This, This->ImplType);
2592
2593     if(This->ImplType != SURFACE_OPENGL && This->d3d_initialized)
2594     {
2595         /* Should happen almost never */
2596         FIXME("(%p) Switching to non-opengl surfaces with d3d started. Is this a bug?\n", This);
2597         /* Shutdown d3d */
2598         wined3d_device_uninit_3d(This->wined3d_device);
2599     }
2600     /* Contrary: D3D starting is handled by the caller, because it knows the render target */
2601
2602     memset(&desc, 0, sizeof(desc));
2603     desc.dwSize = sizeof(desc);
2604
2605     return IDirectDraw7_EnumSurfaces(&This->IDirectDraw7_iface, 0, &desc, This,
2606             ddraw_recreate_surfaces_cb);
2607 }
2608
2609 /*****************************************************************************
2610  * ddraw_create_surface
2611  *
2612  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
2613  * with the passed parameters.
2614  *
2615  * Params:
2616  *  DDSD: Description of the surface to create
2617  *  Surf: Address to store the interface pointer at
2618  *
2619  * Returns:
2620  *  DD_OK on success
2621  *
2622  *****************************************************************************/
2623 static HRESULT ddraw_create_surface(IDirectDrawImpl *This, DDSURFACEDESC2 *pDDSD,
2624         IDirectDrawSurfaceImpl **ppSurf, UINT level)
2625 {
2626     WINED3DSURFTYPE ImplType = This->ImplType;
2627     HRESULT hr;
2628
2629     TRACE("ddraw %p, surface_desc %p, surface %p, level %u.\n",
2630             This, pDDSD, ppSurf, level);
2631
2632     if (TRACE_ON(ddraw))
2633     {
2634         TRACE(" (%p) Requesting surface desc :\n", This);
2635         DDRAW_dump_surface_desc(pDDSD);
2636     }
2637
2638     /* Select the surface type, if it wasn't choosen yet */
2639     if(ImplType == SURFACE_UNKNOWN)
2640     {
2641         /* Use GL Surfaces if a D3DDEVICE Surface is requested */
2642         if(pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2643         {
2644             TRACE("(%p) Choosing GL surfaces because a 3DDEVICE Surface was requested\n", This);
2645             ImplType = SURFACE_OPENGL;
2646         }
2647
2648         /* Otherwise use GDI surfaces for now */
2649         else
2650         {
2651             TRACE("(%p) Choosing GDI surfaces for 2D rendering\n", This);
2652             ImplType = SURFACE_GDI;
2653         }
2654
2655         /* Policy if all surface implementations are available:
2656          * First, check if a default type was set with winecfg. If not,
2657          * try Xrender surfaces, and use them if they work. Next, check if
2658          * accelerated OpenGL is available, and use GL surfaces in this
2659          * case. If all else fails, use GDI surfaces. If a 3DDEVICE surface
2660          * was created, always use OpenGL surfaces.
2661          *
2662          * (Note: Xrender surfaces are not implemented for now, the
2663          * unaccelerated implementation uses GDI to render in Software)
2664          */
2665
2666         /* Store the type. If it needs to be changed, all WineD3DSurfaces have to
2667          * be re-created. This could be done with IDirectDrawSurface7::Restore
2668          */
2669         This->ImplType = ImplType;
2670     }
2671     else
2672     {
2673         if ((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2674                 && (This->ImplType != SURFACE_OPENGL)
2675                 && DefaultSurfaceType == SURFACE_UNKNOWN)
2676         {
2677             /* We have to change to OpenGL,
2678              * and re-create all WineD3DSurfaces
2679              */
2680             ImplType = SURFACE_OPENGL;
2681             This->ImplType = ImplType;
2682             TRACE("(%p) Re-creating all surfaces\n", This);
2683             ddraw_recreate_surfaces(This);
2684             TRACE("(%p) Done recreating all surfaces\n", This);
2685         }
2686         else if(This->ImplType != SURFACE_OPENGL && pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2687         {
2688             WARN("The application requests a 3D capable surface, but a non-opengl surface was set in the registry\n");
2689             /* Do not fail surface creation, only fail 3D device creation */
2690         }
2691     }
2692
2693     /* Create the Surface object */
2694     *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
2695     if(!*ppSurf)
2696     {
2697         ERR("(%p) Error allocating memory for a surface\n", This);
2698         return DDERR_OUTOFVIDEOMEMORY;
2699     }
2700
2701     hr = ddraw_surface_init(*ppSurf, This, pDDSD, level, ImplType);
2702     if (FAILED(hr))
2703     {
2704         WARN("Failed to initialize surface, hr %#x.\n", hr);
2705         HeapFree(GetProcessHeap(), 0, *ppSurf);
2706         return hr;
2707     }
2708
2709     /* Increase the surface counter, and attach the surface */
2710     InterlockedIncrement(&This->surfaces);
2711     list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
2712
2713     TRACE("Created surface %p.\n", *ppSurf);
2714
2715     return DD_OK;
2716 }
2717 /*****************************************************************************
2718  * CreateAdditionalSurfaces
2719  *
2720  * Creates a new mipmap chain.
2721  *
2722  * Params:
2723  *  root: Root surface to attach the newly created chain to
2724  *  count: number of surfaces to create
2725  *  DDSD: Description of the surface. Intentionally not a pointer to avoid side
2726  *        effects on the caller
2727  *  CubeFaceRoot: Whether the new surface is a root of a cube map face. This
2728  *                creates an additional surface without the mipmapping flags
2729  *
2730  *****************************************************************************/
2731 static HRESULT
2732 CreateAdditionalSurfaces(IDirectDrawImpl *This,
2733                          IDirectDrawSurfaceImpl *root,
2734                          UINT count,
2735                          DDSURFACEDESC2 DDSD,
2736                          BOOL CubeFaceRoot)
2737 {
2738     UINT i, j, level = 0;
2739     HRESULT hr;
2740     IDirectDrawSurfaceImpl *last = root;
2741
2742     for(i = 0; i < count; i++)
2743     {
2744         IDirectDrawSurfaceImpl *object2 = NULL;
2745
2746         /* increase the mipmap level, but only if a mipmap is created
2747          * In this case, also halve the size
2748          */
2749         if(DDSD.ddsCaps.dwCaps & DDSCAPS_MIPMAP && !CubeFaceRoot)
2750         {
2751             level++;
2752             if(DDSD.dwWidth > 1) DDSD.dwWidth /= 2;
2753             if(DDSD.dwHeight > 1) DDSD.dwHeight /= 2;
2754             /* Set the mipmap sublevel flag according to msdn */
2755             DDSD.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2756         }
2757         else
2758         {
2759             DDSD.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2760         }
2761         CubeFaceRoot = FALSE;
2762
2763         hr = ddraw_create_surface(This, &DDSD, &object2, level);
2764         if(hr != DD_OK)
2765         {
2766             return hr;
2767         }
2768
2769         /* Add the new surface to the complex attachment array */
2770         for(j = 0; j < MAX_COMPLEX_ATTACHED; j++)
2771         {
2772             if(last->complex_array[j]) continue;
2773             last->complex_array[j] = object2;
2774             break;
2775         }
2776         last = object2;
2777
2778         /* Remove the (possible) back buffer cap from the new surface description,
2779          * because only one surface in the flipping chain is a back buffer, one
2780          * is a front buffer, the others are just primary surfaces.
2781          */
2782         DDSD.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2783     }
2784     return DD_OK;
2785 }
2786
2787 /* Must set all attached surfaces (e.g. mipmaps) versions as well */
2788 static void ddraw_set_surface_version(IDirectDrawSurfaceImpl *surface, UINT version)
2789 {
2790     unsigned int i;
2791
2792     TRACE("surface %p, version %u -> %u.\n", surface, surface->version, version);
2793
2794     surface->version = version;
2795     for (i = 0; i < MAX_COMPLEX_ATTACHED; ++i)
2796     {
2797         if (!surface->complex_array[i]) break;
2798         ddraw_set_surface_version(surface->complex_array[i], version);
2799     }
2800     while ((surface = surface->next_attached))
2801     {
2802         ddraw_set_surface_version(surface, version);
2803     }
2804 }
2805
2806 /*****************************************************************************
2807  * ddraw_attach_d3d_device
2808  *
2809  * Initializes the D3D capabilities of WineD3D
2810  *
2811  * Params:
2812  *  primary: The primary surface for D3D
2813  *
2814  * Returns
2815  *  DD_OK on success,
2816  *  DDERR_* otherwise
2817  *
2818  *****************************************************************************/
2819 static HRESULT ddraw_attach_d3d_device(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2820 {
2821     WINED3DPRESENT_PARAMETERS localParameters;
2822     HWND window = ddraw->dest_window;
2823     HRESULT hr;
2824
2825     TRACE("ddraw %p, primary %p.\n", ddraw, primary);
2826
2827     if (!window || window == GetDesktopWindow())
2828     {
2829         window = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "Hidden D3D Window",
2830                 WS_DISABLED, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
2831                 NULL, NULL, NULL, NULL);
2832         if (!window)
2833         {
2834             ERR("Failed to create window, last error %#x.\n", GetLastError());
2835             return E_FAIL;
2836         }
2837
2838         ShowWindow(window, SW_HIDE);   /* Just to be sure */
2839         WARN("No window for the Direct3DDevice, created hidden window %p.\n", window);
2840     }
2841     else
2842     {
2843         TRACE("Using existing window %p for Direct3D rendering.\n", window);
2844     }
2845     ddraw->d3d_window = window;
2846
2847     /* Store the future Render Target surface */
2848     ddraw->d3d_target = primary;
2849
2850     /* Use the surface description for the device parameters, not the device
2851      * settings. The application might render to an offscreen surface. */
2852     localParameters.BackBufferWidth = primary->surface_desc.dwWidth;
2853     localParameters.BackBufferHeight = primary->surface_desc.dwHeight;
2854     localParameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2855     localParameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2856             ? primary->surface_desc.dwBackBufferCount : 0;
2857     localParameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2858     localParameters.MultiSampleQuality = 0;
2859     localParameters.SwapEffect = WINED3DSWAPEFFECT_COPY;
2860     localParameters.hDeviceWindow = window;
2861     localParameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2862     localParameters.EnableAutoDepthStencil = TRUE;
2863     localParameters.AutoDepthStencilFormat = WINED3DFMT_D16_UNORM;
2864     localParameters.Flags = 0;
2865     localParameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2866     localParameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2867     localParameters.AutoRestoreDisplayMode = FALSE;
2868
2869     /* Set this NOW, otherwise creating the depth stencil surface will cause a
2870      * recursive loop until ram or emulated video memory is full. */
2871     ddraw->d3d_initialized = TRUE;
2872     hr = wined3d_device_init_3d(ddraw->wined3d_device, &localParameters);
2873     if (FAILED(hr))
2874     {
2875         ddraw->d3d_target = NULL;
2876         ddraw->d3d_initialized = FALSE;
2877         return hr;
2878     }
2879
2880     ddraw->declArraySize = 2;
2881     ddraw->decls = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw->decls) * ddraw->declArraySize);
2882     if (!ddraw->decls)
2883     {
2884         ERR("Error allocating an array for the converted vertex decls.\n");
2885         ddraw->declArraySize = 0;
2886         hr = wined3d_device_uninit_3d(ddraw->wined3d_device);
2887         return E_OUTOFMEMORY;
2888     }
2889
2890     TRACE("Successfully initialized 3D.\n");
2891
2892     return DD_OK;
2893 }
2894
2895 static HRESULT ddraw_create_gdi_swapchain(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2896 {
2897     WINED3DPRESENT_PARAMETERS presentation_parameters;
2898     HWND window;
2899     HRESULT hr;
2900
2901     window = ddraw->dest_window;
2902
2903     memset(&presentation_parameters, 0, sizeof(presentation_parameters));
2904
2905     /* Use the surface description for the device parameters, not the device
2906      * settings. The application might render to an offscreen surface. */
2907     presentation_parameters.BackBufferWidth = primary->surface_desc.dwWidth;
2908     presentation_parameters.BackBufferHeight = primary->surface_desc.dwHeight;
2909     presentation_parameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2910     presentation_parameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2911             ? primary->surface_desc.dwBackBufferCount : 0;
2912     presentation_parameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2913     presentation_parameters.MultiSampleQuality = 0;
2914     presentation_parameters.SwapEffect = WINED3DSWAPEFFECT_FLIP;
2915     presentation_parameters.hDeviceWindow = window;
2916     presentation_parameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2917     presentation_parameters.EnableAutoDepthStencil = FALSE; /* Not on GDI swapchains */
2918     presentation_parameters.AutoDepthStencilFormat = 0;
2919     presentation_parameters.Flags = 0;
2920     presentation_parameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2921     presentation_parameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2922     presentation_parameters.AutoRestoreDisplayMode = FALSE;
2923
2924     ddraw->d3d_target = primary;
2925     hr = wined3d_device_init_gdi(ddraw->wined3d_device, &presentation_parameters);
2926     ddraw->d3d_target = NULL;
2927     if (FAILED(hr))
2928     {
2929         WARN("Failed to initialize GDI ddraw implementation, hr %#x.\n", hr);
2930         primary->wined3d_swapchain = NULL;
2931     }
2932
2933     return hr;
2934 }
2935
2936 /*****************************************************************************
2937  * IDirectDraw7::CreateSurface
2938  *
2939  * Creates a new IDirectDrawSurface object and returns its interface.
2940  *
2941  * The surface connections with wined3d are a bit tricky. Basically it works
2942  * like this:
2943  *
2944  * |------------------------|               |-----------------|
2945  * | DDraw surface          |               | WineD3DSurface  |
2946  * |                        |               |                 |
2947  * |        WineD3DSurface  |-------------->|                 |
2948  * |        Child           |<------------->| Parent          |
2949  * |------------------------|               |-----------------|
2950  *
2951  * The DDraw surface is the parent of the wined3d surface, and it releases
2952  * the WineD3DSurface when the ddraw surface is destroyed.
2953  *
2954  * However, for all surfaces which can be in a container in WineD3D,
2955  * we have to do this. These surfaces are usually complex surfaces,
2956  * so this concerns primary surfaces with a front and a back buffer,
2957  * and textures.
2958  *
2959  * |------------------------|               |-----------------|
2960  * | DDraw surface          |               | Container       |
2961  * |                        |               |                 |
2962  * |                  Child |<------------->| Parent          |
2963  * |                Texture |<------------->|                 |
2964  * |         WineD3DSurface |<----|         |          Levels |<--|
2965  * | Complex connection     |     |         |                 |   |
2966  * |------------------------|     |         |-----------------|   |
2967  *  ^                             |                               |
2968  *  |                             |                               |
2969  *  |                             |                               |
2970  *  |    |------------------|     |         |-----------------|   |
2971  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2972  *  |    |                  |               |                 |   |
2973  *  |    |            Child |<------------->| Parent          |   |
2974  *  |    |                  |               |       Container |<--|
2975  *  |    |------------------|               |-----------------|   |
2976  *  |                                                             |
2977  *  |   |----------------------|                                  |
2978  *  |   | DDraw surface 2      |                                  |
2979  *  |   |                      |                                  |
2980  *  |<->| Complex root   Child |                                  |
2981  *  |   |              Texture |                                  |
2982  *  |   |       WineD3DSurface |<----|                            |
2983  *  |   |----------------------|     |                            |
2984  *  |                                |                            |
2985  *  |    |---------------------|     |      |-----------------|   |
2986  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2987  *  |    |                     |            |                 |   |
2988  *  |    |               Child |<---------->| Parent          |   |
2989  *  |    |---------------------|            |       Container |<--|
2990  *  |                                       |-----------------|   |
2991  *  |                                                             |
2992  *  |             ---More surfaces can follow---                  |
2993  *
2994  * The reason is that the IWineD3DSwapchain(render target container)
2995  * and the IWineD3DTexure(Texture container) release the parents
2996  * of their surface's children, but by releasing the complex root
2997  * the surfaces which are complexly attached to it are destroyed
2998  * too. See IDirectDrawSurface::Release for a more detailed
2999  * explanation.
3000  *
3001  * Params:
3002  *  DDSD: Description of the surface to create
3003  *  Surf: Address to store the interface pointer at
3004  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
3005  *            aggregation, so it has to be NULL
3006  *
3007  * Returns:
3008  *  DD_OK on success
3009  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3010  *  DDERR_* if an error occurs
3011  *
3012  *****************************************************************************/
3013 static HRESULT CreateSurface(IDirectDrawImpl *ddraw, DDSURFACEDESC2 *DDSD,
3014         IDirectDrawSurface7 **Surf, IUnknown *UnkOuter)
3015 {
3016     IDirectDrawSurfaceImpl *object = NULL;
3017     HRESULT hr;
3018     LONG extra_surfaces = 0;
3019     DDSURFACEDESC2 desc2;
3020     WINED3DDISPLAYMODE Mode;
3021     const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
3022
3023     TRACE("ddraw %p, surface_desc %p, surface %p, outer_unknown %p.\n", ddraw, DDSD, Surf, UnkOuter);
3024
3025     /* Some checks before we start */
3026     if (TRACE_ON(ddraw))
3027     {
3028         TRACE(" (%p) Requesting surface desc :\n", ddraw);
3029         DDRAW_dump_surface_desc(DDSD);
3030     }
3031     EnterCriticalSection(&ddraw_cs);
3032
3033     if (UnkOuter != NULL)
3034     {
3035         FIXME("(%p) : outer != NULL?\n", ddraw);
3036         LeaveCriticalSection(&ddraw_cs);
3037         return CLASS_E_NOAGGREGATION; /* unchecked */
3038     }
3039
3040     if (Surf == NULL)
3041     {
3042         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", ddraw);
3043         LeaveCriticalSection(&ddraw_cs);
3044         return E_POINTER; /* unchecked */
3045     }
3046
3047     if (!(DDSD->dwFlags & DDSD_CAPS))
3048     {
3049         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
3050         DDSD->dwFlags |= DDSD_CAPS;
3051     }
3052
3053     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
3054     {
3055         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
3056         DDSD->dwFlags &= ~DDSD_LPSURFACE;
3057     }
3058
3059     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
3060     {
3061         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
3062         WARN("(%p) Null surface pointer specified, ignore it!\n", ddraw);
3063         DDSD->dwFlags &= ~DDSD_LPSURFACE;
3064     }
3065
3066     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
3067        !(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
3068     {
3069         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n",
3070                 ddraw);
3071         *Surf = NULL;
3072         LeaveCriticalSection(&ddraw_cs);
3073         return DDERR_NOEXCLUSIVEMODE;
3074     }
3075
3076     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE))
3077     {
3078         WARN("Application wanted to create back buffer primary surface\n");
3079         LeaveCriticalSection(&ddraw_cs);
3080         return DDERR_INVALIDCAPS;
3081     }
3082
3083     if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
3084     {
3085         /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
3086         WARN("Application tries to put the surface in both system and video memory\n");
3087         LeaveCriticalSection(&ddraw_cs);
3088         *Surf = NULL;
3089         return DDERR_INVALIDCAPS;
3090     }
3091
3092     /* Check cube maps but only if the size includes them */
3093     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
3094     {
3095         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
3096            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
3097         {
3098             WARN("Cube map faces requested without cube map flag\n");
3099             LeaveCriticalSection(&ddraw_cs);
3100             return DDERR_INVALIDCAPS;
3101         }
3102         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
3103            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
3104         {
3105             WARN("Cube map without faces requested\n");
3106             LeaveCriticalSection(&ddraw_cs);
3107             return DDERR_INVALIDPARAMS;
3108         }
3109
3110         /* Quick tests confirm those can be created, but we don't do that yet */
3111         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
3112            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
3113         {
3114             FIXME("Partial cube maps not supported yet\n");
3115         }
3116     }
3117
3118     /* According to the msdn this flag is ignored by CreateSurface */
3119     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
3120         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
3121
3122     /* Modify some flags */
3123     memset(&desc2, 0, sizeof(desc2));
3124     desc2.dwSize = sizeof(desc2);   /* For the struct copy */
3125     DD_STRUCT_COPY_BYSIZE(&desc2, DDSD);
3126     desc2.dwSize = sizeof(desc2);   /* To override a possibly smaller size */
3127     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
3128
3129     /* Get the video mode from WineD3D - we will need it */
3130     hr = wined3d_device_get_display_mode(ddraw->wined3d_device, 0, &Mode);
3131     if (FAILED(hr))
3132     {
3133         ERR("Failed to read display mode from wined3d\n");
3134         switch(ddraw->orig_bpp)
3135         {
3136             case 8:
3137                 Mode.Format = WINED3DFMT_P8_UINT;
3138                 break;
3139
3140             case 15:
3141                 Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;
3142                 break;
3143
3144             case 16:
3145                 Mode.Format = WINED3DFMT_B5G6R5_UNORM;
3146                 break;
3147
3148             case 24:
3149                 Mode.Format = WINED3DFMT_B8G8R8_UNORM;
3150                 break;
3151
3152             case 32:
3153                 Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;
3154                 break;
3155         }
3156         Mode.Width = ddraw->orig_width;
3157         Mode.Height = ddraw->orig_height;
3158     }
3159
3160     /* No pixelformat given? Use the current screen format */
3161     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
3162     {
3163         desc2.dwFlags |= DDSD_PIXELFORMAT;
3164         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
3165
3166         /* Wait: It could be a Z buffer */
3167         if(desc2.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
3168         {
3169             switch(desc2.u2.dwMipMapCount) /* Who had this glorious idea? */
3170             {
3171                 case 15:
3172                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_S1_UINT_D15_UNORM);
3173                     break;
3174                 case 16:
3175                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D16_UNORM);
3176                     break;
3177                 case 24:
3178                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_X8D24_UNORM);
3179                     break;
3180                 case 32:
3181                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D32_UNORM);
3182                     break;
3183                 default:
3184                     ERR("Unknown Z buffer bit depth\n");
3185             }
3186         }
3187         else
3188         {
3189             PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
3190         }
3191     }
3192
3193     /* No Width or no Height? Use the original screen size
3194      */
3195     if(!(desc2.dwFlags & DDSD_WIDTH) ||
3196        !(desc2.dwFlags & DDSD_HEIGHT) )
3197     {
3198         /* Invalid for non-render targets */
3199         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
3200         {
3201             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
3202             *Surf = NULL;
3203             LeaveCriticalSection(&ddraw_cs);
3204             return DDERR_INVALIDPARAMS;
3205         }
3206
3207         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
3208         desc2.dwWidth = Mode.Width;
3209         desc2.dwHeight = Mode.Height;
3210     }
3211
3212     if (!desc2.dwWidth || !desc2.dwHeight)
3213     {
3214         LeaveCriticalSection(&ddraw_cs);
3215         return DDERR_INVALIDPARAMS;
3216     }
3217
3218     /* Mipmap count fixes */
3219     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
3220     {
3221         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
3222         {
3223             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
3224             {
3225                 /* Mipmap count is given, should not be 0 */
3226                 if( desc2.u2.dwMipMapCount == 0 )
3227                 {
3228                     LeaveCriticalSection(&ddraw_cs);
3229                     return DDERR_INVALIDPARAMS;
3230                 }
3231             }
3232             else
3233             {
3234                 /* Undocumented feature: Create sublevels until
3235                  * either the width or the height is 1
3236                  */
3237                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
3238                             desc2.dwWidth : desc2.dwHeight;
3239                 desc2.u2.dwMipMapCount = 0;
3240                 while( min )
3241                 {
3242                     desc2.u2.dwMipMapCount += 1;
3243                     min >>= 1;
3244                 }
3245             }
3246         }
3247         else
3248         {
3249             /* Not-complex mipmap -> Mipmapcount = 1 */
3250             desc2.u2.dwMipMapCount = 1;
3251         }
3252         extra_surfaces = desc2.u2.dwMipMapCount - 1;
3253
3254         /* There's a mipmap count in the created surface in any case */
3255         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
3256     }
3257     /* If no mipmap is given, the texture has only one level */
3258
3259     /* The first surface is a front buffer, the back buffer is created afterwards */
3260     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
3261     {
3262         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
3263     }
3264
3265     /* The root surface in a cube map is positive x */
3266     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3267     {
3268         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3269         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3270     }
3271
3272     /* Create the first surface */
3273     hr = ddraw_create_surface(ddraw, &desc2, &object, 0);
3274     if (FAILED(hr))
3275     {
3276         WARN("ddraw_create_surface failed, hr %#x.\n", hr);
3277         LeaveCriticalSection(&ddraw_cs);
3278         return hr;
3279     }
3280     object->is_complex_root = TRUE;
3281
3282     *Surf = (IDirectDrawSurface7 *)object;
3283
3284     /* Create Additional surfaces if necessary
3285      * This applies to Primary surfaces which have a back buffer count
3286      * set, but not to mipmap textures. In case of Mipmap textures,
3287      * wineD3D takes care of the creation of additional surfaces
3288      */
3289     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
3290     {
3291         extra_surfaces = DDSD->dwBackBufferCount;
3292         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
3293         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
3294         desc2.dwBackBufferCount = 0;
3295     }
3296
3297     hr = DD_OK;
3298     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3299     {
3300         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3301         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
3302         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3303         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
3304         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
3305         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3306         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
3307         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
3308         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3309         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
3310         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
3311         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3312         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
3313         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
3314         hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3315         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
3316         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3317     }
3318
3319     hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces, desc2, FALSE);
3320     if(hr != DD_OK)
3321     {
3322         /* This destroys and possibly created surfaces too */
3323         IDirectDrawSurface_Release((IDirectDrawSurface7 *)object);
3324         LeaveCriticalSection(&ddraw_cs);
3325         return hr;
3326     }
3327
3328     /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
3329      * But attach the d3ddevice only if the currently created surface was
3330      * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
3331      * The only case I can think of where this doesn't apply is when a
3332      * 2D app was configured by the user to run with OpenGL and it didn't create
3333      * the render target as first surface. In this case the render target creation
3334      * will cause the 3D init.
3335      */
3336     if( (ddraw->ImplType == SURFACE_OPENGL) && !(ddraw->d3d_initialized) &&
3337         desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE) )
3338     {
3339         IDirectDrawSurfaceImpl *target = object, *surface;
3340         struct list *entry;
3341
3342         /* Search for the primary to use as render target */
3343         LIST_FOR_EACH(entry, &ddraw->surface_list)
3344         {
3345             surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3346             if((surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER)) ==
3347                (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER))
3348             {
3349                 /* found */
3350                 target = surface;
3351                 TRACE("Using primary %p as render target\n", target);
3352                 break;
3353             }
3354         }
3355
3356         TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", ddraw, target);
3357         hr = ddraw_attach_d3d_device(ddraw, target);
3358         if (hr != D3D_OK)
3359         {
3360             IDirectDrawSurfaceImpl *release_surf;
3361             ERR("ddraw_attach_d3d_device failed, hr %#x\n", hr);
3362             *Surf = NULL;
3363
3364             /* The before created surface structures are in an incomplete state here.
3365              * WineD3D holds the reference on the IParents, and it released them on the failure
3366              * already. So the regular release method implementation would fail on the attempt
3367              * to destroy either the IParents or the swapchain. So free the surface here.
3368              * The surface structure here is a list, not a tree, because onscreen targets
3369              * cannot be cube textures
3370              */
3371             while(object)
3372             {
3373                 release_surf = object;
3374                 object = object->complex_array[0];
3375                 ddraw_surface_destroy(release_surf);
3376             }
3377             LeaveCriticalSection(&ddraw_cs);
3378             return hr;
3379         }
3380     }
3381     else if(!(ddraw->d3d_initialized) && desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
3382     {
3383         ddraw_create_gdi_swapchain(ddraw, object);
3384     }
3385
3386     /* Addref the ddraw interface to keep an reference for each surface */
3387     IDirectDraw7_AddRef(&ddraw->IDirectDraw7_iface);
3388     object->ifaceToRelease = (IUnknown *)&ddraw->IDirectDraw7_iface;
3389
3390     /* Create a WineD3DTexture if a texture was requested */
3391     if (desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
3392     {
3393         ddraw->tex_root = object;
3394         ddraw_surface_create_texture(object);
3395         ddraw->tex_root = NULL;
3396     }
3397
3398     LeaveCriticalSection(&ddraw_cs);
3399     return hr;
3400 }
3401
3402 static HRESULT WINAPI ddraw7_CreateSurface(IDirectDraw7 *iface, DDSURFACEDESC2 *surface_desc,
3403         IDirectDrawSurface7 **surface, IUnknown *outer_unknown)
3404 {
3405     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3406
3407     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3408             iface, surface_desc, surface, outer_unknown);
3409
3410     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3411     {
3412         WARN("Application supplied invalid surface descriptor\n");
3413         return DDERR_INVALIDPARAMS;
3414     }
3415
3416     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3417     {
3418         if (TRACE_ON(ddraw))
3419         {
3420             TRACE(" (%p) Requesting surface desc :\n", iface);
3421             DDRAW_dump_surface_desc(surface_desc);
3422         }
3423
3424         WARN("Application tried to create an explicit front or back buffer\n");
3425         return DDERR_INVALIDCAPS;
3426     }
3427
3428     return CreateSurface(This, surface_desc, surface, outer_unknown);
3429 }
3430
3431 static HRESULT WINAPI ddraw4_CreateSurface(IDirectDraw4 *iface,
3432         DDSURFACEDESC2 *surface_desc, IDirectDrawSurface4 **surface, IUnknown *outer_unknown)
3433 {
3434     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3435     IDirectDrawSurfaceImpl *impl;
3436     HRESULT hr;
3437
3438     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3439             iface, surface_desc, surface, outer_unknown);
3440
3441     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3442     {
3443         WARN("Application supplied invalid surface descriptor\n");
3444         return DDERR_INVALIDPARAMS;
3445     }
3446
3447     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3448     {
3449         if (TRACE_ON(ddraw))
3450         {
3451             TRACE(" (%p) Requesting surface desc :\n", iface);
3452             DDRAW_dump_surface_desc(surface_desc);
3453         }
3454
3455         WARN("Application tried to create an explicit front or back buffer\n");
3456         return DDERR_INVALIDCAPS;
3457     }
3458
3459     hr = CreateSurface(This, surface_desc, (IDirectDrawSurface7 **)surface, outer_unknown);
3460     impl = (IDirectDrawSurfaceImpl *)*surface;
3461     if (SUCCEEDED(hr) && impl)
3462     {
3463         ddraw_set_surface_version(impl, 4);
3464         IDirectDraw7_Release(&This->IDirectDraw7_iface);
3465         IDirectDraw4_AddRef(iface);
3466         impl->ifaceToRelease = (IUnknown *)iface;
3467     }
3468
3469     return hr;
3470 }
3471
3472 static HRESULT WINAPI ddraw3_CreateSurface(IDirectDraw3 *iface, DDSURFACEDESC *surface_desc,
3473         IDirectDrawSurface **surface, IUnknown *outer_unknown)
3474 {
3475     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3476     IDirectDrawSurface7 *surface7;
3477     IDirectDrawSurfaceImpl *impl;
3478     HRESULT hr;
3479
3480     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3481             iface, surface_desc, surface, outer_unknown);
3482
3483     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3484     {
3485         WARN("Application supplied invalid surface descriptor\n");
3486         return DDERR_INVALIDPARAMS;
3487     }
3488
3489     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3490     {
3491         if (TRACE_ON(ddraw))
3492         {
3493             TRACE(" (%p) Requesting surface desc :\n", iface);
3494             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3495         }
3496
3497         WARN("Application tried to create an explicit front or back buffer\n");
3498         return DDERR_INVALIDCAPS;
3499     }
3500
3501     hr = CreateSurface(This, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3502     if (FAILED(hr))
3503     {
3504         *surface = NULL;
3505         return hr;
3506     }
3507
3508     impl = (IDirectDrawSurfaceImpl *)surface7;
3509     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3510     ddraw_set_surface_version(impl, 3);
3511     IDirectDraw7_Release(&This->IDirectDraw7_iface);
3512     IDirectDraw3_AddRef(iface);
3513     impl->ifaceToRelease = (IUnknown *)iface;
3514
3515     return hr;
3516 }
3517
3518 static HRESULT WINAPI ddraw2_CreateSurface(IDirectDraw2 *iface,
3519         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3520 {
3521     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3522     IDirectDrawSurface7 *surface7;
3523     IDirectDrawSurfaceImpl *impl;
3524     HRESULT hr;
3525
3526     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3527             iface, surface_desc, surface, outer_unknown);
3528
3529     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3530     {
3531         WARN("Application supplied invalid surface descriptor\n");
3532         return DDERR_INVALIDPARAMS;
3533     }
3534
3535     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3536     {
3537         if (TRACE_ON(ddraw))
3538         {
3539             TRACE(" (%p) Requesting surface desc :\n", iface);
3540             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3541         }
3542
3543         WARN("Application tried to create an explicit front or back buffer\n");
3544         return DDERR_INVALIDCAPS;
3545     }
3546
3547     hr = CreateSurface(This, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3548     if (FAILED(hr))
3549     {
3550         *surface = NULL;
3551         return hr;
3552     }
3553
3554     impl = (IDirectDrawSurfaceImpl *)surface7;
3555     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3556     ddraw_set_surface_version(impl, 2);
3557     IDirectDraw7_Release(&This->IDirectDraw7_iface);
3558     impl->ifaceToRelease = NULL;
3559
3560     return hr;
3561 }
3562
3563 static HRESULT WINAPI ddraw1_CreateSurface(IDirectDraw *iface,
3564         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3565 {
3566     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3567     IDirectDrawSurface7 *surface7;
3568     IDirectDrawSurfaceImpl *impl;
3569     HRESULT hr;
3570
3571     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3572             iface, surface_desc, surface, outer_unknown);
3573
3574     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3575     {
3576         WARN("Application supplied invalid surface descriptor\n");
3577         return DDERR_INVALIDPARAMS;
3578     }
3579
3580     /* Remove front buffer flag, this causes failure in v7, and its added to normal
3581      * primaries anyway. */
3582     surface_desc->ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER;
3583     hr = CreateSurface(This, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3584     if (FAILED(hr))
3585     {
3586         *surface = NULL;
3587         return hr;
3588     }
3589
3590     impl = (IDirectDrawSurfaceImpl *)surface7;
3591     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3592     ddraw_set_surface_version(impl, 1);
3593     IDirectDraw7_Release(&This->IDirectDraw7_iface);
3594     impl->ifaceToRelease = NULL;
3595
3596     return hr;
3597 }
3598
3599 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
3600 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
3601
3602 static BOOL
3603 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
3604                                     const DDPIXELFORMAT *provided)
3605 {
3606     /* Some flags must be present in both or neither for a match. */
3607     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
3608         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
3609         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
3610
3611     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3612         return FALSE;
3613
3614     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
3615         return FALSE;
3616
3617     if (requested->dwFlags & DDPF_FOURCC)
3618         if (requested->dwFourCC != provided->dwFourCC)
3619             return FALSE;
3620
3621     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
3622                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3623         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
3624             return FALSE;
3625
3626     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3627                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3628         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
3629             return FALSE;
3630
3631     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
3632         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
3633             return FALSE;
3634
3635     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
3636     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3637                               |DDPF_BUMPDUDV))
3638         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
3639             return FALSE;
3640
3641     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
3642         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
3643             return FALSE;
3644
3645     return TRUE;
3646 }
3647
3648 static BOOL ddraw_match_surface_desc(const DDSURFACEDESC2 *requested, const DDSURFACEDESC2 *provided)
3649 {
3650     struct compare_info
3651     {
3652         DWORD flag;
3653         ptrdiff_t offset;
3654         size_t size;
3655     };
3656
3657 #define CMP(FLAG, FIELD)                                \
3658         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
3659           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
3660
3661     static const struct compare_info compare[] =
3662     {
3663         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
3664         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
3665         CMP(CAPS, ddsCaps),
3666         CMP(CKDESTBLT, ddckCKDestBlt),
3667         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
3668         CMP(CKSRCBLT, ddckCKSrcBlt),
3669         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
3670         CMP(HEIGHT, dwHeight),
3671         CMP(LINEARSIZE, u1 /* dwLinearSize */),
3672         CMP(LPSURFACE, lpSurface),
3673         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
3674         CMP(PITCH, u1 /* lPitch */),
3675         /* PIXELFORMAT: manual */
3676         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
3677         CMP(TEXTURESTAGE, dwTextureStage),
3678         CMP(WIDTH, dwWidth),
3679         /* ZBUFFERBITDEPTH: "obsolete" */
3680     };
3681
3682 #undef CMP
3683
3684     unsigned int i;
3685
3686     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3687         return FALSE;
3688
3689     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
3690     {
3691         if (requested->dwFlags & compare[i].flag
3692             && memcmp((const char *)provided + compare[i].offset,
3693                       (const char *)requested + compare[i].offset,
3694                       compare[i].size) != 0)
3695             return FALSE;
3696     }
3697
3698     if (requested->dwFlags & DDSD_PIXELFORMAT)
3699     {
3700         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
3701                                                 &provided->u4.ddpfPixelFormat))
3702             return FALSE;
3703     }
3704
3705     return TRUE;
3706 }
3707
3708 #undef DDENUMSURFACES_SEARCHTYPE
3709 #undef DDENUMSURFACES_MATCHTYPE
3710
3711 struct surfacescallback_context
3712 {
3713     LPDDENUMSURFACESCALLBACK func;
3714     void *context;
3715 };
3716
3717 static HRESULT CALLBACK EnumSurfacesCallbackThunk(IDirectDrawSurface7 *surface,
3718         DDSURFACEDESC2 *surface_desc, void *context)
3719 {
3720     struct surfacescallback_context *cbcontext = context;
3721
3722     return cbcontext->func((IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface)->IDirectDrawSurface3_vtbl,
3723             (DDSURFACEDESC *)surface_desc, cbcontext->context);
3724 }
3725
3726 /*****************************************************************************
3727  * IDirectDraw7::EnumSurfaces
3728  *
3729  * Loops through all surfaces attached to this device and calls the
3730  * application callback. This can't be relayed to WineD3DDevice,
3731  * because some WineD3DSurfaces' parents are IParent objects
3732  *
3733  * Params:
3734  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
3735  *  DDSD: Description to filter for
3736  *  Context: Application-provided pointer, it's passed unmodified to the
3737  *           Callback function
3738  *  Callback: Address to call for each surface
3739  *
3740  * Returns:
3741  *  DDERR_INVALIDPARAMS if the callback is NULL
3742  *  DD_OK on success
3743  *
3744  *****************************************************************************/
3745 static HRESULT WINAPI ddraw7_EnumSurfaces(IDirectDraw7 *iface, DWORD Flags,
3746         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMSURFACESCALLBACK7 Callback)
3747 {
3748     /* The surface enumeration is handled by WineDDraw,
3749      * because it keeps track of all surfaces attached to
3750      * it. The filtering is done by our callback function,
3751      * because WineDDraw doesn't handle ddraw-like surface
3752      * caps structures
3753      */
3754     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3755     IDirectDrawSurfaceImpl *surf;
3756     BOOL all, nomatch;
3757     DDSURFACEDESC2 desc;
3758     struct list *entry, *entry2;
3759
3760     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3761             iface, Flags, DDSD, Context, Callback);
3762
3763     all = Flags & DDENUMSURFACES_ALL;
3764     nomatch = Flags & DDENUMSURFACES_NOMATCH;
3765
3766     EnterCriticalSection(&ddraw_cs);
3767
3768     if(!Callback)
3769     {
3770         LeaveCriticalSection(&ddraw_cs);
3771         return DDERR_INVALIDPARAMS;
3772     }
3773
3774     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
3775     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
3776     {
3777         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3778         if (all || (nomatch != ddraw_match_surface_desc(DDSD, &surf->surface_desc)))
3779         {
3780             desc = surf->surface_desc;
3781             IDirectDrawSurface7_AddRef((IDirectDrawSurface7 *)surf);
3782             if (Callback((IDirectDrawSurface7 *)surf, &desc, Context) != DDENUMRET_OK)
3783             {
3784                 LeaveCriticalSection(&ddraw_cs);
3785                 return DD_OK;
3786             }
3787         }
3788     }
3789     LeaveCriticalSection(&ddraw_cs);
3790     return DD_OK;
3791 }
3792
3793 static HRESULT WINAPI ddraw4_EnumSurfaces(IDirectDraw4 *iface, DWORD flags,
3794         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMSURFACESCALLBACK2 callback)
3795 {
3796     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3797
3798     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3799             iface, flags, surface_desc, context, callback);
3800
3801     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, surface_desc, context,
3802             (LPDDENUMSURFACESCALLBACK7)callback);
3803 }
3804
3805 static HRESULT WINAPI ddraw3_EnumSurfaces(IDirectDraw3 *iface, DWORD flags,
3806         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3807 {
3808     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3809     struct surfacescallback_context cbcontext;
3810
3811     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3812             iface, flags, surface_desc, context, callback);
3813
3814     cbcontext.func = callback;
3815     cbcontext.context = context;
3816
3817     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
3818             &cbcontext, EnumSurfacesCallbackThunk);
3819 }
3820
3821 static HRESULT WINAPI ddraw2_EnumSurfaces(IDirectDraw2 *iface, DWORD flags,
3822         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3823 {
3824     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3825     struct surfacescallback_context cbcontext;
3826
3827     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3828             iface, flags, surface_desc, context, callback);
3829
3830     cbcontext.func = callback;
3831     cbcontext.context = context;
3832
3833     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
3834             &cbcontext, EnumSurfacesCallbackThunk);
3835 }
3836
3837 static HRESULT WINAPI ddraw1_EnumSurfaces(IDirectDraw *iface, DWORD flags,
3838         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3839 {
3840     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3841     struct surfacescallback_context cbcontext;
3842
3843     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3844             iface, flags, surface_desc, context, callback);
3845
3846     cbcontext.func = callback;
3847     cbcontext.context = context;
3848
3849     return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
3850             &cbcontext, EnumSurfacesCallbackThunk);
3851 }
3852
3853 /*****************************************************************************
3854  * DirectDrawCreateClipper (DDRAW.@)
3855  *
3856  * Creates a new IDirectDrawClipper object.
3857  *
3858  * Params:
3859  *  Clipper: Address to write the interface pointer to
3860  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3861  *            NULL
3862  *
3863  * Returns:
3864  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3865  *  E_OUTOFMEMORY if allocating the object failed
3866  *
3867  *****************************************************************************/
3868 HRESULT WINAPI
3869 DirectDrawCreateClipper(DWORD Flags,
3870                         LPDIRECTDRAWCLIPPER *Clipper,
3871                         IUnknown *UnkOuter)
3872 {
3873     IDirectDrawClipperImpl* object;
3874     HRESULT hr;
3875
3876     TRACE("flags %#x, clipper %p, outer_unknown %p.\n",
3877             Flags, Clipper, UnkOuter);
3878
3879     EnterCriticalSection(&ddraw_cs);
3880     if (UnkOuter != NULL)
3881     {
3882         LeaveCriticalSection(&ddraw_cs);
3883         return CLASS_E_NOAGGREGATION;
3884     }
3885
3886     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3887                      sizeof(IDirectDrawClipperImpl));
3888     if (object == NULL)
3889     {
3890         LeaveCriticalSection(&ddraw_cs);
3891         return E_OUTOFMEMORY;
3892     }
3893
3894     hr = ddraw_clipper_init(object);
3895     if (FAILED(hr))
3896     {
3897         WARN("Failed to initialize clipper, hr %#x.\n", hr);
3898         HeapFree(GetProcessHeap(), 0, object);
3899         LeaveCriticalSection(&ddraw_cs);
3900         return hr;
3901     }
3902
3903     TRACE("Created clipper %p.\n", object);
3904     *Clipper = (IDirectDrawClipper *) object;
3905     LeaveCriticalSection(&ddraw_cs);
3906     return DD_OK;
3907 }
3908
3909 /*****************************************************************************
3910  * IDirectDraw7::CreateClipper
3911  *
3912  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3913  *
3914  *****************************************************************************/
3915 static HRESULT WINAPI ddraw7_CreateClipper(IDirectDraw7 *iface, DWORD Flags,
3916         IDirectDrawClipper **Clipper, IUnknown *UnkOuter)
3917 {
3918     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3919             iface, Flags, Clipper, UnkOuter);
3920
3921     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3922 }
3923
3924 static HRESULT WINAPI ddraw4_CreateClipper(IDirectDraw4 *iface, DWORD flags,
3925         IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3926 {
3927     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3928
3929     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3930             iface, flags, clipper, outer_unknown);
3931
3932     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3933 }
3934
3935 static HRESULT WINAPI ddraw3_CreateClipper(IDirectDraw3 *iface, DWORD flags,
3936         IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3937 {
3938     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3939
3940     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3941             iface, flags, clipper, outer_unknown);
3942
3943     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3944 }
3945
3946 static HRESULT WINAPI ddraw2_CreateClipper(IDirectDraw2 *iface,
3947         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3948 {
3949     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3950
3951     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3952             iface, flags, clipper, outer_unknown);
3953
3954     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3955 }
3956
3957 static HRESULT WINAPI ddraw1_CreateClipper(IDirectDraw *iface,
3958         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3959 {
3960     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3961
3962     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3963             iface, flags, clipper, outer_unknown);
3964
3965     return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
3966 }
3967
3968 /*****************************************************************************
3969  * IDirectDraw7::CreatePalette
3970  *
3971  * Creates a new IDirectDrawPalette object
3972  *
3973  * Params:
3974  *  Flags: The flags for the new clipper
3975  *  ColorTable: Color table to assign to the new clipper
3976  *  Palette: Address to write the interface pointer to
3977  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3978  *            NULL
3979  *
3980  * Returns:
3981  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3982  *  E_OUTOFMEMORY if allocating the object failed
3983  *
3984  *****************************************************************************/
3985 static HRESULT WINAPI ddraw7_CreatePalette(IDirectDraw7 *iface, DWORD Flags,
3986         PALETTEENTRY *ColorTable, IDirectDrawPalette **Palette, IUnknown *pUnkOuter)
3987 {
3988     IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3989     IDirectDrawPaletteImpl *object;
3990     HRESULT hr;
3991
3992     TRACE("iface %p, flags %#x, color_table %p, palette %p, outer_unknown %p.\n",
3993             iface, Flags, ColorTable, Palette, pUnkOuter);
3994
3995     EnterCriticalSection(&ddraw_cs);
3996     if(pUnkOuter != NULL)
3997     {
3998         WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
3999         LeaveCriticalSection(&ddraw_cs);
4000         return CLASS_E_NOAGGREGATION;
4001     }
4002
4003     /* The refcount test shows that a cooplevel is required for this */
4004     if(!This->cooperative_level)
4005     {
4006         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
4007         LeaveCriticalSection(&ddraw_cs);
4008         return DDERR_NOCOOPERATIVELEVELSET;
4009     }
4010
4011     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
4012     if(!object)
4013     {
4014         ERR("Out of memory when allocating memory for a palette implementation\n");
4015         LeaveCriticalSection(&ddraw_cs);
4016         return E_OUTOFMEMORY;
4017     }
4018
4019     hr = ddraw_palette_init(object, This, Flags, ColorTable);
4020     if (FAILED(hr))
4021     {
4022         WARN("Failed to initialize palette, hr %#x.\n", hr);
4023         HeapFree(GetProcessHeap(), 0, object);
4024         LeaveCriticalSection(&ddraw_cs);
4025         return hr;
4026     }
4027
4028     TRACE("Created palette %p.\n", object);
4029     *Palette = (IDirectDrawPalette *)object;
4030     LeaveCriticalSection(&ddraw_cs);
4031     return DD_OK;
4032 }
4033
4034 static HRESULT WINAPI ddraw4_CreatePalette(IDirectDraw4 *iface, DWORD flags, PALETTEENTRY *entries,
4035         IDirectDrawPalette **palette, IUnknown *outer_unknown)
4036 {
4037     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
4038     HRESULT hr;
4039
4040     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
4041             iface, flags, entries, palette, outer_unknown);
4042
4043     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4044     if (SUCCEEDED(hr) && *palette)
4045     {
4046         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4047         IDirectDraw7_Release(&This->IDirectDraw7_iface);
4048         IDirectDraw4_AddRef(iface);
4049         impl->ifaceToRelease = (IUnknown *)iface;
4050     }
4051     return hr;
4052 }
4053
4054 static HRESULT WINAPI ddraw3_CreatePalette(IDirectDraw3 *iface, DWORD flags,
4055         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
4056 {
4057     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
4058     HRESULT hr;
4059
4060     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
4061             iface, flags, entries, palette, outer_unknown);
4062
4063     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4064     if (SUCCEEDED(hr) && *palette)
4065     {
4066         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4067         IDirectDraw7_Release(&This->IDirectDraw7_iface);
4068         IDirectDraw4_AddRef(iface);
4069         impl->ifaceToRelease = (IUnknown *)iface;
4070     }
4071
4072     return hr;
4073 }
4074
4075 static HRESULT WINAPI ddraw2_CreatePalette(IDirectDraw2 *iface, DWORD flags,
4076         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
4077 {
4078     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
4079     HRESULT hr;
4080
4081     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
4082             iface, flags, entries, palette, outer_unknown);
4083
4084     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4085     if (SUCCEEDED(hr) && *palette)
4086     {
4087         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4088         IDirectDraw7_Release(&This->IDirectDraw7_iface);
4089         impl->ifaceToRelease = NULL;
4090     }
4091
4092     return hr;
4093 }
4094
4095 static HRESULT WINAPI ddraw1_CreatePalette(IDirectDraw *iface, DWORD flags,
4096         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
4097 {
4098     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
4099     HRESULT hr;
4100
4101     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
4102             iface, flags, entries, palette, outer_unknown);
4103
4104     hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4105     if (SUCCEEDED(hr) && *palette)
4106     {
4107         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4108         IDirectDraw7_Release(&This->IDirectDraw7_iface);
4109         impl->ifaceToRelease = NULL;
4110     }
4111
4112     return hr;
4113 }
4114
4115 /*****************************************************************************
4116  * IDirectDraw7::DuplicateSurface
4117  *
4118  * Duplicates a surface. The surface memory points to the same memory as
4119  * the original surface, and it's released when the last surface referencing
4120  * it is released. I guess that's beyond Wine's surface management right now
4121  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
4122  * test application to implement this)
4123  *
4124  * Params:
4125  *  Src: Address of the source surface
4126  *  Dest: Address to write the new surface pointer to
4127  *
4128  * Returns:
4129  *  See IDirectDraw7::CreateSurface
4130  *
4131  *****************************************************************************/
4132 static HRESULT WINAPI ddraw7_DuplicateSurface(IDirectDraw7 *iface,
4133         IDirectDrawSurface7 *Src, IDirectDrawSurface7 **Dest)
4134 {
4135     IDirectDrawSurfaceImpl *Surf = (IDirectDrawSurfaceImpl *)Src;
4136
4137     FIXME("iface %p, src %p, dst %p partial stub!\n", iface, Src, Dest);
4138
4139     /* For now, simply create a new, independent surface */
4140     return IDirectDraw7_CreateSurface(iface,
4141                                       &Surf->surface_desc,
4142                                       Dest,
4143                                       NULL);
4144 }
4145
4146 static HRESULT WINAPI ddraw4_DuplicateSurface(IDirectDraw4 *iface, IDirectDrawSurface4 *src,
4147         IDirectDrawSurface4 **dst)
4148 {
4149     IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
4150
4151     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4152
4153     return ddraw7_DuplicateSurface(&This->IDirectDraw7_iface, (IDirectDrawSurface7 *)src,
4154             (IDirectDrawSurface7 **)dst);
4155 }
4156
4157 static HRESULT WINAPI ddraw3_DuplicateSurface(IDirectDraw3 *iface, IDirectDrawSurface *src,
4158         IDirectDrawSurface **dst)
4159 {
4160     IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
4161     IDirectDrawSurface7 *src7, *dst7;
4162     HRESULT hr;
4163
4164     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4165     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
4166     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface, src7, &dst7);
4167     if (FAILED(hr))
4168         return hr;
4169     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
4170     return hr;
4171 }
4172
4173 static HRESULT WINAPI ddraw2_DuplicateSurface(IDirectDraw2 *iface,
4174         IDirectDrawSurface *src, IDirectDrawSurface **dst)
4175 {
4176     IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
4177     IDirectDrawSurface7 *src7, *dst7;
4178     HRESULT hr;
4179
4180     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4181     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
4182     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface, src7, &dst7);
4183     if (FAILED(hr))
4184         return hr;
4185     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
4186     return hr;
4187 }
4188
4189 static HRESULT WINAPI ddraw1_DuplicateSurface(IDirectDraw *iface, IDirectDrawSurface *src,
4190         IDirectDrawSurface **dst)
4191 {
4192     IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
4193     IDirectDrawSurface7 *src7, *dst7;
4194     HRESULT hr;
4195
4196     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4197     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
4198     hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface, src7, &dst7);
4199     if (FAILED(hr))
4200         return hr;
4201     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
4202     return hr;
4203 }
4204
4205 /*****************************************************************************
4206  * IDirect3D7::EnumDevices
4207  *
4208  * The EnumDevices method for IDirect3D7. It enumerates all supported
4209  * D3D7 devices. Currently the T&L, HAL and RGB devices are enumerated.
4210  *
4211  * Params:
4212  *  callback: Function to call for each enumerated device
4213  *  context: Pointer to pass back to the app
4214  *
4215  * Returns:
4216  *  D3D_OK, or the return value of the GetCaps call
4217  *
4218  *****************************************************************************/
4219 static HRESULT WINAPI d3d7_EnumDevices(IDirect3D7 *iface, LPD3DENUMDEVICESCALLBACK7 callback, void *context)
4220 {
4221     char interface_name_tnl[] = "WINE Direct3D7 Hardware Transform and Lighting acceleration using WineD3D";
4222     char device_name_tnl[] = "Wine D3D7 T&L HAL";
4223     char interface_name_hal[] = "WINE Direct3D7 Hardware acceleration using WineD3D";
4224     char device_name_hal[] = "Wine D3D7 HAL";
4225     char interface_name_rgb[] = "WINE Direct3D7 RGB Software Emulation using WineD3D";
4226     char device_name_rgb[] = "Wine D3D7 RGB";
4227
4228     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4229     D3DDEVICEDESC7 device_desc7;
4230     D3DDEVICEDESC device_desc1;
4231     HRESULT hr;
4232
4233     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4234
4235     EnterCriticalSection(&ddraw_cs);
4236
4237     hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
4238     if (hr != D3D_OK)
4239     {
4240         LeaveCriticalSection(&ddraw_cs);
4241         return hr;
4242     }
4243     callback(interface_name_tnl, device_name_tnl, &device_desc7, context);
4244
4245     device_desc7.deviceGUID = IID_IDirect3DHALDevice;
4246     callback(interface_name_hal, device_name_hal, &device_desc7, context);
4247
4248     device_desc7.deviceGUID = IID_IDirect3DRGBDevice;
4249     callback(interface_name_rgb, device_name_rgb, &device_desc7, context);
4250
4251     TRACE("End of enumeration.\n");
4252
4253     LeaveCriticalSection(&ddraw_cs);
4254
4255     return D3D_OK;
4256 }
4257
4258 /*****************************************************************************
4259  * IDirect3D3::EnumDevices
4260  *
4261  * Enumerates all supported Direct3DDevice interfaces. This is the
4262  * implementation for Direct3D 1 to Direc3D 3, Version 7 has its own.
4263  *
4264  * Version 1, 2 and 3
4265  *
4266  * Params:
4267  *  callback: Application-provided routine to call for each enumerated device
4268  *  Context: Pointer to pass to the callback
4269  *
4270  * Returns:
4271  *  D3D_OK on success,
4272  *  The result of IDirect3DImpl_GetCaps if it failed
4273  *
4274  *****************************************************************************/
4275 static HRESULT WINAPI d3d3_EnumDevices(IDirect3D3 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4276 {
4277     static CHAR wined3d_description[] = "Wine D3DDevice using WineD3D and OpenGL";
4278
4279     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4280     D3DDEVICEDESC device_desc1, hal_desc, hel_desc;
4281     D3DDEVICEDESC7 device_desc7;
4282     HRESULT hr;
4283
4284     /* Some games (Motoracer 2 demo) have the bad idea to modify the device
4285      * name string. Let's put the string in a sufficiently sized array in
4286      * writable memory. */
4287     char device_name[50];
4288     strcpy(device_name,"Direct3D HEL");
4289
4290     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4291
4292     EnterCriticalSection(&ddraw_cs);
4293
4294     hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
4295     if (hr != D3D_OK)
4296     {
4297         LeaveCriticalSection(&ddraw_cs);
4298         return hr;
4299     }
4300
4301     /* Do I have to enumerate the reference id? Note from old d3d7:
4302      * "It seems that enumerating the reference IID on Direct3D 1 games
4303      * (AvP / Motoracer2) breaks them". So do not enumerate this iid in V1
4304      *
4305      * There's a registry key HKLM\Software\Microsoft\Direct3D\Drivers,
4306      * EnumReference which enables / disables enumerating the reference
4307      * rasterizer. It's a DWORD, 0 means disabled, 2 means enabled. The
4308      * enablerefrast.reg and disablerefrast.reg files in the DirectX 7.0 sdk
4309      * demo directory suggest this.
4310      *
4311      * Some games(GTA 2) seem to use the second enumerated device, so I have
4312      * to enumerate at least 2 devices. So enumerate the reference device to
4313      * have 2 devices.
4314      *
4315      * Other games (Rollcage) tell emulation and hal device apart by certain
4316      * flags. Rollcage expects D3DPTEXTURECAPS_POW2 to be set (yeah, it is a
4317      * limitation flag), and it refuses all devices that have the perspective
4318      * flag set. This way it refuses the emulation device, and HAL devices
4319      * never have POW2 unset in d3d7 on windows. */
4320     if (This->d3dversion != 1)
4321     {
4322         static CHAR reference_description[] = "RGB Direct3D emulation";
4323
4324         TRACE("Enumerating WineD3D D3DDevice interface.\n");
4325         hal_desc = device_desc1;
4326         hel_desc = device_desc1;
4327         /* The rgb device has the pow2 flag set in the hel caps, but not in the hal caps. */
4328         hal_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4329                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4330         hal_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4331                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4332         hr = callback((GUID *)&IID_IDirect3DRGBDevice, reference_description,
4333                 device_name, &hal_desc, &hel_desc, context);
4334         if (hr != D3DENUMRET_OK)
4335         {
4336             TRACE("Application cancelled the enumeration.\n");
4337             LeaveCriticalSection(&ddraw_cs);
4338             return D3D_OK;
4339         }
4340     }
4341
4342     strcpy(device_name,"Direct3D HAL");
4343
4344     TRACE("Enumerating HAL Direct3D device.\n");
4345     hal_desc = device_desc1;
4346     hel_desc = device_desc1;
4347     /* The hal device does not have the pow2 flag set in hel, but in hal. */
4348     hel_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4349             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4350     hel_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4351             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4352     hr = callback((GUID *)&IID_IDirect3DHALDevice, wined3d_description,
4353             device_name, &hal_desc, &hel_desc, context);
4354     if (hr != D3DENUMRET_OK)
4355     {
4356         TRACE("Application cancelled the enumeration.\n");
4357         LeaveCriticalSection(&ddraw_cs);
4358         return D3D_OK;
4359     }
4360
4361     TRACE("End of enumeration.\n");
4362
4363     LeaveCriticalSection(&ddraw_cs);
4364     return D3D_OK;
4365 }
4366
4367 static HRESULT WINAPI d3d2_EnumDevices(IDirect3D2 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4368 {
4369     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4370
4371     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4372
4373     return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4374 }
4375
4376 static HRESULT WINAPI d3d1_EnumDevices(IDirect3D *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4377 {
4378     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4379
4380     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4381
4382     return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4383 }
4384
4385 /*****************************************************************************
4386  * IDirect3D3::CreateLight
4387  *
4388  * Creates an IDirect3DLight interface. This interface is used in
4389  * Direct3D3 or earlier for lighting. In Direct3D7 it has been replaced
4390  * by the DIRECT3DLIGHT7 structure. Wine's Direct3DLight implementation
4391  * uses the IDirect3DDevice7 interface with D3D7 lights.
4392  *
4393  * Version 1, 2 and 3
4394  *
4395  * Params:
4396  *  light: Address to store the new interface pointer
4397  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4398  *                 Must be NULL
4399  *
4400  * Returns:
4401  *  D3D_OK on success
4402  *  DDERR_OUTOFMEMORY if memory allocation failed
4403  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4404  *
4405  *****************************************************************************/
4406 static HRESULT WINAPI d3d3_CreateLight(IDirect3D3 *iface, IDirect3DLight **light,
4407         IUnknown *outer_unknown)
4408 {
4409     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4410     IDirect3DLightImpl *object;
4411
4412     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4413
4414     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4415
4416     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4417     if (!object)
4418     {
4419         ERR("Failed to allocate light memory.\n");
4420         return DDERR_OUTOFMEMORY;
4421     }
4422
4423     d3d_light_init(object, This);
4424
4425     TRACE("Created light %p.\n", object);
4426     *light = (IDirect3DLight *)object;
4427
4428     return D3D_OK;
4429 }
4430
4431 static HRESULT WINAPI d3d2_CreateLight(IDirect3D2 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4432 {
4433     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4434
4435     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4436
4437     return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4438 }
4439
4440 static HRESULT WINAPI d3d1_CreateLight(IDirect3D *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4441 {
4442     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4443
4444     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4445
4446     return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4447 }
4448
4449 /*****************************************************************************
4450  * IDirect3D3::CreateMaterial
4451  *
4452  * Creates an IDirect3DMaterial interface. This interface is used by Direct3D3
4453  * and older versions. The IDirect3DMaterial implementation wraps its
4454  * functionality to IDirect3DDevice7::SetMaterial and friends.
4455  *
4456  * Version 1, 2 and 3
4457  *
4458  * Params:
4459  *  material: Address to store the new interface's pointer to
4460  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4461  *                 Must be NULL
4462  *
4463  * Returns:
4464  *  D3D_OK on success
4465  *  DDERR_OUTOFMEMORY if memory allocation failed
4466  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4467  *
4468  *****************************************************************************/
4469 static HRESULT WINAPI d3d3_CreateMaterial(IDirect3D3 *iface, IDirect3DMaterial3 **material,
4470         IUnknown *outer_unknown)
4471 {
4472     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4473     IDirect3DMaterialImpl *object;
4474
4475     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4476
4477     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4478
4479     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4480     if (!object)
4481     {
4482         ERR("Failed to allocate material memory.\n");
4483         return DDERR_OUTOFMEMORY;
4484     }
4485
4486     d3d_material_init(object, This);
4487
4488     TRACE("Created material %p.\n", object);
4489     *material = (IDirect3DMaterial3 *)object;
4490
4491     return D3D_OK;
4492 }
4493
4494 static HRESULT WINAPI d3d2_CreateMaterial(IDirect3D2 *iface, IDirect3DMaterial2 **material, IUnknown *outer_unknown)
4495 {
4496     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4497     IDirect3DMaterial3 *material3;
4498     HRESULT hr;
4499
4500     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4501
4502     hr = d3d3_CreateMaterial(&This->IDirect3D3_iface, &material3, outer_unknown);
4503     *material = material3 ? (IDirect3DMaterial2 *)&((IDirect3DMaterialImpl *)material3)->IDirect3DMaterial2_vtbl : NULL;
4504
4505     TRACE("Returning material %p.\n", *material);
4506
4507     return hr;
4508 }
4509
4510 static HRESULT WINAPI d3d1_CreateMaterial(IDirect3D *iface, IDirect3DMaterial **material, IUnknown *outer_unknown)
4511 {
4512     IDirect3DMaterial3 *material3;
4513     HRESULT hr;
4514
4515     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4516
4517     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4518
4519     hr = d3d3_CreateMaterial(&This->IDirect3D3_iface, &material3, outer_unknown);
4520     *material = material3 ? (IDirect3DMaterial *)&((IDirect3DMaterialImpl *)material3)->IDirect3DMaterial_vtbl : NULL;
4521
4522     TRACE("Returning material %p.\n", *material);
4523
4524     return hr;
4525 }
4526
4527 /*****************************************************************************
4528  * IDirect3D3::CreateViewport
4529  *
4530  * Creates an IDirect3DViewport interface. This interface is used
4531  * by Direct3D and earlier versions for Viewport management. In Direct3D7
4532  * it has been replaced by a viewport structure and
4533  * IDirect3DDevice7::*Viewport. Wine's IDirect3DViewport implementation
4534  * uses the IDirect3DDevice7 methods for its functionality
4535  *
4536  * Params:
4537  *  Viewport: Address to store the new interface pointer
4538  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4539  *                 Must be NULL
4540  *
4541  * Returns:
4542  *  D3D_OK on success
4543  *  DDERR_OUTOFMEMORY if memory allocation failed
4544  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4545  *
4546  *****************************************************************************/
4547 static HRESULT WINAPI d3d3_CreateViewport(IDirect3D3 *iface, IDirect3DViewport3 **viewport,
4548         IUnknown *outer_unknown)
4549 {
4550     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4551     IDirect3DViewportImpl *object;
4552
4553     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4554
4555     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4556
4557     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4558     if (!object)
4559     {
4560         ERR("Failed to allocate viewport memory.\n");
4561         return DDERR_OUTOFMEMORY;
4562     }
4563
4564     d3d_viewport_init(object, This);
4565
4566     TRACE("Created viewport %p.\n", object);
4567     *viewport = (IDirect3DViewport3 *)object;
4568
4569     return D3D_OK;
4570 }
4571
4572 static HRESULT WINAPI d3d2_CreateViewport(IDirect3D2 *iface, IDirect3DViewport2 **viewport, IUnknown *outer_unknown)
4573 {
4574     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4575
4576     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4577
4578     return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4579             outer_unknown);
4580 }
4581
4582 static HRESULT WINAPI d3d1_CreateViewport(IDirect3D *iface, IDirect3DViewport **viewport, IUnknown *outer_unknown)
4583 {
4584     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4585
4586     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4587
4588     return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
4589             outer_unknown);
4590 }
4591
4592 /*****************************************************************************
4593  * IDirect3D3::FindDevice
4594  *
4595  * This method finds a device with the requested properties and returns a
4596  * device description
4597  *
4598  * Verion 1, 2 and 3
4599  * Params:
4600  *  fds: Describes the requested device characteristics
4601  *  fdr: Returns the device description
4602  *
4603  * Returns:
4604  *  D3D_OK on success
4605  *  DDERR_INVALIDPARAMS if no device was found
4606  *
4607  *****************************************************************************/
4608 static HRESULT WINAPI d3d3_FindDevice(IDirect3D3 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4609 {
4610     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4611     D3DDEVICEDESC7 desc7;
4612     D3DDEVICEDESC desc1;
4613     HRESULT hr;
4614
4615     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4616
4617     if (!fds || !fdr) return DDERR_INVALIDPARAMS;
4618
4619     if (fds->dwSize != sizeof(D3DFINDDEVICESEARCH)
4620             || fdr->dwSize != sizeof(D3DFINDDEVICERESULT))
4621         return DDERR_INVALIDPARAMS;
4622
4623     if ((fds->dwFlags & D3DFDS_COLORMODEL)
4624             && fds->dcmColorModel != D3DCOLOR_RGB)
4625     {
4626         WARN("Trying to request a non-RGB D3D color model. Not supported.\n");
4627         return DDERR_INVALIDPARAMS; /* No real idea what to return here :-) */
4628     }
4629
4630     if (fds->dwFlags & D3DFDS_GUID)
4631     {
4632         TRACE("Trying to match guid %s.\n", debugstr_guid(&(fds->guid)));
4633         if (!IsEqualGUID(&IID_D3DDEVICE_WineD3D, &fds->guid)
4634                 && !IsEqualGUID(&IID_IDirect3DHALDevice, &fds->guid)
4635                 && !IsEqualGUID(&IID_IDirect3DRGBDevice, &fds->guid))
4636         {
4637             WARN("No match for this GUID.\n");
4638             return DDERR_NOTFOUND;
4639         }
4640     }
4641
4642     /* Get the caps */
4643     hr = IDirect3DImpl_GetCaps(This->wineD3D, &desc1, &desc7);
4644     if (hr != D3D_OK) return hr;
4645
4646     /* Now return our own GUID */
4647     fdr->guid = IID_D3DDEVICE_WineD3D;
4648     fdr->ddHwDesc = desc1;
4649     fdr->ddSwDesc = desc1;
4650
4651     TRACE("Returning Wine's wined3d device with (undumped) capabilities.\n");
4652
4653     return D3D_OK;
4654 }
4655
4656 static HRESULT WINAPI d3d2_FindDevice(IDirect3D2 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4657 {
4658     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4659
4660     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4661
4662     return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4663 }
4664
4665 static HRESULT WINAPI d3d1_FindDevice(IDirect3D *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4666 {
4667     IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4668
4669     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4670
4671     return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4672 }
4673
4674 /*****************************************************************************
4675  * IDirect3D7::CreateDevice
4676  *
4677  * Creates an IDirect3DDevice7 interface.
4678  *
4679  * Version 2, 3 and 7. IDirect3DDevice 1 interfaces are interfaces to
4680  * DirectDraw surfaces and are created with
4681  * IDirectDrawSurface::QueryInterface. This method uses CreateDevice to
4682  * create the device object and QueryInterfaces for IDirect3DDevice
4683  *
4684  * Params:
4685  *  refiid: IID of the device to create
4686  *  Surface: Initial rendertarget
4687  *  Device: Address to return the interface pointer
4688  *
4689  * Returns:
4690  *  D3D_OK on success
4691  *  DDERR_OUTOFMEMORY if memory allocation failed
4692  *  DDERR_INVALIDPARAMS if a device exists already
4693  *
4694  *****************************************************************************/
4695 static HRESULT WINAPI d3d7_CreateDevice(IDirect3D7 *iface, REFCLSID riid,
4696         IDirectDrawSurface7 *surface, IDirect3DDevice7 **device)
4697 {
4698     IDirectDrawSurfaceImpl *target = (IDirectDrawSurfaceImpl *)surface;
4699     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4700     IDirect3DDeviceImpl *object;
4701     HRESULT hr;
4702
4703     TRACE("iface %p, riid %s, surface %p, device %p.\n", iface, debugstr_guid(riid), surface, device);
4704
4705     EnterCriticalSection(&ddraw_cs);
4706     *device = NULL;
4707
4708     /* Fail device creation if non-opengl surfaces are used. */
4709     if (This->ImplType != SURFACE_OPENGL)
4710     {
4711         ERR("The application wants to create a Direct3D device, but non-opengl surfaces are set in the registry.\n");
4712         ERR("Please set the surface implementation to opengl or autodetection to allow 3D rendering.\n");
4713
4714         /* We only hit this path if a default surface is set in the registry. Incorrect autodetection
4715          * is caught in CreateSurface or QueryInterface. */
4716         LeaveCriticalSection(&ddraw_cs);
4717         return DDERR_NO3D;
4718     }
4719
4720     if (This->d3ddevice)
4721     {
4722         FIXME("Only one Direct3D device per DirectDraw object supported.\n");
4723         LeaveCriticalSection(&ddraw_cs);
4724         return DDERR_INVALIDPARAMS;
4725     }
4726
4727     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4728     if (!object)
4729     {
4730         ERR("Failed to allocate device memory.\n");
4731         LeaveCriticalSection(&ddraw_cs);
4732         return DDERR_OUTOFMEMORY;
4733     }
4734
4735     hr = d3d_device_init(object, This, target);
4736     if (FAILED(hr))
4737     {
4738         WARN("Failed to initialize device, hr %#x.\n", hr);
4739         HeapFree(GetProcessHeap(), 0, object);
4740         LeaveCriticalSection(&ddraw_cs);
4741         return hr;
4742     }
4743
4744     TRACE("Created device %p.\n", object);
4745     *device = (IDirect3DDevice7 *)object;
4746
4747     LeaveCriticalSection(&ddraw_cs);
4748     return D3D_OK;
4749 }
4750
4751 static HRESULT WINAPI d3d3_CreateDevice(IDirect3D3 *iface, REFCLSID riid,
4752         IDirectDrawSurface4 *surface, IDirect3DDevice3 **device, IUnknown *outer_unknown)
4753 {
4754     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4755     HRESULT hr;
4756
4757     TRACE("iface %p, riid %s, surface %p, device %p, outer_unknown %p.\n",
4758             iface, debugstr_guid(riid), surface, device, outer_unknown);
4759
4760     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4761
4762     hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid, (IDirectDrawSurface7 *)surface,
4763             (IDirect3DDevice7 **)device);
4764     if (*device) *device = (IDirect3DDevice3 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice3_vtbl;
4765
4766     return hr;
4767 }
4768
4769 static HRESULT WINAPI d3d2_CreateDevice(IDirect3D2 *iface, REFCLSID riid,
4770         IDirectDrawSurface *surface, IDirect3DDevice2 **device)
4771 {
4772     IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4773     HRESULT hr;
4774
4775     TRACE("iface %p, riid %s, surface %p, device %p.\n",
4776             iface, debugstr_guid(riid), surface, device);
4777
4778     hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid,
4779             surface ? (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)surface) : NULL,
4780             (IDirect3DDevice7 **)device);
4781     if (*device) *device = (IDirect3DDevice2 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice2_vtbl;
4782
4783     return hr;
4784 }
4785
4786 /*****************************************************************************
4787  * IDirect3D7::CreateVertexBuffer
4788  *
4789  * Creates a new vertex buffer object and returns a IDirect3DVertexBuffer7
4790  * interface.
4791  *
4792  * Version 3 and 7
4793  *
4794  * Params:
4795  *  desc: Requested Vertex buffer properties
4796  *  vertex_buffer: Address to return the interface pointer at
4797  *  flags: Some flags, should be 0
4798  *
4799  * Returns
4800  *  D3D_OK on success
4801  *  DDERR_OUTOFMEMORY if memory allocation failed
4802  *  The return value of IWineD3DDevice::CreateVertexBuffer if this call fails
4803  *  DDERR_INVALIDPARAMS if desc or vertex_buffer are NULL
4804  *
4805  *****************************************************************************/
4806 static HRESULT WINAPI d3d7_CreateVertexBuffer(IDirect3D7 *iface, D3DVERTEXBUFFERDESC *desc,
4807         IDirect3DVertexBuffer7 **vertex_buffer, DWORD flags)
4808 {
4809     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4810     IDirect3DVertexBufferImpl *object;
4811     HRESULT hr;
4812
4813     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x.\n",
4814             iface, desc, vertex_buffer, flags);
4815
4816     if (!vertex_buffer || !desc) return DDERR_INVALIDPARAMS;
4817
4818     TRACE("Vertex buffer description:\n");
4819     TRACE("    dwSize %u\n", desc->dwSize);
4820     TRACE("    dwCaps %#x\n", desc->dwCaps);
4821     TRACE("    FVF %#x\n", desc->dwFVF);
4822     TRACE("    dwNumVertices %u\n", desc->dwNumVertices);
4823
4824     /* Now create the vertex buffer */
4825     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4826     if (!object)
4827     {
4828         ERR("Failed to allocate vertex buffer memory.\n");
4829         return DDERR_OUTOFMEMORY;
4830     }
4831
4832     hr = d3d_vertex_buffer_init(object, This, desc);
4833     if (FAILED(hr))
4834     {
4835         WARN("Failed to initialize vertex buffer, hr %#x.\n", hr);
4836         HeapFree(GetProcessHeap(), 0, object);
4837         return hr;
4838     }
4839
4840     TRACE("Created vertex buffer %p.\n", object);
4841     *vertex_buffer = (IDirect3DVertexBuffer7 *)object;
4842
4843     return D3D_OK;
4844 }
4845
4846 static HRESULT WINAPI d3d3_CreateVertexBuffer(IDirect3D3 *iface, D3DVERTEXBUFFERDESC *desc,
4847         IDirect3DVertexBuffer **vertex_buffer, DWORD flags, IUnknown *outer_unknown)
4848 {
4849     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4850     HRESULT hr;
4851
4852     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x, outer_unknown %p.\n",
4853             iface, desc, vertex_buffer, flags, outer_unknown);
4854
4855     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4856
4857     hr = d3d7_CreateVertexBuffer(&This->IDirect3D7_iface, desc,
4858             (IDirect3DVertexBuffer7 **)vertex_buffer, flags);
4859     if (*vertex_buffer)
4860         *vertex_buffer = (IDirect3DVertexBuffer *)&((IDirect3DVertexBufferImpl *)*vertex_buffer)->IDirect3DVertexBuffer_vtbl;
4861
4862     return hr;
4863 }
4864
4865 /*****************************************************************************
4866  * IDirect3D7::EnumZBufferFormats
4867  *
4868  * Enumerates all supported Z buffer pixel formats
4869  *
4870  * Version 3 and 7
4871  *
4872  * Params:
4873  *  device_iid:
4874  *  callback: callback to call for each pixel format
4875  *  context: Pointer to pass back to the callback
4876  *
4877  * Returns:
4878  *  D3D_OK on success
4879  *  DDERR_INVALIDPARAMS if callback is NULL
4880  *  For details, see IWineD3DDevice::EnumZBufferFormats
4881  *
4882  *****************************************************************************/
4883 static HRESULT WINAPI d3d7_EnumZBufferFormats(IDirect3D7 *iface, REFCLSID device_iid,
4884         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4885 {
4886     IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4887     WINED3DDISPLAYMODE d3ddm;
4888     WINED3DDEVTYPE type;
4889     unsigned int i;
4890     HRESULT hr;
4891
4892     /* Order matters. Specifically, BattleZone II (full version) expects the
4893      * 16-bit depth formats to be listed before the 24 and 32 ones. */
4894     static const enum wined3d_format_id formats[] =
4895     {
4896         WINED3DFMT_S1_UINT_D15_UNORM,
4897         WINED3DFMT_D16_UNORM,
4898         WINED3DFMT_X8D24_UNORM,
4899         WINED3DFMT_S4X4_UINT_D24_UNORM,
4900         WINED3DFMT_D24_UNORM_S8_UINT,
4901         WINED3DFMT_D32_UNORM,
4902     };
4903
4904     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4905             iface, debugstr_guid(device_iid), callback, context);
4906
4907     if (!callback) return DDERR_INVALIDPARAMS;
4908
4909     if (IsEqualGUID(device_iid, &IID_IDirect3DHALDevice)
4910             || IsEqualGUID(device_iid, &IID_IDirect3DTnLHalDevice)
4911             || IsEqualGUID(device_iid, &IID_D3DDEVICE_WineD3D))
4912     {
4913         TRACE("Asked for HAL device.\n");
4914         type = WINED3DDEVTYPE_HAL;
4915     }
4916     else if (IsEqualGUID(device_iid, &IID_IDirect3DRGBDevice)
4917             || IsEqualGUID(device_iid, &IID_IDirect3DMMXDevice))
4918     {
4919         TRACE("Asked for SW device.\n");
4920         type = WINED3DDEVTYPE_SW;
4921     }
4922     else if (IsEqualGUID(device_iid, &IID_IDirect3DRefDevice))
4923     {
4924         TRACE("Asked for REF device.\n");
4925         type = WINED3DDEVTYPE_REF;
4926     }
4927     else if (IsEqualGUID(device_iid, &IID_IDirect3DNullDevice))
4928     {
4929         TRACE("Asked for NULLREF device.\n");
4930         type = WINED3DDEVTYPE_NULLREF;
4931     }
4932     else
4933     {
4934         FIXME("Unexpected device GUID %s.\n", debugstr_guid(device_iid));
4935         type = WINED3DDEVTYPE_HAL;
4936     }
4937
4938     EnterCriticalSection(&ddraw_cs);
4939     /* We need an adapter format from somewhere to please wined3d and WGL.
4940      * Use the current display mode. So far all cards offer the same depth
4941      * stencil format for all modes, but if some do not and applications do
4942      * not like that we'll have to find some workaround, like iterating over
4943      * all imaginable formats and collecting all the depth stencil formats we
4944      * can get. */
4945     hr = wined3d_device_get_display_mode(This->wined3d_device, 0, &d3ddm);
4946
4947     for (i = 0; i < (sizeof(formats) / sizeof(*formats)); ++i)
4948     {
4949         hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, type, d3ddm.Format,
4950                 WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, formats[i], SURFACE_OPENGL);
4951         if (SUCCEEDED(hr))
4952         {
4953             DDPIXELFORMAT pformat;
4954
4955             memset(&pformat, 0, sizeof(pformat));
4956             pformat.dwSize = sizeof(pformat);
4957             PixelFormat_WineD3DtoDD(&pformat, formats[i]);
4958
4959             TRACE("Enumerating wined3d format %#x.\n", formats[i]);
4960             hr = callback(&pformat, context);
4961             if (hr != DDENUMRET_OK)
4962             {
4963                 TRACE("Format enumeration cancelled by application.\n");
4964                 LeaveCriticalSection(&ddraw_cs);
4965                 return D3D_OK;
4966             }
4967         }
4968     }
4969     TRACE("End of enumeration.\n");
4970
4971     LeaveCriticalSection(&ddraw_cs);
4972     return D3D_OK;
4973 }
4974
4975 static HRESULT WINAPI d3d3_EnumZBufferFormats(IDirect3D3 *iface, REFCLSID device_iid,
4976         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4977 {
4978     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4979
4980     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4981             iface, debugstr_guid(device_iid), callback, context);
4982
4983     return d3d7_EnumZBufferFormats(&This->IDirect3D7_iface, device_iid, callback, context);
4984 }
4985
4986 /*****************************************************************************
4987  * IDirect3D7::EvictManagedTextures
4988  *
4989  * Removes all managed textures (=surfaces with DDSCAPS2_TEXTUREMANAGE or
4990  * DDSCAPS2_D3DTEXTUREMANAGE caps) to be removed from video memory.
4991  *
4992  * Version 3 and 7
4993  *
4994  * Returns:
4995  *  D3D_OK, because it's a stub
4996  *
4997  *****************************************************************************/
4998 static HRESULT WINAPI d3d7_EvictManagedTextures(IDirect3D7 *iface)
4999 {
5000     FIXME("iface %p stub!\n", iface);
5001
5002     /* TODO: Just enumerate resources using IWineD3DDevice_EnumResources(),
5003      * then unload surfaces / textures. */
5004
5005     return D3D_OK;
5006 }
5007
5008 static HRESULT WINAPI d3d3_EvictManagedTextures(IDirect3D3 *iface)
5009 {
5010     IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
5011
5012     TRACE("iface %p.\n", iface);
5013
5014     return d3d7_EvictManagedTextures(&This->IDirect3D7_iface);
5015 }
5016
5017 /*****************************************************************************
5018  * IDirect3DImpl_GetCaps
5019  *
5020  * This function retrieves the device caps from wined3d
5021  * and converts it into a D3D7 and D3D - D3D3 structure
5022  * This is a helper function called from various places in ddraw
5023  *
5024  * Params:
5025  *  wined3d: The interface to get the caps from
5026  *  desc1: Old D3D <3 structure to fill (needed)
5027  *  desc7: D3D7 device desc structure to fill (needed)
5028  *
5029  * Returns
5030  *  D3D_OK on success, or the return value of IWineD3D::GetCaps
5031  *
5032  *****************************************************************************/
5033 HRESULT IDirect3DImpl_GetCaps(const struct wined3d *wined3d, D3DDEVICEDESC *desc1, D3DDEVICEDESC7 *desc7)
5034 {
5035     WINED3DCAPS wined3d_caps;
5036     HRESULT hr;
5037
5038     TRACE("wined3d %p, desc1 %p, desc7 %p.\n", wined3d, desc1, desc7);
5039
5040     memset(&wined3d_caps, 0, sizeof(wined3d_caps));
5041
5042     EnterCriticalSection(&ddraw_cs);
5043     hr = wined3d_get_device_caps(wined3d, 0, WINED3DDEVTYPE_HAL, &wined3d_caps);
5044     LeaveCriticalSection(&ddraw_cs);
5045     if (FAILED(hr))
5046     {
5047         WARN("Failed to get device caps, hr %#x.\n", hr);
5048         return hr;
5049     }
5050
5051     /* Copy the results into the d3d7 and d3d3 structures */
5052     desc7->dwDevCaps = wined3d_caps.DevCaps;
5053     desc7->dpcLineCaps.dwMiscCaps = wined3d_caps.PrimitiveMiscCaps;
5054     desc7->dpcLineCaps.dwRasterCaps = wined3d_caps.RasterCaps;
5055     desc7->dpcLineCaps.dwZCmpCaps = wined3d_caps.ZCmpCaps;
5056     desc7->dpcLineCaps.dwSrcBlendCaps = wined3d_caps.SrcBlendCaps;
5057     desc7->dpcLineCaps.dwDestBlendCaps = wined3d_caps.DestBlendCaps;
5058     desc7->dpcLineCaps.dwAlphaCmpCaps = wined3d_caps.AlphaCmpCaps;
5059     desc7->dpcLineCaps.dwShadeCaps = wined3d_caps.ShadeCaps;
5060     desc7->dpcLineCaps.dwTextureCaps = wined3d_caps.TextureCaps;
5061     desc7->dpcLineCaps.dwTextureFilterCaps = wined3d_caps.TextureFilterCaps;
5062     desc7->dpcLineCaps.dwTextureAddressCaps = wined3d_caps.TextureAddressCaps;
5063
5064     desc7->dwMaxTextureWidth = wined3d_caps.MaxTextureWidth;
5065     desc7->dwMaxTextureHeight = wined3d_caps.MaxTextureHeight;
5066
5067     desc7->dwMaxTextureRepeat = wined3d_caps.MaxTextureRepeat;
5068     desc7->dwMaxTextureAspectRatio = wined3d_caps.MaxTextureAspectRatio;
5069     desc7->dwMaxAnisotropy = wined3d_caps.MaxAnisotropy;
5070     desc7->dvMaxVertexW = wined3d_caps.MaxVertexW;
5071
5072     desc7->dvGuardBandLeft = wined3d_caps.GuardBandLeft;
5073     desc7->dvGuardBandTop = wined3d_caps.GuardBandTop;
5074     desc7->dvGuardBandRight = wined3d_caps.GuardBandRight;
5075     desc7->dvGuardBandBottom = wined3d_caps.GuardBandBottom;
5076
5077     desc7->dvExtentsAdjust = wined3d_caps.ExtentsAdjust;
5078     desc7->dwStencilCaps = wined3d_caps.StencilCaps;
5079
5080     desc7->dwFVFCaps = wined3d_caps.FVFCaps;
5081     desc7->dwTextureOpCaps = wined3d_caps.TextureOpCaps;
5082
5083     desc7->dwVertexProcessingCaps = wined3d_caps.VertexProcessingCaps;
5084     desc7->dwMaxActiveLights = wined3d_caps.MaxActiveLights;
5085
5086     /* Remove all non-d3d7 caps */
5087     desc7->dwDevCaps &= (
5088         D3DDEVCAPS_FLOATTLVERTEX         | D3DDEVCAPS_SORTINCREASINGZ          | D3DDEVCAPS_SORTDECREASINGZ          |
5089         D3DDEVCAPS_SORTEXACT             | D3DDEVCAPS_EXECUTESYSTEMMEMORY      | D3DDEVCAPS_EXECUTEVIDEOMEMORY       |
5090         D3DDEVCAPS_TLVERTEXSYSTEMMEMORY  | D3DDEVCAPS_TLVERTEXVIDEOMEMORY      | D3DDEVCAPS_TEXTURESYSTEMMEMORY      |
5091         D3DDEVCAPS_TEXTUREVIDEOMEMORY    | D3DDEVCAPS_DRAWPRIMTLVERTEX         | D3DDEVCAPS_CANRENDERAFTERFLIP       |
5092         D3DDEVCAPS_TEXTURENONLOCALVIDMEM | D3DDEVCAPS_DRAWPRIMITIVES2          | D3DDEVCAPS_SEPARATETEXTUREMEMORIES  |
5093         D3DDEVCAPS_DRAWPRIMITIVES2EX     | D3DDEVCAPS_HWTRANSFORMANDLIGHT      | D3DDEVCAPS_CANBLTSYSTONONLOCAL      |
5094         D3DDEVCAPS_HWRASTERIZATION);
5095
5096     desc7->dwStencilCaps &= (
5097         D3DSTENCILCAPS_KEEP              | D3DSTENCILCAPS_ZERO                 | D3DSTENCILCAPS_REPLACE              |
5098         D3DSTENCILCAPS_INCRSAT           | D3DSTENCILCAPS_DECRSAT              | D3DSTENCILCAPS_INVERT               |
5099         D3DSTENCILCAPS_INCR              | D3DSTENCILCAPS_DECR);
5100
5101     /* FVF caps ?*/
5102
5103     desc7->dwTextureOpCaps &= (
5104         D3DTEXOPCAPS_DISABLE             | D3DTEXOPCAPS_SELECTARG1             | D3DTEXOPCAPS_SELECTARG2             |
5105         D3DTEXOPCAPS_MODULATE            | D3DTEXOPCAPS_MODULATE2X             | D3DTEXOPCAPS_MODULATE4X             |
5106         D3DTEXOPCAPS_ADD                 | D3DTEXOPCAPS_ADDSIGNED              | D3DTEXOPCAPS_ADDSIGNED2X            |
5107         D3DTEXOPCAPS_SUBTRACT            | D3DTEXOPCAPS_ADDSMOOTH              | D3DTEXOPCAPS_BLENDTEXTUREALPHA      |
5108         D3DTEXOPCAPS_BLENDFACTORALPHA    | D3DTEXOPCAPS_BLENDTEXTUREALPHAPM    | D3DTEXOPCAPS_BLENDCURRENTALPHA      |
5109         D3DTEXOPCAPS_PREMODULATE         | D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA |
5110         D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | D3DTEXOPCAPS_BUMPENVMAP    |
5111         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE | D3DTEXOPCAPS_DOTPRODUCT3);
5112
5113     desc7->dwVertexProcessingCaps &= (
5114         D3DVTXPCAPS_TEXGEN               | D3DVTXPCAPS_MATERIALSOURCE7         | D3DVTXPCAPS_VERTEXFOG               |
5115         D3DVTXPCAPS_DIRECTIONALLIGHTS    | D3DVTXPCAPS_POSITIONALLIGHTS        | D3DVTXPCAPS_LOCALVIEWER);
5116
5117     desc7->dpcLineCaps.dwMiscCaps &= (
5118         D3DPMISCCAPS_MASKPLANES          | D3DPMISCCAPS_MASKZ                  | D3DPMISCCAPS_LINEPATTERNREP         |
5119         D3DPMISCCAPS_CONFORMANT          | D3DPMISCCAPS_CULLNONE               | D3DPMISCCAPS_CULLCW                 |
5120         D3DPMISCCAPS_CULLCCW);
5121
5122     desc7->dpcLineCaps.dwRasterCaps &= (
5123         D3DPRASTERCAPS_DITHER            | D3DPRASTERCAPS_ROP2                 | D3DPRASTERCAPS_XOR                  |
5124         D3DPRASTERCAPS_PAT               | D3DPRASTERCAPS_ZTEST                | D3DPRASTERCAPS_SUBPIXEL             |
5125         D3DPRASTERCAPS_SUBPIXELX         | D3DPRASTERCAPS_FOGVERTEX            | D3DPRASTERCAPS_FOGTABLE             |
5126         D3DPRASTERCAPS_STIPPLE           | D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT | D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT |
5127         D3DPRASTERCAPS_ANTIALIASEDGES    | D3DPRASTERCAPS_MIPMAPLODBIAS        | D3DPRASTERCAPS_ZBIAS                |
5128         D3DPRASTERCAPS_ZBUFFERLESSHSR    | D3DPRASTERCAPS_FOGRANGE             | D3DPRASTERCAPS_ANISOTROPY           |
5129         D3DPRASTERCAPS_WBUFFER           | D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT | D3DPRASTERCAPS_WFOG           |
5130         D3DPRASTERCAPS_ZFOG);
5131
5132     desc7->dpcLineCaps.dwZCmpCaps &= (
5133         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
5134         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
5135         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
5136
5137     desc7->dpcLineCaps.dwSrcBlendCaps &= (
5138         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
5139         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
5140         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
5141         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
5142         D3DPBLENDCAPS_BOTHINVSRCALPHA);
5143
5144     desc7->dpcLineCaps.dwDestBlendCaps &= (
5145         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
5146         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
5147         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
5148         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
5149         D3DPBLENDCAPS_BOTHINVSRCALPHA);
5150
5151     desc7->dpcLineCaps.dwAlphaCmpCaps &= (
5152         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
5153         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
5154         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
5155
5156     desc7->dpcLineCaps.dwShadeCaps &= (
5157         D3DPSHADECAPS_COLORFLATMONO      | D3DPSHADECAPS_COLORFLATRGB          | D3DPSHADECAPS_COLORGOURAUDMONO      |
5158         D3DPSHADECAPS_COLORGOURAUDRGB    | D3DPSHADECAPS_COLORPHONGMONO        | D3DPSHADECAPS_COLORPHONGRGB         |
5159         D3DPSHADECAPS_SPECULARFLATMONO   | D3DPSHADECAPS_SPECULARFLATRGB       | D3DPSHADECAPS_SPECULARGOURAUDMONO   |
5160         D3DPSHADECAPS_SPECULARGOURAUDRGB | D3DPSHADECAPS_SPECULARPHONGMONO     | D3DPSHADECAPS_SPECULARPHONGRGB      |
5161         D3DPSHADECAPS_ALPHAFLATBLEND     | D3DPSHADECAPS_ALPHAFLATSTIPPLED     | D3DPSHADECAPS_ALPHAGOURAUDBLEND     |
5162         D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED | D3DPSHADECAPS_ALPHAPHONGBLEND     | D3DPSHADECAPS_ALPHAPHONGSTIPPLED    |
5163         D3DPSHADECAPS_FOGFLAT            | D3DPSHADECAPS_FOGGOURAUD            | D3DPSHADECAPS_FOGPHONG);
5164
5165     desc7->dpcLineCaps.dwTextureCaps &= (
5166         D3DPTEXTURECAPS_PERSPECTIVE      | D3DPTEXTURECAPS_POW2                | D3DPTEXTURECAPS_ALPHA               |
5167         D3DPTEXTURECAPS_TRANSPARENCY     | D3DPTEXTURECAPS_BORDER              | D3DPTEXTURECAPS_SQUAREONLY          |
5168         D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE | D3DPTEXTURECAPS_ALPHAPALETTE| D3DPTEXTURECAPS_NONPOW2CONDITIONAL  |
5169         D3DPTEXTURECAPS_PROJECTED        | D3DPTEXTURECAPS_CUBEMAP             | D3DPTEXTURECAPS_COLORKEYBLEND);
5170
5171     desc7->dpcLineCaps.dwTextureFilterCaps &= (
5172         D3DPTFILTERCAPS_NEAREST          | D3DPTFILTERCAPS_LINEAR              | D3DPTFILTERCAPS_MIPNEAREST          |
5173         D3DPTFILTERCAPS_MIPLINEAR        | D3DPTFILTERCAPS_LINEARMIPNEAREST    | D3DPTFILTERCAPS_LINEARMIPLINEAR     |
5174         D3DPTFILTERCAPS_MINFPOINT        | D3DPTFILTERCAPS_MINFLINEAR          | D3DPTFILTERCAPS_MINFANISOTROPIC     |
5175         D3DPTFILTERCAPS_MIPFPOINT        | D3DPTFILTERCAPS_MIPFLINEAR          | D3DPTFILTERCAPS_MAGFPOINT           |
5176         D3DPTFILTERCAPS_MAGFLINEAR       | D3DPTFILTERCAPS_MAGFANISOTROPIC     | D3DPTFILTERCAPS_MAGFAFLATCUBIC      |
5177         D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
5178
5179     desc7->dpcLineCaps.dwTextureBlendCaps &= (
5180         D3DPTBLENDCAPS_DECAL             | D3DPTBLENDCAPS_MODULATE             | D3DPTBLENDCAPS_DECALALPHA           |
5181         D3DPTBLENDCAPS_MODULATEALPHA     | D3DPTBLENDCAPS_DECALMASK            | D3DPTBLENDCAPS_MODULATEMASK         |
5182         D3DPTBLENDCAPS_COPY              | D3DPTBLENDCAPS_ADD);
5183
5184     desc7->dpcLineCaps.dwTextureAddressCaps &= (
5185         D3DPTADDRESSCAPS_WRAP            | D3DPTADDRESSCAPS_MIRROR             | D3DPTADDRESSCAPS_CLAMP              |
5186         D3DPTADDRESSCAPS_BORDER          | D3DPTADDRESSCAPS_INDEPENDENTUV);
5187
5188     if (!(desc7->dpcLineCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2))
5189     {
5190         /* DirectX7 always has the np2 flag set, no matter what the card
5191          * supports. Some old games (Rollcage) check the caps incorrectly.
5192          * If wined3d supports nonpow2 textures it also has np2 conditional
5193          * support. */
5194         desc7->dpcLineCaps.dwTextureCaps |= D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL;
5195     }
5196
5197     /* Fill the missing members, and do some fixup */
5198     desc7->dpcLineCaps.dwSize = sizeof(desc7->dpcLineCaps);
5199     desc7->dpcLineCaps.dwTextureBlendCaps = D3DPTBLENDCAPS_ADD | D3DPTBLENDCAPS_MODULATEMASK |
5200                                             D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_DECAL |
5201                                             D3DPTBLENDCAPS_DECALALPHA | D3DPTBLENDCAPS_DECALMASK |
5202                                             D3DPTBLENDCAPS_MODULATE | D3DPTBLENDCAPS_MODULATEALPHA;
5203     desc7->dpcLineCaps.dwStippleWidth = 32;
5204     desc7->dpcLineCaps.dwStippleHeight = 32;
5205     /* Use the same for the TriCaps */
5206     desc7->dpcTriCaps = desc7->dpcLineCaps;
5207
5208     desc7->dwDeviceRenderBitDepth = DDBD_16 | DDBD_24 | DDBD_32;
5209     desc7->dwDeviceZBufferBitDepth = DDBD_16 | DDBD_24;
5210     desc7->dwMinTextureWidth = 1;
5211     desc7->dwMinTextureHeight = 1;
5212
5213     /* Convert DWORDs safely to WORDs */
5214     if (wined3d_caps.MaxTextureBlendStages > 0xffff) desc7->wMaxTextureBlendStages = 0xffff;
5215     else desc7->wMaxTextureBlendStages = (WORD)wined3d_caps.MaxTextureBlendStages;
5216     if (wined3d_caps.MaxSimultaneousTextures > 0xffff) desc7->wMaxSimultaneousTextures = 0xffff;
5217     else desc7->wMaxSimultaneousTextures = (WORD)wined3d_caps.MaxSimultaneousTextures;
5218
5219     if (wined3d_caps.MaxUserClipPlanes > 0xffff) desc7->wMaxUserClipPlanes = 0xffff;
5220     else desc7->wMaxUserClipPlanes = (WORD)wined3d_caps.MaxUserClipPlanes;
5221     if (wined3d_caps.MaxVertexBlendMatrices > 0xffff) desc7->wMaxVertexBlendMatrices = 0xffff;
5222     else desc7->wMaxVertexBlendMatrices = (WORD)wined3d_caps.MaxVertexBlendMatrices;
5223
5224     desc7->deviceGUID = IID_IDirect3DTnLHalDevice;
5225
5226     desc7->dwReserved1 = 0;
5227     desc7->dwReserved2 = 0;
5228     desc7->dwReserved3 = 0;
5229     desc7->dwReserved4 = 0;
5230
5231     /* Fill the old structure */
5232     memset(desc1, 0, sizeof(*desc1));
5233     desc1->dwSize = sizeof(D3DDEVICEDESC);
5234     desc1->dwFlags = D3DDD_COLORMODEL
5235             | D3DDD_DEVCAPS
5236             | D3DDD_TRANSFORMCAPS
5237             | D3DDD_BCLIPPING
5238             | D3DDD_LIGHTINGCAPS
5239             | D3DDD_LINECAPS
5240             | D3DDD_TRICAPS
5241             | D3DDD_DEVICERENDERBITDEPTH
5242             | D3DDD_DEVICEZBUFFERBITDEPTH
5243             | D3DDD_MAXBUFFERSIZE
5244             | D3DDD_MAXVERTEXCOUNT;
5245
5246     desc1->dcmColorModel = D3DCOLOR_RGB;
5247     desc1->dwDevCaps = desc7->dwDevCaps;
5248     desc1->dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
5249     desc1->dtcTransformCaps.dwCaps = D3DTRANSFORMCAPS_CLIP;
5250     desc1->bClipping = TRUE;
5251     desc1->dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
5252     desc1->dlcLightingCaps.dwCaps = D3DLIGHTCAPS_DIRECTIONAL
5253             | D3DLIGHTCAPS_PARALLELPOINT
5254             | D3DLIGHTCAPS_POINT
5255             | D3DLIGHTCAPS_SPOT;
5256
5257     desc1->dlcLightingCaps.dwLightingModel = D3DLIGHTINGMODEL_RGB;
5258     desc1->dlcLightingCaps.dwNumLights = desc7->dwMaxActiveLights;
5259
5260     desc1->dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
5261     desc1->dpcLineCaps.dwMiscCaps = desc7->dpcLineCaps.dwMiscCaps;
5262     desc1->dpcLineCaps.dwRasterCaps = desc7->dpcLineCaps.dwRasterCaps;
5263     desc1->dpcLineCaps.dwZCmpCaps = desc7->dpcLineCaps.dwZCmpCaps;
5264     desc1->dpcLineCaps.dwSrcBlendCaps = desc7->dpcLineCaps.dwSrcBlendCaps;
5265     desc1->dpcLineCaps.dwDestBlendCaps = desc7->dpcLineCaps.dwDestBlendCaps;
5266     desc1->dpcLineCaps.dwShadeCaps = desc7->dpcLineCaps.dwShadeCaps;
5267     desc1->dpcLineCaps.dwTextureCaps = desc7->dpcLineCaps.dwTextureCaps;
5268     desc1->dpcLineCaps.dwTextureFilterCaps = desc7->dpcLineCaps.dwTextureFilterCaps;
5269     desc1->dpcLineCaps.dwTextureBlendCaps = desc7->dpcLineCaps.dwTextureBlendCaps;
5270     desc1->dpcLineCaps.dwTextureAddressCaps = desc7->dpcLineCaps.dwTextureAddressCaps;
5271     desc1->dpcLineCaps.dwStippleWidth = desc7->dpcLineCaps.dwStippleWidth;
5272     desc1->dpcLineCaps.dwAlphaCmpCaps = desc7->dpcLineCaps.dwAlphaCmpCaps;
5273
5274     desc1->dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
5275     desc1->dpcTriCaps.dwMiscCaps = desc7->dpcTriCaps.dwMiscCaps;
5276     desc1->dpcTriCaps.dwRasterCaps = desc7->dpcTriCaps.dwRasterCaps;
5277     desc1->dpcTriCaps.dwZCmpCaps = desc7->dpcTriCaps.dwZCmpCaps;
5278     desc1->dpcTriCaps.dwSrcBlendCaps = desc7->dpcTriCaps.dwSrcBlendCaps;
5279     desc1->dpcTriCaps.dwDestBlendCaps = desc7->dpcTriCaps.dwDestBlendCaps;
5280     desc1->dpcTriCaps.dwShadeCaps = desc7->dpcTriCaps.dwShadeCaps;
5281     desc1->dpcTriCaps.dwTextureCaps = desc7->dpcTriCaps.dwTextureCaps;
5282     desc1->dpcTriCaps.dwTextureFilterCaps = desc7->dpcTriCaps.dwTextureFilterCaps;
5283     desc1->dpcTriCaps.dwTextureBlendCaps = desc7->dpcTriCaps.dwTextureBlendCaps;
5284     desc1->dpcTriCaps.dwTextureAddressCaps = desc7->dpcTriCaps.dwTextureAddressCaps;
5285     desc1->dpcTriCaps.dwStippleWidth = desc7->dpcTriCaps.dwStippleWidth;
5286     desc1->dpcTriCaps.dwAlphaCmpCaps = desc7->dpcTriCaps.dwAlphaCmpCaps;
5287
5288     desc1->dwDeviceRenderBitDepth = desc7->dwDeviceRenderBitDepth;
5289     desc1->dwDeviceZBufferBitDepth = desc7->dwDeviceZBufferBitDepth;
5290     desc1->dwMaxBufferSize = 0;
5291     desc1->dwMaxVertexCount = 65536;
5292     desc1->dwMinTextureWidth  = desc7->dwMinTextureWidth;
5293     desc1->dwMinTextureHeight = desc7->dwMinTextureHeight;
5294     desc1->dwMaxTextureWidth  = desc7->dwMaxTextureWidth;
5295     desc1->dwMaxTextureHeight = desc7->dwMaxTextureHeight;
5296     desc1->dwMinStippleWidth  = 1;
5297     desc1->dwMinStippleHeight = 1;
5298     desc1->dwMaxStippleWidth  = 32;
5299     desc1->dwMaxStippleHeight = 32;
5300     desc1->dwMaxTextureRepeat = desc7->dwMaxTextureRepeat;
5301     desc1->dwMaxTextureAspectRatio = desc7->dwMaxTextureAspectRatio;
5302     desc1->dwMaxAnisotropy = desc7->dwMaxAnisotropy;
5303     desc1->dvGuardBandLeft = desc7->dvGuardBandLeft;
5304     desc1->dvGuardBandRight = desc7->dvGuardBandRight;
5305     desc1->dvGuardBandTop = desc7->dvGuardBandTop;
5306     desc1->dvGuardBandBottom = desc7->dvGuardBandBottom;
5307     desc1->dvExtentsAdjust = desc7->dvExtentsAdjust;
5308     desc1->dwStencilCaps = desc7->dwStencilCaps;
5309     desc1->dwFVFCaps = desc7->dwFVFCaps;
5310     desc1->dwTextureOpCaps = desc7->dwTextureOpCaps;
5311     desc1->wMaxTextureBlendStages = desc7->wMaxTextureBlendStages;
5312     desc1->wMaxSimultaneousTextures = desc7->wMaxSimultaneousTextures;
5313
5314     return DD_OK;
5315 }
5316
5317 /*****************************************************************************
5318  * IDirectDraw7 VTable
5319  *****************************************************************************/
5320 static const struct IDirectDraw7Vtbl ddraw7_vtbl =
5321 {
5322     /* IUnknown */
5323     ddraw7_QueryInterface,
5324     ddraw7_AddRef,
5325     ddraw7_Release,
5326     /* IDirectDraw */
5327     ddraw7_Compact,
5328     ddraw7_CreateClipper,
5329     ddraw7_CreatePalette,
5330     ddraw7_CreateSurface,
5331     ddraw7_DuplicateSurface,
5332     ddraw7_EnumDisplayModes,
5333     ddraw7_EnumSurfaces,
5334     ddraw7_FlipToGDISurface,
5335     ddraw7_GetCaps,
5336     ddraw7_GetDisplayMode,
5337     ddraw7_GetFourCCCodes,
5338     ddraw7_GetGDISurface,
5339     ddraw7_GetMonitorFrequency,
5340     ddraw7_GetScanLine,
5341     ddraw7_GetVerticalBlankStatus,
5342     ddraw7_Initialize,
5343     ddraw7_RestoreDisplayMode,
5344     ddraw7_SetCooperativeLevel,
5345     ddraw7_SetDisplayMode,
5346     ddraw7_WaitForVerticalBlank,
5347     /* IDirectDraw2 */
5348     ddraw7_GetAvailableVidMem,
5349     /* IDirectDraw3 */
5350     ddraw7_GetSurfaceFromDC,
5351     /* IDirectDraw4 */
5352     ddraw7_RestoreAllSurfaces,
5353     ddraw7_TestCooperativeLevel,
5354     ddraw7_GetDeviceIdentifier,
5355     /* IDirectDraw7 */
5356     ddraw7_StartModeTest,
5357     ddraw7_EvaluateMode
5358 };
5359
5360 static const struct IDirectDraw4Vtbl ddraw4_vtbl =
5361 {
5362     /* IUnknown */
5363     ddraw4_QueryInterface,
5364     ddraw4_AddRef,
5365     ddraw4_Release,
5366     /* IDirectDraw */
5367     ddraw4_Compact,
5368     ddraw4_CreateClipper,
5369     ddraw4_CreatePalette,
5370     ddraw4_CreateSurface,
5371     ddraw4_DuplicateSurface,
5372     ddraw4_EnumDisplayModes,
5373     ddraw4_EnumSurfaces,
5374     ddraw4_FlipToGDISurface,
5375     ddraw4_GetCaps,
5376     ddraw4_GetDisplayMode,
5377     ddraw4_GetFourCCCodes,
5378     ddraw4_GetGDISurface,
5379     ddraw4_GetMonitorFrequency,
5380     ddraw4_GetScanLine,
5381     ddraw4_GetVerticalBlankStatus,
5382     ddraw4_Initialize,
5383     ddraw4_RestoreDisplayMode,
5384     ddraw4_SetCooperativeLevel,
5385     ddraw4_SetDisplayMode,
5386     ddraw4_WaitForVerticalBlank,
5387     /* IDirectDraw2 */
5388     ddraw4_GetAvailableVidMem,
5389     /* IDirectDraw3 */
5390     ddraw4_GetSurfaceFromDC,
5391     /* IDirectDraw4 */
5392     ddraw4_RestoreAllSurfaces,
5393     ddraw4_TestCooperativeLevel,
5394     ddraw4_GetDeviceIdentifier,
5395 };
5396
5397 static const struct IDirectDraw3Vtbl ddraw3_vtbl =
5398 {
5399     /* IUnknown */
5400     ddraw3_QueryInterface,
5401     ddraw3_AddRef,
5402     ddraw3_Release,
5403     /* IDirectDraw */
5404     ddraw3_Compact,
5405     ddraw3_CreateClipper,
5406     ddraw3_CreatePalette,
5407     ddraw3_CreateSurface,
5408     ddraw3_DuplicateSurface,
5409     ddraw3_EnumDisplayModes,
5410     ddraw3_EnumSurfaces,
5411     ddraw3_FlipToGDISurface,
5412     ddraw3_GetCaps,
5413     ddraw3_GetDisplayMode,
5414     ddraw3_GetFourCCCodes,
5415     ddraw3_GetGDISurface,
5416     ddraw3_GetMonitorFrequency,
5417     ddraw3_GetScanLine,
5418     ddraw3_GetVerticalBlankStatus,
5419     ddraw3_Initialize,
5420     ddraw3_RestoreDisplayMode,
5421     ddraw3_SetCooperativeLevel,
5422     ddraw3_SetDisplayMode,
5423     ddraw3_WaitForVerticalBlank,
5424     /* IDirectDraw2 */
5425     ddraw3_GetAvailableVidMem,
5426     /* IDirectDraw3 */
5427     ddraw3_GetSurfaceFromDC,
5428 };
5429
5430 static const struct IDirectDraw2Vtbl ddraw2_vtbl =
5431 {
5432     /* IUnknown */
5433     ddraw2_QueryInterface,
5434     ddraw2_AddRef,
5435     ddraw2_Release,
5436     /* IDirectDraw */
5437     ddraw2_Compact,
5438     ddraw2_CreateClipper,
5439     ddraw2_CreatePalette,
5440     ddraw2_CreateSurface,
5441     ddraw2_DuplicateSurface,
5442     ddraw2_EnumDisplayModes,
5443     ddraw2_EnumSurfaces,
5444     ddraw2_FlipToGDISurface,
5445     ddraw2_GetCaps,
5446     ddraw2_GetDisplayMode,
5447     ddraw2_GetFourCCCodes,
5448     ddraw2_GetGDISurface,
5449     ddraw2_GetMonitorFrequency,
5450     ddraw2_GetScanLine,
5451     ddraw2_GetVerticalBlankStatus,
5452     ddraw2_Initialize,
5453     ddraw2_RestoreDisplayMode,
5454     ddraw2_SetCooperativeLevel,
5455     ddraw2_SetDisplayMode,
5456     ddraw2_WaitForVerticalBlank,
5457     /* IDirectDraw2 */
5458     ddraw2_GetAvailableVidMem,
5459 };
5460
5461 static const struct IDirectDrawVtbl ddraw1_vtbl =
5462 {
5463     /* IUnknown */
5464     ddraw1_QueryInterface,
5465     ddraw1_AddRef,
5466     ddraw1_Release,
5467     /* IDirectDraw */
5468     ddraw1_Compact,
5469     ddraw1_CreateClipper,
5470     ddraw1_CreatePalette,
5471     ddraw1_CreateSurface,
5472     ddraw1_DuplicateSurface,
5473     ddraw1_EnumDisplayModes,
5474     ddraw1_EnumSurfaces,
5475     ddraw1_FlipToGDISurface,
5476     ddraw1_GetCaps,
5477     ddraw1_GetDisplayMode,
5478     ddraw1_GetFourCCCodes,
5479     ddraw1_GetGDISurface,
5480     ddraw1_GetMonitorFrequency,
5481     ddraw1_GetScanLine,
5482     ddraw1_GetVerticalBlankStatus,
5483     ddraw1_Initialize,
5484     ddraw1_RestoreDisplayMode,
5485     ddraw1_SetCooperativeLevel,
5486     ddraw1_SetDisplayMode,
5487     ddraw1_WaitForVerticalBlank,
5488 };
5489
5490 static const struct IDirect3D7Vtbl d3d7_vtbl =
5491 {
5492     /* IUnknown methods */
5493     d3d7_QueryInterface,
5494     d3d7_AddRef,
5495     d3d7_Release,
5496     /* IDirect3D7 methods */
5497     d3d7_EnumDevices,
5498     d3d7_CreateDevice,
5499     d3d7_CreateVertexBuffer,
5500     d3d7_EnumZBufferFormats,
5501     d3d7_EvictManagedTextures
5502 };
5503
5504 static const struct IDirect3D3Vtbl d3d3_vtbl =
5505 {
5506     /* IUnknown methods */
5507     d3d3_QueryInterface,
5508     d3d3_AddRef,
5509     d3d3_Release,
5510     /* IDirect3D3 methods */
5511     d3d3_EnumDevices,
5512     d3d3_CreateLight,
5513     d3d3_CreateMaterial,
5514     d3d3_CreateViewport,
5515     d3d3_FindDevice,
5516     d3d3_CreateDevice,
5517     d3d3_CreateVertexBuffer,
5518     d3d3_EnumZBufferFormats,
5519     d3d3_EvictManagedTextures
5520 };
5521
5522 static const struct IDirect3D2Vtbl d3d2_vtbl =
5523 {
5524     /* IUnknown methods */
5525     d3d2_QueryInterface,
5526     d3d2_AddRef,
5527     d3d2_Release,
5528     /* IDirect3D2 methods */
5529     d3d2_EnumDevices,
5530     d3d2_CreateLight,
5531     d3d2_CreateMaterial,
5532     d3d2_CreateViewport,
5533     d3d2_FindDevice,
5534     d3d2_CreateDevice
5535 };
5536
5537 static const struct IDirect3DVtbl d3d1_vtbl =
5538 {
5539     /* IUnknown methods */
5540     d3d1_QueryInterface,
5541     d3d1_AddRef,
5542     d3d1_Release,
5543     /* IDirect3D methods */
5544     d3d1_Initialize,
5545     d3d1_EnumDevices,
5546     d3d1_CreateLight,
5547     d3d1_CreateMaterial,
5548     d3d1_CreateViewport,
5549     d3d1_FindDevice
5550 };
5551
5552 /*****************************************************************************
5553  * ddraw_find_decl
5554  *
5555  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
5556  * if none was found.
5557  *
5558  * This function is in ddraw.c and the DDraw object space because D3D7
5559  * vertex buffers are created using the IDirect3D interface to the ddraw
5560  * object, so they can be valid across D3D devices(theoretically. The ddraw
5561  * object also owns the wined3d device
5562  *
5563  * Parameters:
5564  *  This: Device
5565  *  fvf: Fvf to find the decl for
5566  *
5567  * Returns:
5568  *  NULL in case of an error, the vertex declaration for the FVF otherwise.
5569  *
5570  *****************************************************************************/
5571 struct wined3d_vertex_declaration *ddraw_find_decl(IDirectDrawImpl *This, DWORD fvf)
5572 {
5573     struct wined3d_vertex_declaration *pDecl = NULL;
5574     HRESULT hr;
5575     int p, low, high; /* deliberately signed */
5576     struct FvfToDecl *convertedDecls = This->decls;
5577
5578     TRACE("Searching for declaration for fvf %08x... ", fvf);
5579
5580     low = 0;
5581     high = This->numConvertedDecls - 1;
5582     while(low <= high) {
5583         p = (low + high) >> 1;
5584         TRACE("%d ", p);
5585         if(convertedDecls[p].fvf == fvf) {
5586             TRACE("found %p\n", convertedDecls[p].decl);
5587             return convertedDecls[p].decl;
5588         } else if(convertedDecls[p].fvf < fvf) {
5589             low = p + 1;
5590         } else {
5591             high = p - 1;
5592         }
5593     }
5594     TRACE("not found. Creating and inserting at position %d.\n", low);
5595
5596     hr = wined3d_vertex_declaration_create_from_fvf(This->wined3d_device,
5597             fvf, This, &ddraw_null_wined3d_parent_ops, &pDecl);
5598     if (hr != S_OK) return NULL;
5599
5600     if(This->declArraySize == This->numConvertedDecls) {
5601         int grow = max(This->declArraySize / 2, 8);
5602         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
5603                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
5604         if (!convertedDecls)
5605         {
5606             wined3d_vertex_declaration_decref(pDecl);
5607             return NULL;
5608         }
5609         This->decls = convertedDecls;
5610         This->declArraySize += grow;
5611     }
5612
5613     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
5614     convertedDecls[low].decl = pDecl;
5615     convertedDecls[low].fvf = fvf;
5616     This->numConvertedDecls++;
5617
5618     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
5619     return pDecl;
5620 }
5621
5622 static inline struct IDirectDrawImpl *ddraw_from_device_parent(struct wined3d_device_parent *device_parent)
5623 {
5624     return CONTAINING_RECORD(device_parent, struct IDirectDrawImpl, device_parent);
5625 }
5626
5627 static void CDECL device_parent_wined3d_device_created(struct wined3d_device_parent *device_parent,
5628         struct wined3d_device *device)
5629 {
5630     TRACE("device_parent %p, device %p.\n", device_parent, device);
5631 }
5632
5633 static HRESULT CDECL device_parent_create_surface(struct wined3d_device_parent *device_parent,
5634         void *container_parent, UINT width, UINT height, enum wined3d_format_id format, DWORD usage,
5635         WINED3DPOOL pool, UINT level, WINED3DCUBEMAP_FACES face, struct wined3d_surface **surface)
5636 {
5637     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5638     IDirectDrawSurfaceImpl *surf = NULL;
5639     UINT i = 0;
5640     DDSCAPS2 searchcaps = ddraw->tex_root->surface_desc.ddsCaps;
5641
5642     TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, usage %#x,\n"
5643             "\tpool %#x, level %u, face %u, surface %p.\n",
5644             device_parent, container_parent, width, height, format, usage, pool, level, face, surface);
5645
5646     searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
5647     switch(face)
5648     {
5649         case WINED3DCUBEMAP_FACE_POSITIVE_X:
5650             TRACE("Asked for positive x\n");
5651             if (searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP)
5652             {
5653                 searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
5654             }
5655             surf = ddraw->tex_root; break;
5656         case WINED3DCUBEMAP_FACE_NEGATIVE_X:
5657             TRACE("Asked for negative x\n");
5658             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
5659         case WINED3DCUBEMAP_FACE_POSITIVE_Y:
5660             TRACE("Asked for positive y\n");
5661             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
5662         case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
5663             TRACE("Asked for negative y\n");
5664             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
5665         case WINED3DCUBEMAP_FACE_POSITIVE_Z:
5666             TRACE("Asked for positive z\n");
5667             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
5668         case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
5669             TRACE("Asked for negative z\n");
5670             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
5671         default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
5672     }
5673
5674     if (!surf)
5675     {
5676         IDirectDrawSurface7 *attached;
5677         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)ddraw->tex_root, &searchcaps, &attached);
5678         surf = (IDirectDrawSurfaceImpl *)attached;
5679         IDirectDrawSurface7_Release(attached);
5680     }
5681     if (!surf) ERR("root search surface not found\n");
5682
5683     /* Find the wanted mipmap. There are enough mipmaps in the chain */
5684     while (i < level)
5685     {
5686         IDirectDrawSurface7 *attached;
5687         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)surf, &searchcaps, &attached);
5688         if(!attached) ERR("Surface not found\n");
5689         surf = (IDirectDrawSurfaceImpl *)attached;
5690         IDirectDrawSurface7_Release(attached);
5691         ++i;
5692     }
5693
5694     /* Return the surface */
5695     *surface = surf->wined3d_surface;
5696     wined3d_surface_incref(*surface);
5697
5698     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, surf);
5699
5700     return D3D_OK;
5701 }
5702
5703 static HRESULT WINAPI findRenderTarget(IDirectDrawSurface7 *surface, DDSURFACEDESC2 *surface_desc, void *ctx)
5704 {
5705     IDirectDrawSurfaceImpl *s = (IDirectDrawSurfaceImpl *)surface;
5706     IDirectDrawSurfaceImpl **target = ctx;
5707
5708     if (!s->isRenderTarget)
5709     {
5710         *target = s;
5711         IDirectDrawSurface7_Release(surface);
5712         return DDENUMRET_CANCEL;
5713     }
5714
5715     /* Recurse into the surface tree */
5716     IDirectDrawSurface7_EnumAttachedSurfaces(surface, ctx, findRenderTarget);
5717
5718     IDirectDrawSurface7_Release(surface);
5719     if (*target) return DDENUMRET_CANCEL;
5720
5721     return DDENUMRET_OK;
5722 }
5723
5724 static HRESULT CDECL device_parent_create_rendertarget(struct wined3d_device_parent *device_parent,
5725         void *container_parent, UINT width, UINT height, enum wined3d_format_id format,
5726         WINED3DMULTISAMPLE_TYPE multisample_type, DWORD multisample_quality, BOOL lockable,
5727         struct wined3d_surface **surface)
5728 {
5729     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5730     IDirectDrawSurfaceImpl *d3d_surface = ddraw->d3d_target;
5731     IDirectDrawSurfaceImpl *target = NULL;
5732
5733     TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5734             "\tmultisample_quality %u, lockable %u, surface %p.\n",
5735             device_parent, container_parent, width, height, format, multisample_type,
5736             multisample_quality, lockable, surface);
5737
5738     if (d3d_surface->isRenderTarget)
5739     {
5740         IDirectDrawSurface7_EnumAttachedSurfaces((IDirectDrawSurface7 *)d3d_surface, &target, findRenderTarget);
5741     }
5742     else
5743     {
5744         target = d3d_surface;
5745     }
5746
5747     if (!target)
5748     {
5749         target = ddraw->d3d_target;
5750         ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", ddraw);
5751     }
5752
5753     /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */
5754
5755     *surface = target->wined3d_surface;
5756     wined3d_surface_incref(*surface);
5757     target->isRenderTarget = TRUE;
5758
5759     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, d3d_surface);
5760
5761     return D3D_OK;
5762 }
5763
5764 static HRESULT CDECL device_parent_create_depth_stencil(struct wined3d_device_parent *device_parent,
5765         UINT width, UINT height, enum wined3d_format_id format, WINED3DMULTISAMPLE_TYPE multisample_type,
5766         DWORD multisample_quality, BOOL discard, struct wined3d_surface **surface)
5767 {
5768     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5769     IDirectDrawSurfaceImpl *ddraw_surface;
5770     DDSURFACEDESC2 ddsd;
5771     HRESULT hr;
5772
5773     TRACE("device_parent %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5774             "\tmultisample_quality %u, discard %u, surface %p.\n",
5775             device_parent, width, height, format, multisample_type, multisample_quality, discard, surface);
5776
5777     *surface = NULL;
5778
5779     /* Create a DirectDraw surface */
5780     memset(&ddsd, 0, sizeof(ddsd));
5781     ddsd.dwSize = sizeof(ddsd);
5782     ddsd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
5783     ddsd.dwFlags = DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
5784     ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
5785     ddsd.dwHeight = height;
5786     ddsd.dwWidth = width;
5787     if (format)
5788     {
5789         PixelFormat_WineD3DtoDD(&ddsd.u4.ddpfPixelFormat, format);
5790     }
5791     else
5792     {
5793         ddsd.dwFlags ^= DDSD_PIXELFORMAT;
5794     }
5795
5796     ddraw->depthstencil = TRUE;
5797     hr = IDirectDraw7_CreateSurface(&ddraw->IDirectDraw7_iface, &ddsd,
5798             (IDirectDrawSurface7 **)&ddraw_surface, NULL);
5799     ddraw->depthstencil = FALSE;
5800     if (FAILED(hr))
5801     {
5802         WARN("Failed to create depth/stencil surface, hr %#x.\n", hr);
5803         return hr;
5804     }
5805
5806     *surface = ddraw_surface->wined3d_surface;
5807     wined3d_surface_incref(*surface);
5808     IDirectDrawSurface7_Release((IDirectDrawSurface7 *)ddraw_surface);
5809
5810     return D3D_OK;
5811 }
5812
5813 static HRESULT CDECL device_parent_create_volume(struct wined3d_device_parent *device_parent,
5814         void *container_parent, UINT width, UINT height, UINT depth, enum wined3d_format_id format,
5815         WINED3DPOOL pool, DWORD usage, struct wined3d_volume **volume)
5816 {
5817     TRACE("device_parent %p, container_parent %p, width %u, height %u, depth %u, "
5818             "format %#x, pool %#x, usage %#x, volume %p.\n",
5819             device_parent, container_parent, width, height, depth,
5820             format, pool, usage, volume);
5821
5822     ERR("Not implemented!\n");
5823
5824     return E_NOTIMPL;
5825 }
5826
5827 static HRESULT CDECL device_parent_create_swapchain(struct wined3d_device_parent *device_parent,
5828         WINED3DPRESENT_PARAMETERS *present_parameters, struct wined3d_swapchain **swapchain)
5829 {
5830     struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5831     IDirectDrawSurfaceImpl *iterator;
5832     HRESULT hr;
5833
5834     TRACE("device_parent %p, present_parameters %p, swapchain %p.\n", device_parent, present_parameters, swapchain);
5835
5836     hr = wined3d_swapchain_create(ddraw->wined3d_device, present_parameters,
5837             ddraw->ImplType, NULL, &ddraw_null_wined3d_parent_ops, swapchain);
5838     if (FAILED(hr))
5839     {
5840         WARN("Failed to create swapchain, hr %#x.\n", hr);
5841         *swapchain = NULL;
5842         return hr;
5843     }
5844
5845     ddraw->d3d_target->wined3d_swapchain = *swapchain;
5846     iterator = ddraw->d3d_target->complex_array[0];
5847     while (iterator)
5848     {
5849         iterator->wined3d_swapchain = *swapchain;
5850         iterator = iterator->complex_array[0];
5851     }
5852
5853     return hr;
5854 }
5855
5856 static const struct wined3d_device_parent_ops ddraw_wined3d_device_parent_ops =
5857 {
5858     device_parent_wined3d_device_created,
5859     device_parent_create_surface,
5860     device_parent_create_rendertarget,
5861     device_parent_create_depth_stencil,
5862     device_parent_create_volume,
5863     device_parent_create_swapchain,
5864 };
5865
5866 HRESULT ddraw_init(IDirectDrawImpl *ddraw, WINED3DDEVTYPE device_type)
5867 {
5868     HRESULT hr;
5869     HDC hDC;
5870
5871     ddraw->IDirectDraw7_iface.lpVtbl = &ddraw7_vtbl;
5872     ddraw->IDirectDraw_iface.lpVtbl = &ddraw1_vtbl;
5873     ddraw->IDirectDraw2_iface.lpVtbl = &ddraw2_vtbl;
5874     ddraw->IDirectDraw3_iface.lpVtbl = &ddraw3_vtbl;
5875     ddraw->IDirectDraw4_iface.lpVtbl = &ddraw4_vtbl;
5876     ddraw->IDirect3D_iface.lpVtbl = &d3d1_vtbl;
5877     ddraw->IDirect3D2_iface.lpVtbl = &d3d2_vtbl;
5878     ddraw->IDirect3D3_iface.lpVtbl = &d3d3_vtbl;
5879     ddraw->IDirect3D7_iface.lpVtbl = &d3d7_vtbl;
5880     ddraw->device_parent.ops = &ddraw_wined3d_device_parent_ops;
5881     ddraw->numIfaces = 1;
5882     ddraw->ref7 = 1;
5883
5884     /* See comments in IDirectDrawImpl_CreateNewSurface for a description of
5885      * this field. */
5886     ddraw->ImplType = DefaultSurfaceType;
5887
5888     /* Get the current screen settings. */
5889     hDC = GetDC(0);
5890     ddraw->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
5891     ReleaseDC(0, hDC);
5892     ddraw->orig_width = GetSystemMetrics(SM_CXSCREEN);
5893     ddraw->orig_height = GetSystemMetrics(SM_CYSCREEN);
5894
5895     ddraw->wineD3D = wined3d_create(7, &ddraw->IDirectDraw7_iface);
5896     if (!ddraw->wineD3D)
5897     {
5898         WARN("Failed to create a wined3d object.\n");
5899         return E_OUTOFMEMORY;
5900     }
5901
5902     hr = wined3d_device_create(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, device_type,
5903             NULL, 0, &ddraw->device_parent, &ddraw->wined3d_device);
5904     if (FAILED(hr))
5905     {
5906         WARN("Failed to create a wined3d device, hr %#x.\n", hr);
5907         wined3d_decref(ddraw->wineD3D);
5908         return hr;
5909     }
5910
5911     /* Get the amount of video memory */
5912     ddraw->total_vidmem = wined3d_device_get_available_texture_mem(ddraw->wined3d_device);
5913
5914     list_init(&ddraw->surface_list);
5915
5916     return DD_OK;
5917 }