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