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