ntdll: Fix compilation on systems that don't support nameless unions.
[wine] / dlls / ddraw / main.c
1 /*        DirectDraw Base Functions
2  *
3  * Copyright 1997-1999 Marcus Meissner
4  * Copyright 1998 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2006 Stefan Dösinger
7  *
8  * This file contains the (internal) driver registration functions,
9  * driver enumeration APIs and DirectDraw creation functions.
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28 #include "wine/debug.h"
29
30 #include <assert.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <stdlib.h>
34
35 #define COBJMACROS
36
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "wingdi.h"
41 #include "wine/exception.h"
42 #include "winreg.h"
43
44 #include "ddraw.h"
45 #include "d3d.h"
46
47 #include "ddraw_private.h"
48
49 typedef IWineD3D* (WINAPI *fnWineDirect3DCreate)(UINT, UINT, IUnknown *);
50
51 static HMODULE hWineD3D = (HMODULE) -1;
52 static fnWineDirect3DCreate pWineDirect3DCreate;
53
54 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
55
56 /* The configured default surface */
57 WINED3DSURFTYPE DefaultSurfaceType = SURFACE_UNKNOWN;
58
59 /* DDraw list and critical section */
60 static struct list global_ddraw_list = LIST_INIT(global_ddraw_list);
61
62 static CRITICAL_SECTION ddraw_list_cs;
63 static CRITICAL_SECTION_DEBUG ddraw_list_cs_debug =
64 {
65     0, 0, &ddraw_list_cs,
66     { &ddraw_list_cs_debug.ProcessLocksList, 
67     &ddraw_list_cs_debug.ProcessLocksList },
68     0, 0, { (DWORD_PTR)(__FILE__ ": ddraw_list_cs") }
69 };
70 static CRITICAL_SECTION ddraw_list_cs = { &ddraw_list_cs_debug, -1, 0, 0, 0, 0 };
71
72 /***********************************************************************
73  *
74  * Helper function for DirectDrawCreate and friends
75  * Creates a new DDraw interface with the given REFIID
76  *
77  * Interfaces that can be created:
78  *  IDirectDraw, IDirectDraw2, IDirectDraw4, IDirectDraw7
79  *  IDirect3D, IDirect3D2, IDirect3D3, IDirect3D7. (Does Windows return
80  *  IDirect3D interfaces?)
81  *
82  * Arguments:
83  *  guid: ID of the requested driver, NULL for the default driver.
84  *        The GUID can be queried with DirectDrawEnumerate(Ex)A/W
85  *  DD: Used to return the pointer to the created object
86  *  UnkOuter: For aggregation, which is unsupported. Must be NULL
87  *  iid: requested version ID.
88  *
89  * Returns:
90  *  DD_OK if the Interface was created successfully
91  *  CLASS_E_NOAGGREGATION if UnkOuter is not NULL
92  *  E_OUTOFMEMORY if some allocation failed
93  *
94  ***********************************************************************/
95 static HRESULT
96 DDRAW_Create(const GUID *guid,
97              void **DD,
98              IUnknown *UnkOuter,
99              REFIID iid)
100 {
101     IDirectDrawImpl *This = NULL;
102     HRESULT hr;
103     IWineD3D *wineD3D = NULL;
104     IWineD3DDevice *wineD3DDevice = NULL;
105     HDC hDC;
106     WINED3DDEVTYPE devicetype;
107
108     TRACE("(%s,%p,%p)\n", debugstr_guid(guid), DD, UnkOuter);
109
110     *DD = NULL;
111
112     /* We don't care about this guids. Well, there's no special guid anyway
113      * OK, we could
114      */
115     if (guid == (GUID *) DDCREATE_EMULATIONONLY)
116     {
117         /* Use the reference device id. This doesn't actually change anything,
118          * WineD3D always uses OpenGL for D3D rendering. One could make it request
119          * indirect rendering
120          */
121         devicetype = WINED3DDEVTYPE_REF;
122     }
123     else if(guid == (GUID *) DDCREATE_HARDWAREONLY)
124     {
125         devicetype = WINED3DDEVTYPE_HAL;
126     }
127     else
128     {
129         devicetype = 0;
130     }
131
132     /* DDraw doesn't support aggregation, according to msdn */
133     if (UnkOuter != NULL)
134         return CLASS_E_NOAGGREGATION;
135
136     /* DirectDraw creation comes here */
137     This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawImpl));
138     if(!This)
139     {
140         ERR("Out of memory when creating DirectDraw\n");
141         return E_OUTOFMEMORY;
142     }
143
144     /* The interfaces:
145      * IDirectDraw and IDirect3D are the same object,
146      * QueryInterface is used to get other interfaces.
147      */
148     ICOM_INIT_INTERFACE(This, IDirectDraw,  IDirectDraw1_Vtbl);
149     ICOM_INIT_INTERFACE(This, IDirectDraw2, IDirectDraw2_Vtbl);
150     ICOM_INIT_INTERFACE(This, IDirectDraw3, IDirectDraw3_Vtbl);
151     ICOM_INIT_INTERFACE(This, IDirectDraw4, IDirectDraw4_Vtbl);
152     ICOM_INIT_INTERFACE(This, IDirectDraw7, IDirectDraw7_Vtbl);
153     ICOM_INIT_INTERFACE(This, IDirect3D,  IDirect3D1_Vtbl);
154     ICOM_INIT_INTERFACE(This, IDirect3D2, IDirect3D2_Vtbl);
155     ICOM_INIT_INTERFACE(This, IDirect3D3, IDirect3D3_Vtbl);
156     ICOM_INIT_INTERFACE(This, IDirect3D7, IDirect3D7_Vtbl);
157
158     /* See comments in IDirectDrawImpl_CreateNewSurface for a description
159      * of this member.
160      * Read from a registry key, should add a winecfg option later
161      */
162     This->ImplType = DefaultSurfaceType;
163
164     /* Get the current screen settings */
165     hDC = GetDC(0);
166     This->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
167     ReleaseDC(0, hDC);
168     This->orig_width = GetSystemMetrics(SM_CXSCREEN);
169     This->orig_height = GetSystemMetrics(SM_CYSCREEN);
170
171     if (hWineD3D == (HMODULE) -1)
172     {
173         hWineD3D = LoadLibraryA("wined3d");
174         if (hWineD3D)
175         {
176             pWineDirect3DCreate = (fnWineDirect3DCreate) GetProcAddress(hWineD3D, "WineDirect3DCreate");
177             pWineDirect3DCreateClipper = (fnWineDirect3DCreateClipper) GetProcAddress(hWineD3D, "WineDirect3DCreateClipper");
178         }
179     }
180
181     if (!hWineD3D)
182     {
183         ERR("Couldn't load WineD3D - OpenGL libs not present?\n");
184         hr = DDERR_NODIRECTDRAWSUPPORT;
185         goto err_out;
186     }
187
188     /* Initialize WineD3D
189      *
190      * All Rendering (2D and 3D) is relayed to WineD3D,
191      * but DirectDraw specific management, like DDSURFACEDESC and DDPIXELFORMAT
192      * structure handling is handled in this lib.
193      */
194     wineD3D = pWineDirect3DCreate(0 /* SDKVersion */, 7 /* DXVersion */, (IUnknown *) This /* Parent */);
195     if(!wineD3D)
196     {
197         ERR("Failed to initialise WineD3D\n");
198         hr = E_OUTOFMEMORY;
199         goto err_out;
200     }
201     This->wineD3D = wineD3D;
202     TRACE("WineD3D created at %p\n", wineD3D);
203
204     /* Initialized member...
205      *
206      * It is set to false at creation time, and set to true in
207      * IDirectDraw7::Initialize. Its sole purpose is to return DD_OK on
208      * initialize only once
209      */
210     This->initialized = FALSE;
211
212     /* Initialize WineD3DDevice
213      *
214      * It is used for screen setup, surface and palette creation
215      * When a Direct3DDevice7 is created, the D3D capabilities of WineD3D are
216      * initialized
217      */
218     hr = IWineD3D_CreateDevice(wineD3D,
219                                0 /*D3D_ADAPTER_DEFAULT*/,
220                                devicetype,
221                                NULL, /* FocusWindow, don't know yet */
222                                0, /* BehaviorFlags */
223                                &wineD3DDevice,
224                                (IUnknown *) ICOM_INTERFACE(This, IDirectDraw7));
225     if(FAILED(hr))
226     {
227         ERR("Failed to create a wineD3DDevice, result = %x\n", hr);
228         goto err_out;
229     }
230     This->wineD3DDevice = wineD3DDevice;
231     TRACE("wineD3DDevice created at %p\n", This->wineD3DDevice);
232
233     /* Register the window class
234      *
235      * It is used to create a hidden window for D3D
236      * rendering, if the application didn't pass one.
237      * It can also be used for Creating a device window
238      * from SetCooperativeLevel
239      *
240      * The name: DDRAW_<address>. The classname is
241      * 32 bit long, so a 64 bit address will fit nicely
242      * (Will this be compiled for 64 bit anyway?)
243      *
244      */
245     sprintf(This->classname, "DDRAW_%p", This);
246
247     memset(&This->wnd_class, 0, sizeof(This->wnd_class));
248     This->wnd_class.style = CS_HREDRAW | CS_VREDRAW;
249     This->wnd_class.lpfnWndProc = DefWindowProcA;
250     This->wnd_class.cbClsExtra = 0;
251     This->wnd_class.cbWndExtra = 0;
252     This->wnd_class.hInstance = GetModuleHandleA(0);
253     This->wnd_class.hIcon = 0;
254     This->wnd_class.hCursor = 0;
255     This->wnd_class.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
256     This->wnd_class.lpszMenuName = NULL;
257     This->wnd_class.lpszClassName = This->classname;
258     if(!RegisterClassA(&This->wnd_class))
259     {
260         ERR("RegisterClassA failed!\n");
261         goto err_out;
262     }
263
264     /* Get the amount of video memory */
265     This->total_vidmem = IWineD3DDevice_GetAvailableTextureMem(This->wineD3DDevice);
266
267     /* Initialize the caps */
268     This->caps.dwSize = sizeof(This->caps);
269 /* do not report DDCAPS_OVERLAY and friends since we don't support overlays */
270 #define BLIT_CAPS (DDCAPS_BLT | DDCAPS_BLTCOLORFILL | DDCAPS_BLTDEPTHFILL \
271           | DDCAPS_BLTSTRETCH | DDCAPS_CANBLTSYSMEM | DDCAPS_CANCLIP      \
272           | DDCAPS_CANCLIPSTRETCHED | DDCAPS_COLORKEY                     \
273           | DDCAPS_COLORKEYHWASSIST | DDCAPS_ALIGNBOUNDARYSRC )
274 #define CKEY_CAPS (DDCKEYCAPS_DESTBLT | DDCKEYCAPS_SRCBLT)
275 #define FX_CAPS (DDFXCAPS_BLTALPHA | DDFXCAPS_BLTMIRRORLEFTRIGHT        \
276                 | DDFXCAPS_BLTMIRRORUPDOWN | DDFXCAPS_BLTROTATION90     \
277                 | DDFXCAPS_BLTSHRINKX | DDFXCAPS_BLTSHRINKXN            \
278                 | DDFXCAPS_BLTSHRINKY | DDFXCAPS_BLTSHRINKXN            \
279                 | DDFXCAPS_BLTSTRETCHX | DDFXCAPS_BLTSTRETCHXN          \
280                 | DDFXCAPS_BLTSTRETCHY | DDFXCAPS_BLTSTRETCHYN)
281     This->caps.dwCaps |= DDCAPS_GDI | DDCAPS_PALETTE | BLIT_CAPS;
282
283     This->caps.dwCaps2 |= DDCAPS2_CERTIFIED | DDCAPS2_NOPAGELOCKREQUIRED |
284                           DDCAPS2_PRIMARYGAMMA | DDCAPS2_WIDESURFACES |
285                           DDCAPS2_CANRENDERWINDOWED;
286     This->caps.dwCKeyCaps |= CKEY_CAPS;
287     This->caps.dwFXCaps |= FX_CAPS;
288     This->caps.dwPalCaps |= DDPCAPS_8BIT | DDPCAPS_PRIMARYSURFACE;
289     This->caps.dwVidMemTotal = This->total_vidmem;
290     This->caps.dwVidMemFree = This->total_vidmem;
291     This->caps.dwSVBCaps |= BLIT_CAPS;
292     This->caps.dwSVBCKeyCaps |= CKEY_CAPS;
293     This->caps.dwSVBFXCaps |= FX_CAPS;
294     This->caps.dwVSBCaps |= BLIT_CAPS;
295     This->caps.dwVSBCKeyCaps |= CKEY_CAPS;
296     This->caps.dwVSBFXCaps |= FX_CAPS;
297     This->caps.dwSSBCaps |= BLIT_CAPS;
298     This->caps.dwSSBCKeyCaps |= CKEY_CAPS;
299     This->caps.dwSSBFXCaps |= FX_CAPS;
300     This->caps.ddsCaps.dwCaps |= DDSCAPS_ALPHA | DDSCAPS_BACKBUFFER |
301                                  DDSCAPS_FLIP | DDSCAPS_FRONTBUFFER |
302                                  DDSCAPS_OFFSCREENPLAIN | DDSCAPS_PALETTE |
303                                  DDSCAPS_PRIMARYSURFACE | DDSCAPS_SYSTEMMEMORY |
304                                  DDSCAPS_VIDEOMEMORY | DDSCAPS_VISIBLE;
305     /* Hacks for D3D code */
306     /* TODO: Check if WineD3D has 3D enabled
307        Need opengl surfaces or auto for 3D
308      */
309     if(This->ImplType == 0 || This->ImplType == SURFACE_OPENGL)
310     {
311         This->caps.dwCaps |= DDCAPS_3D;
312         This->caps.ddsCaps.dwCaps |= DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER;
313     }
314     This->caps.ddsOldCaps.dwCaps = This->caps.ddsCaps.dwCaps;
315
316 #undef BLIT_CAPS
317 #undef CKEY_CAPS
318 #undef FX_CAPS
319
320     list_init(&This->surface_list);
321
322     EnterCriticalSection(&ddraw_list_cs);
323     list_add_head(&global_ddraw_list, &This->ddraw_list_entry);
324     LeaveCriticalSection(&ddraw_list_cs);
325
326     This->decls = HeapAlloc(GetProcessHeap(), 0, 0);
327     if(!This->decls)
328     {
329         ERR("Error allocating an empty array for the converted vertex decls\n");
330         goto err_out;
331     }
332
333     /* Call QueryInterface to get the pointer to the requested interface. This also initializes
334      * The required refcount
335      */
336     hr = IDirectDraw7_QueryInterface( ICOM_INTERFACE(This, IDirectDraw7), iid, DD);
337     if(SUCCEEDED(hr)) return DD_OK;
338
339 err_out:
340     /* Let's hope we never need this ;) */
341     if(wineD3DDevice) IWineD3DDevice_Release(wineD3DDevice);
342     if(wineD3D) IWineD3D_Release(wineD3D);
343     if(This) HeapFree(GetProcessHeap(), 0, This->decls);
344     HeapFree(GetProcessHeap(), 0, This);
345     return hr;
346 }
347
348 /***********************************************************************
349  * DirectDrawCreate (DDRAW.@)
350  *
351  * Creates legacy DirectDraw Interfaces. Can't create IDirectDraw7
352  * interfaces in theory
353  *
354  * Arguments, return values: See DDRAW_Create
355  *
356  ***********************************************************************/
357 HRESULT WINAPI
358 DirectDrawCreate(GUID *GUID,
359                  IDirectDraw **DD,
360                  IUnknown *UnkOuter)
361 {
362     TRACE("(%s,%p,%p)\n", debugstr_guid(GUID), DD, UnkOuter);
363
364     return DDRAW_Create(GUID, (void **) DD, UnkOuter, &IID_IDirectDraw);
365 }
366
367 /***********************************************************************
368  * DirectDrawCreateEx (DDRAW.@)
369  *
370  * Only creates new IDirectDraw7 interfaces, supposed to fail if legacy
371  * interfaces are requested.
372  *
373  * Arguments, return values: See DDRAW_Create
374  *
375  ***********************************************************************/
376 HRESULT WINAPI
377 DirectDrawCreateEx(GUID *GUID,
378                    void **DD,
379                    REFIID iid,
380                    IUnknown *UnkOuter)
381 {
382     TRACE("(%s,%p,%s,%p)\n", debugstr_guid(GUID), DD, debugstr_guid(iid), UnkOuter);
383
384     if (!IsEqualGUID(iid, &IID_IDirectDraw7))
385         return DDERR_INVALIDPARAMS;
386
387     return DDRAW_Create(GUID, DD, UnkOuter, iid);
388 }
389
390 /***********************************************************************
391  * DirectDrawEnumerateA (DDRAW.@)
392  *
393  * Enumerates legacy ddraw drivers, ascii version. We only have one
394  * driver, which relays to WineD3D. If we were sufficiently cool,
395  * we could offer various interfaces, which use a different default surface
396  * implementation, but I think it's better to offer this choice in
397  * winecfg, because some apps use the default driver, so we would need
398  * a winecfg option anyway, and there shouldn't be 2 ways to set one setting
399  *
400  * Arguments:
401  *  Callback: Callback function from the app
402  *  Context: Argument to the call back.
403  *
404  * Returns:
405  *  DD_OK on success
406  *  E_INVALIDARG if the Callback caused a page fault
407  *
408  *
409  ***********************************************************************/
410 HRESULT WINAPI
411 DirectDrawEnumerateA(LPDDENUMCALLBACKA Callback,
412                      void *Context)
413 {
414     BOOL stop = FALSE;
415
416     TRACE(" Enumerating default DirectDraw HAL interface\n");
417     /* We only have one driver */
418     __TRY
419     {
420         static CHAR driver_desc[] = "DirectDraw HAL",
421         driver_name[] = "display";
422
423         stop = !Callback(NULL, driver_desc, driver_name, Context);
424     }
425     __EXCEPT_PAGE_FAULT
426     {
427         return E_INVALIDARG;
428     }
429     __ENDTRY
430
431     TRACE(" End of enumeration\n");
432     return DD_OK;
433 }
434
435 /***********************************************************************
436  * DirectDrawEnumerateExA (DDRAW.@)
437  *
438  * Enumerates DirectDraw7 drivers, ascii version. See
439  * the comments above DirectDrawEnumerateA for more details.
440  *
441  * The Flag member is not supported right now.
442  *
443  ***********************************************************************/
444 HRESULT WINAPI
445 DirectDrawEnumerateExA(LPDDENUMCALLBACKEXA Callback,
446                        void *Context,
447                        DWORD Flags)
448 {
449     BOOL stop = FALSE;
450     TRACE("Enumerating default DirectDraw HAL interface\n");
451
452     /* We only have one driver by now */
453     __TRY
454     {
455         static CHAR driver_desc[] = "DirectDraw HAL",
456         driver_name[] = "display";
457
458         /* QuickTime expects the description "DirectDraw HAL" */
459         stop = !Callback(NULL, driver_desc, driver_name, Context, 0);
460     }
461     __EXCEPT_PAGE_FAULT
462     {
463         return E_INVALIDARG;
464     }
465     __ENDTRY;
466
467     TRACE("End of enumeration\n");
468     return DD_OK;
469 }
470
471 /***********************************************************************
472  * DirectDrawEnumerateW (DDRAW.@)
473  *
474  * Enumerates legacy drivers, unicode version. See
475  * the comments above DirectDrawEnumerateA for more details.
476  *
477  * The Flag member is not supported right now.
478  *
479  ***********************************************************************/
480
481 /***********************************************************************
482  * DirectDrawEnumerateExW (DDRAW.@)
483  *
484  * Enumerates DirectDraw7 drivers, unicode version. See
485  * the comments above DirectDrawEnumerateA for more details.
486  *
487  * The Flag member is not supported right now.
488  *
489  ***********************************************************************/
490
491 /***********************************************************************
492  * Classfactory implementation.
493  ***********************************************************************/
494
495 /***********************************************************************
496  * CF_CreateDirectDraw
497  *
498  * DDraw creation function for the class factory
499  *
500  * Params:
501  *  UnkOuter: Set to NULL
502  *  iid: ID of the wanted interface
503  *  obj: Address to pass the interface pointer back
504  *
505  * Returns
506  *  DD_OK / DDERR*, see DDRAW_Create
507  *
508  ***********************************************************************/
509 static HRESULT
510 CF_CreateDirectDraw(IUnknown* UnkOuter, REFIID iid,
511                     void **obj)
512 {
513     HRESULT hr;
514
515     TRACE("(%p,%s,%p)\n", UnkOuter, debugstr_guid(iid), obj);
516
517     hr = DDRAW_Create(NULL, obj, UnkOuter, iid);
518     return hr;
519 }
520
521 /***********************************************************************
522  * CF_CreateDirectDraw
523  *
524  * Clipper creation function for the class factory
525  *
526  * Params:
527  *  UnkOuter: Set to NULL
528  *  iid: ID of the wanted interface
529  *  obj: Address to pass the interface pointer back
530  *
531  * Returns
532  *  DD_OK / DDERR*, see DDRAW_Create
533  *
534  ***********************************************************************/
535 static HRESULT
536 CF_CreateDirectDrawClipper(IUnknown* UnkOuter, REFIID riid,
537                               void **obj)
538 {
539     HRESULT hr;
540     IDirectDrawClipper *Clip;
541
542     hr = DirectDrawCreateClipper(0, &Clip, UnkOuter);
543     if (hr != DD_OK) return hr;
544
545     hr = IDirectDrawClipper_QueryInterface(Clip, riid, obj);
546     IDirectDrawClipper_Release(Clip);
547     return hr;
548 }
549
550 static const struct object_creation_info object_creation[] =
551 {
552     { &CLSID_DirectDraw,        CF_CreateDirectDraw },
553     { &CLSID_DirectDraw7,       CF_CreateDirectDraw },
554     { &CLSID_DirectDrawClipper, CF_CreateDirectDrawClipper }
555 };
556
557 /*******************************************************************************
558  * IDirectDrawClassFactory::QueryInterface
559  *
560  * QueryInterface for the class factory
561  *
562  * PARAMS
563  *    riid   Reference to identifier of queried interface
564  *    ppv    Address to return the interface pointer at
565  *
566  * RETURNS
567  *    Success: S_OK
568  *    Failure: E_NOINTERFACE
569  *
570  *******************************************************************************/
571 static HRESULT WINAPI
572 IDirectDrawClassFactoryImpl_QueryInterface(IClassFactory *iface,
573                     REFIID riid,
574                     void **obj)
575 {
576     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
577
578     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), obj);
579
580     if (IsEqualGUID(riid, &IID_IUnknown)
581         || IsEqualGUID(riid, &IID_IClassFactory))
582     {
583         IClassFactory_AddRef(iface);
584         *obj = This;
585         return S_OK;
586     }
587
588     WARN("(%p)->(%s,%p),not found\n",This,debugstr_guid(riid),obj);
589     return E_NOINTERFACE;
590 }
591
592 /*******************************************************************************
593  * IDirectDrawClassFactory::AddRef
594  *
595  * AddRef for the class factory
596  *
597  * RETURNS
598  *  The new refcount
599  *
600  *******************************************************************************/
601 static ULONG WINAPI
602 IDirectDrawClassFactoryImpl_AddRef(IClassFactory *iface)
603 {
604     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
605     ULONG ref = InterlockedIncrement(&This->ref);
606
607     TRACE("(%p)->() incrementing from %d.\n", This, ref - 1);
608
609     return ref;
610 }
611
612 /*******************************************************************************
613  * IDirectDrawClassFactory::Release
614  *
615  * Release for the class factory. If the refcount falls to 0, the object
616  * is destroyed
617  *
618  * RETURNS
619  *  The new refcount
620  *
621  *******************************************************************************/
622 static ULONG WINAPI
623 IDirectDrawClassFactoryImpl_Release(IClassFactory *iface)
624 {
625     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
626     ULONG ref = InterlockedDecrement(&This->ref);
627     TRACE("(%p)->() decrementing from %d.\n", This, ref+1);
628
629     if (ref == 0)
630         HeapFree(GetProcessHeap(), 0, This);
631
632     return ref;
633 }
634
635
636 /*******************************************************************************
637  * IDirectDrawClassFactory::CreateInstance
638  *
639  * What is this? Seems to create DirectDraw objects...
640  *
641  * Params
642  *  The ususal things???
643  *
644  * RETURNS
645  *  ???
646  *
647  *******************************************************************************/
648 static HRESULT WINAPI
649 IDirectDrawClassFactoryImpl_CreateInstance(IClassFactory *iface,
650                                            IUnknown *UnkOuter,
651                                            REFIID riid,
652                                            void **obj)
653 {
654     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
655
656     TRACE("(%p)->(%p,%s,%p)\n",This,UnkOuter,debugstr_guid(riid),obj);
657
658     return This->pfnCreateInstance(UnkOuter, riid, obj);
659 }
660
661 /*******************************************************************************
662  * IDirectDrawClassFactory::LockServer
663  *
664  * What is this?
665  *
666  * Params
667  *  ???
668  *
669  * RETURNS
670  *  S_OK, because it's a stub
671  *
672  *******************************************************************************/
673 static HRESULT WINAPI
674 IDirectDrawClassFactoryImpl_LockServer(IClassFactory *iface,BOOL dolock)
675 {
676     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
677     FIXME("(%p)->(%d),stub!\n",This,dolock);
678     return S_OK;
679 }
680
681 /*******************************************************************************
682  * The class factory VTable
683  *******************************************************************************/
684 static const IClassFactoryVtbl IClassFactory_Vtbl =
685 {
686     IDirectDrawClassFactoryImpl_QueryInterface,
687     IDirectDrawClassFactoryImpl_AddRef,
688     IDirectDrawClassFactoryImpl_Release,
689     IDirectDrawClassFactoryImpl_CreateInstance,
690     IDirectDrawClassFactoryImpl_LockServer
691 };
692
693 /*******************************************************************************
694  * DllGetClassObject [DDRAW.@]
695  * Retrieves class object from a DLL object
696  *
697  * NOTES
698  *    Docs say returns STDAPI
699  *
700  * PARAMS
701  *    rclsid [I] CLSID for the class object
702  *    riid   [I] Reference to identifier of interface for class object
703  *    ppv    [O] Address of variable to receive interface pointer for riid
704  *
705  * RETURNS
706  *    Success: S_OK
707  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
708  *             E_UNEXPECTED
709  */
710 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
711 {
712     unsigned int i;
713     IClassFactoryImpl *factory;
714
715     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
716
717     if ( !IsEqualGUID( &IID_IClassFactory, riid )
718          && ! IsEqualGUID( &IID_IUnknown, riid) )
719         return E_NOINTERFACE;
720
721     for (i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++)
722     {
723         if (IsEqualGUID(object_creation[i].clsid, rclsid))
724             break;
725     }
726
727     if (i == sizeof(object_creation)/sizeof(object_creation[0]))
728     {
729         FIXME("%s: no class found.\n", debugstr_guid(rclsid));
730         return CLASS_E_CLASSNOTAVAILABLE;
731     }
732
733     factory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*factory));
734     if (factory == NULL) return E_OUTOFMEMORY;
735
736     ICOM_INIT_INTERFACE(factory, IClassFactory, IClassFactory_Vtbl);
737     factory->ref = 1;
738
739     factory->pfnCreateInstance = object_creation[i].pfnCreateInstance;
740
741     *ppv = ICOM_INTERFACE(factory, IClassFactory);
742     return S_OK;
743 }
744
745
746 /*******************************************************************************
747  * DllCanUnloadNow [DDRAW.@]  Determines whether the DLL is in use.
748  *
749  * RETURNS
750  *    Success: S_OK
751  *    Failure: S_FALSE
752  */
753 HRESULT WINAPI DllCanUnloadNow(void)
754 {
755     FIXME("(void): stub\n");
756     return S_FALSE;
757 }
758
759 /*******************************************************************************
760  * DestroyCallback
761  *
762  * Callback function for the EnumSurfaces call in DllMain.
763  * Dumps some surface info and releases the surface
764  *
765  * Params:
766  *  surf: The enumerated surface
767  *  desc: it's description
768  *  context: Pointer to the ddraw impl
769  *
770  * Returns:
771  *  DDENUMRET_OK;
772  *******************************************************************************/
773 static HRESULT WINAPI
774 DestroyCallback(IDirectDrawSurface7 *surf,
775                 DDSURFACEDESC2 *desc,
776                 void *context)
777 {
778     IDirectDrawSurfaceImpl *Impl = ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, surf);
779     IDirectDrawImpl *ddraw = (IDirectDrawImpl *) context;
780     ULONG ref;
781
782     ref = IDirectDrawSurface7_Release(surf);  /* For the EnumSurfaces */
783     WARN("Surface %p has an reference count of %d\n", Impl, ref);
784
785     /* Skip surfaces which are attached somewhere or which are
786      * part of a complex compound. They will get released when destroying
787      * the root
788      */
789     if( (!Impl->is_complex_root) || (Impl->first_attached != Impl) )
790         return DDENUMRET_OK;
791     /* Skip our depth stencil surface, it will be released with the render target */
792     if( Impl == ddraw->DepthStencilBuffer)
793         return DDENUMRET_OK;
794
795     /* Destroy the surface */
796     while(ref) ref = IDirectDrawSurface7_Release(surf);
797
798     return DDENUMRET_OK;
799 }
800
801 /***********************************************************************
802  * get_config_key
803  *
804  * Reads a config key from the registry. Taken from WineD3D
805  *
806  ***********************************************************************/
807 static inline DWORD get_config_key(HKEY defkey, HKEY appkey, const char* name, char* buffer, DWORD size)
808 {
809     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
810     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
811     return ERROR_FILE_NOT_FOUND;
812 }
813
814 /***********************************************************************
815  * DllMain (DDRAW.0)
816  *
817  * Could be used to register DirectDraw drivers, if we have more than
818  * one. Also used to destroy any objects left at unload if the
819  * app didn't release them properly(Gothic 2, Diablo 2, Moto racer, ...)
820  *
821  ***********************************************************************/
822 BOOL WINAPI
823 DllMain(HINSTANCE hInstDLL,
824         DWORD Reason,
825         void *lpv)
826 {
827     TRACE("(%p,%x,%p)\n", hInstDLL, Reason, lpv);
828     if (Reason == DLL_PROCESS_ATTACH)
829     {
830         char buffer[MAX_PATH+10];
831         DWORD size = sizeof(buffer);
832         HKEY hkey = 0;
833         HKEY appkey = 0;
834         DWORD len;
835
836        /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
837        if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
838
839        len = GetModuleFileNameA( 0, buffer, MAX_PATH );
840        if (len && len < MAX_PATH)
841        {
842             HKEY tmpkey;
843             /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
844             if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
845             {
846                 char *p, *appname = buffer;
847                 if ((p = strrchr( appname, '/' ))) appname = p + 1;
848                 if ((p = strrchr( appname, '\\' ))) appname = p + 1;
849                 strcat( appname, "\\Direct3D" );
850                 TRACE("appname = [%s]\n", appname);
851                 if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
852                 RegCloseKey( tmpkey );
853             }
854        }
855
856        if ( 0 != hkey || 0 != appkey )
857        {
858             if ( !get_config_key( hkey, appkey, "DirectDrawRenderer", buffer, size) )
859             {
860                 if (!strcmp(buffer,"gdi"))
861                 {
862                     TRACE("Defaulting to GDI surfaces\n");
863                     DefaultSurfaceType = SURFACE_GDI;
864                 }
865                 else if (!strcmp(buffer,"opengl"))
866                 {
867                     TRACE("Defaulting to opengl surfaces\n");
868                     DefaultSurfaceType = SURFACE_OPENGL;
869                 }
870                 else
871                 {
872                     ERR("Unknown default surface type. Supported are:\n gdi, opengl\n");
873                 }
874             }
875         }
876
877         DisableThreadLibraryCalls(hInstDLL);
878     }
879     else if (Reason == DLL_PROCESS_DETACH)
880     {
881         if(!list_empty(&global_ddraw_list))
882         {
883             struct list *entry, *entry2;
884             WARN("There are still existing DirectDraw interfaces. Wine bug or buggy application?\n");
885
886             /* We remove elemets from this loop */
887             LIST_FOR_EACH_SAFE(entry, entry2, &global_ddraw_list)
888             {
889                 HRESULT hr;
890                 DDSURFACEDESC2 desc;
891                 int i;
892                 IDirectDrawImpl *ddraw = LIST_ENTRY(entry, IDirectDrawImpl, ddraw_list_entry);
893
894                 WARN("DDraw %p has a refcount of %d\n", ddraw, ddraw->ref7 + ddraw->ref4 + ddraw->ref3 + ddraw->ref2 + ddraw->ref1);
895
896                 /* Add references to each interface to avoid freeing them unexpectadely */
897                 IDirectDraw_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw));
898                 IDirectDraw2_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw2));
899                 IDirectDraw3_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw3));
900                 IDirectDraw4_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw4));
901                 IDirectDraw7_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw7));
902
903                 /* Does a D3D device exist? Destroy it
904                     * TODO: Destroy all Vertex buffers, Lights, Materials
905                     * and execture buffers too
906                     */
907                 if(ddraw->d3ddevice)
908                 {
909                     WARN("DDraw %p has d3ddevice %p attached\n", ddraw, ddraw->d3ddevice);
910                     while(IDirect3DDevice7_Release(ICOM_INTERFACE(ddraw->d3ddevice, IDirect3DDevice7)));
911                 }
912
913                 /* Try to release the objects
914                     * Do an EnumSurfaces to find any hanging surfaces
915                     */
916                 memset(&desc, 0, sizeof(desc));
917                 desc.dwSize = sizeof(desc);
918                 for(i = 0; i <= 1; i++)
919                 {
920                     hr = IDirectDraw7_EnumSurfaces(ICOM_INTERFACE(ddraw, IDirectDraw7),
921                                                     DDENUMSURFACES_ALL,
922                                                     &desc,
923                                                     (void *) ddraw,
924                                                     DestroyCallback);
925                     if(hr != D3D_OK)
926                         ERR("(%p) EnumSurfaces failed, prepare for trouble\n", ddraw);
927                 }
928
929                 /* Check the surface count */
930                 if(ddraw->surfaces > 0)
931                     ERR("DDraw %p still has %d surfaces attached\n", ddraw, ddraw->surfaces);
932
933                 /* Release all hanging references to destroy the objects. This
934                     * restores the screen mode too
935                     */
936                 while(IDirectDraw_Release(ICOM_INTERFACE(ddraw, IDirectDraw)));
937                 while(IDirectDraw2_Release(ICOM_INTERFACE(ddraw, IDirectDraw2)));
938                 while(IDirectDraw3_Release(ICOM_INTERFACE(ddraw, IDirectDraw3)));
939                 while(IDirectDraw4_Release(ICOM_INTERFACE(ddraw, IDirectDraw4)));
940                 while(IDirectDraw7_Release(ICOM_INTERFACE(ddraw, IDirectDraw7)));
941             }
942         }
943     }
944
945     return TRUE;
946 }
947
948 void
949 remove_ddraw_object(IDirectDrawImpl *ddraw)
950 {
951     EnterCriticalSection(&ddraw_list_cs);
952     list_remove(&ddraw->ddraw_list_entry);
953     LeaveCriticalSection(&ddraw_list_cs);
954 }