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