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