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