ddraw: COM cleanup for the IDirectDraw3 iface.
[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((IDirectDraw7 *)This, iid, DD);
277     IDirectDraw7_Release((IDirectDraw7 *)This);
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  * IDirectDrawClassFactory::QueryInterface
533  *
534  * QueryInterface for the class factory
535  *
536  * PARAMS
537  *    riid   Reference to identifier of queried interface
538  *    ppv    Address to return the interface pointer at
539  *
540  * RETURNS
541  *    Success: S_OK
542  *    Failure: E_NOINTERFACE
543  *
544  *******************************************************************************/
545 static HRESULT WINAPI
546 IDirectDrawClassFactoryImpl_QueryInterface(IClassFactory *iface,
547                     REFIID riid,
548                     void **obj)
549 {
550     IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
551
552     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), obj);
553
554     if (IsEqualGUID(riid, &IID_IUnknown)
555         || IsEqualGUID(riid, &IID_IClassFactory))
556     {
557         IClassFactory_AddRef(iface);
558         *obj = This;
559         return S_OK;
560     }
561
562     WARN("(%p)->(%s,%p),not found\n",This,debugstr_guid(riid),obj);
563     return E_NOINTERFACE;
564 }
565
566 /*******************************************************************************
567  * IDirectDrawClassFactory::AddRef
568  *
569  * AddRef for the class factory
570  *
571  * RETURNS
572  *  The new refcount
573  *
574  *******************************************************************************/
575 static ULONG WINAPI
576 IDirectDrawClassFactoryImpl_AddRef(IClassFactory *iface)
577 {
578     IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
579     ULONG ref = InterlockedIncrement(&This->ref);
580
581     TRACE("%p increasing refcount to %u.\n", This, ref);
582
583     return ref;
584 }
585
586 /*******************************************************************************
587  * IDirectDrawClassFactory::Release
588  *
589  * Release for the class factory. If the refcount falls to 0, the object
590  * is destroyed
591  *
592  * RETURNS
593  *  The new refcount
594  *
595  *******************************************************************************/
596 static ULONG WINAPI
597 IDirectDrawClassFactoryImpl_Release(IClassFactory *iface)
598 {
599     IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
600     ULONG ref = InterlockedDecrement(&This->ref);
601
602     TRACE("%p decreasing refcount to %u.\n", This, ref);
603
604     if (ref == 0)
605         HeapFree(GetProcessHeap(), 0, This);
606
607     return ref;
608 }
609
610
611 /*******************************************************************************
612  * IDirectDrawClassFactory::CreateInstance
613  *
614  * What is this? Seems to create DirectDraw objects...
615  *
616  * Params
617  *  The usual things???
618  *
619  * RETURNS
620  *  ???
621  *
622  *******************************************************************************/
623 static HRESULT WINAPI
624 IDirectDrawClassFactoryImpl_CreateInstance(IClassFactory *iface,
625                                            IUnknown *UnkOuter,
626                                            REFIID riid,
627                                            void **obj)
628 {
629     IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
630
631     TRACE("iface %p, outer_unknown %p, riid %s, object %p.\n",
632             iface, UnkOuter, debugstr_guid(riid), obj);
633
634     return This->pfnCreateInstance(UnkOuter, riid, obj);
635 }
636
637 /*******************************************************************************
638  * IDirectDrawClassFactory::LockServer
639  *
640  * What is this?
641  *
642  * Params
643  *  ???
644  *
645  * RETURNS
646  *  S_OK, because it's a stub
647  *
648  *******************************************************************************/
649 static HRESULT WINAPI IDirectDrawClassFactoryImpl_LockServer(IClassFactory *iface, BOOL dolock)
650 {
651     FIXME("iface %p, dolock %#x stub!\n", iface, dolock);
652
653     return S_OK;
654 }
655
656 /*******************************************************************************
657  * The class factory VTable
658  *******************************************************************************/
659 static const IClassFactoryVtbl IClassFactory_Vtbl =
660 {
661     IDirectDrawClassFactoryImpl_QueryInterface,
662     IDirectDrawClassFactoryImpl_AddRef,
663     IDirectDrawClassFactoryImpl_Release,
664     IDirectDrawClassFactoryImpl_CreateInstance,
665     IDirectDrawClassFactoryImpl_LockServer
666 };
667
668 /*******************************************************************************
669  * DllGetClassObject [DDRAW.@]
670  * Retrieves class object from a DLL object
671  *
672  * NOTES
673  *    Docs say returns STDAPI
674  *
675  * PARAMS
676  *    rclsid [I] CLSID for the class object
677  *    riid   [I] Reference to identifier of interface for class object
678  *    ppv    [O] Address of variable to receive interface pointer for riid
679  *
680  * RETURNS
681  *    Success: S_OK
682  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
683  *             E_UNEXPECTED
684  */
685 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
686 {
687     unsigned int i;
688     IClassFactoryImpl *factory;
689
690     TRACE("rclsid %s, riid %s, object %p.\n",
691             debugstr_guid(rclsid), debugstr_guid(riid), ppv);
692
693     if (!IsEqualGUID(&IID_IClassFactory, riid)
694             && !IsEqualGUID(&IID_IUnknown, riid))
695         return E_NOINTERFACE;
696
697     for (i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++)
698     {
699         if (IsEqualGUID(object_creation[i].clsid, rclsid))
700             break;
701     }
702
703     if (i == sizeof(object_creation)/sizeof(object_creation[0]))
704     {
705         FIXME("%s: no class found.\n", debugstr_guid(rclsid));
706         return CLASS_E_CLASSNOTAVAILABLE;
707     }
708
709     factory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*factory));
710     if (factory == NULL) return E_OUTOFMEMORY;
711
712     factory->lpVtbl = &IClassFactory_Vtbl;
713     factory->ref = 1;
714
715     factory->pfnCreateInstance = object_creation[i].pfnCreateInstance;
716
717     *ppv = factory;
718     return S_OK;
719 }
720
721
722 /*******************************************************************************
723  * DllCanUnloadNow [DDRAW.@]  Determines whether the DLL is in use.
724  *
725  * RETURNS
726  *    Success: S_OK
727  *    Failure: S_FALSE
728  */
729 HRESULT WINAPI DllCanUnloadNow(void)
730 {
731     TRACE("\n");
732
733     return S_FALSE;
734 }
735
736
737 /***********************************************************************
738  *              DllRegisterServer (DDRAW.@)
739  */
740 HRESULT WINAPI DllRegisterServer(void)
741 {
742     return __wine_register_resources( instance, NULL );
743 }
744
745 /***********************************************************************
746  *              DllUnregisterServer (DDRAW.@)
747  */
748 HRESULT WINAPI DllUnregisterServer(void)
749 {
750     return __wine_unregister_resources( instance, NULL );
751 }
752
753 /*******************************************************************************
754  * DestroyCallback
755  *
756  * Callback function for the EnumSurfaces call in DllMain.
757  * Dumps some surface info and releases the surface
758  *
759  * Params:
760  *  surf: The enumerated surface
761  *  desc: it's description
762  *  context: Pointer to the ddraw impl
763  *
764  * Returns:
765  *  DDENUMRET_OK;
766  *******************************************************************************/
767 static HRESULT WINAPI
768 DestroyCallback(IDirectDrawSurface7 *surf,
769                 DDSURFACEDESC2 *desc,
770                 void *context)
771 {
772     IDirectDrawSurfaceImpl *Impl = (IDirectDrawSurfaceImpl *)surf;
773     ULONG ref;
774
775     ref = IDirectDrawSurface7_Release(surf);  /* For the EnumSurfaces */
776     WARN("Surface %p has an reference count of %d\n", Impl, ref);
777
778     /* Skip surfaces which are attached somewhere or which are
779      * part of a complex compound. They will get released when destroying
780      * the root
781      */
782     if( (!Impl->is_complex_root) || (Impl->first_attached != Impl) )
783         return DDENUMRET_OK;
784
785     /* Destroy the surface */
786     while(ref) ref = IDirectDrawSurface7_Release(surf);
787
788     return DDENUMRET_OK;
789 }
790
791 /***********************************************************************
792  * get_config_key
793  *
794  * Reads a config key from the registry. Taken from WineD3D
795  *
796  ***********************************************************************/
797 static inline DWORD get_config_key(HKEY defkey, HKEY appkey, const char* name, char* buffer, DWORD size)
798 {
799     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
800     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
801     return ERROR_FILE_NOT_FOUND;
802 }
803
804 /***********************************************************************
805  * DllMain (DDRAW.0)
806  *
807  * Could be used to register DirectDraw drivers, if we have more than
808  * one. Also used to destroy any objects left at unload if the
809  * app didn't release them properly(Gothic 2, Diablo 2, Moto racer, ...)
810  *
811  ***********************************************************************/
812 BOOL WINAPI
813 DllMain(HINSTANCE hInstDLL,
814         DWORD Reason,
815         LPVOID lpv)
816 {
817     TRACE("(%p,%x,%p)\n", hInstDLL, Reason, lpv);
818     if (Reason == DLL_PROCESS_ATTACH)
819     {
820         char buffer[MAX_PATH+10];
821         DWORD size = sizeof(buffer);
822         HKEY hkey = 0;
823         HKEY appkey = 0;
824         WNDCLASSA wc;
825         DWORD len;
826
827         /* Register the window class. This is used to create a hidden window
828          * for D3D rendering, if the application didn't pass one. It can also
829          * be used for creating a device window from SetCooperativeLevel(). */
830         wc.style = CS_HREDRAW | CS_VREDRAW;
831         wc.lpfnWndProc = DefWindowProcA;
832         wc.cbClsExtra = 0;
833         wc.cbWndExtra = 0;
834         wc.hInstance = hInstDLL;
835         wc.hIcon = 0;
836         wc.hCursor = 0;
837         wc.hbrBackground = GetStockObject(BLACK_BRUSH);
838         wc.lpszMenuName = NULL;
839         wc.lpszClassName = DDRAW_WINDOW_CLASS_NAME;
840         if (!RegisterClassA(&wc))
841         {
842             ERR("Failed to register ddraw window class, last error %#x.\n", GetLastError());
843             return FALSE;
844         }
845
846        /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
847        if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
848
849        len = GetModuleFileNameA( 0, buffer, MAX_PATH );
850        if (len && len < MAX_PATH)
851        {
852             HKEY tmpkey;
853             /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
854             if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
855             {
856                 char *p, *appname = buffer;
857                 if ((p = strrchr( appname, '/' ))) appname = p + 1;
858                 if ((p = strrchr( appname, '\\' ))) appname = p + 1;
859                 strcat( appname, "\\Direct3D" );
860                 TRACE("appname = [%s]\n", appname);
861                 if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
862                 RegCloseKey( tmpkey );
863             }
864        }
865
866        if ( 0 != hkey || 0 != appkey )
867        {
868             if ( !get_config_key( hkey, appkey, "DirectDrawRenderer", buffer, size) )
869             {
870                 if (!strcmp(buffer,"gdi"))
871                 {
872                     TRACE("Defaulting to GDI surfaces\n");
873                     DefaultSurfaceType = SURFACE_GDI;
874                 }
875                 else if (!strcmp(buffer,"opengl"))
876                 {
877                     TRACE("Defaulting to opengl surfaces\n");
878                     DefaultSurfaceType = SURFACE_OPENGL;
879                 }
880                 else
881                 {
882                     ERR("Unknown default surface type. Supported are:\n gdi, opengl\n");
883                 }
884             }
885         }
886
887         /* On Windows one can force the refresh rate that DirectDraw uses by
888          * setting an override value in dxdiag.  This is documented in KB315614
889          * (main article), KB230002, and KB217348.  By comparing registry dumps
890          * before and after setting the override, we see that the override value
891          * is stored in HKLM\Software\Microsoft\DirectDraw\ForceRefreshRate as a
892          * DWORD that represents the refresh rate to force.  We use this
893          * registry entry to modify the behavior of SetDisplayMode so that Wine
894          * users can override the refresh rate in a Windows-compatible way.
895          *
896          * dxdiag will not accept a refresh rate lower than 40 or higher than
897          * 120 so this value should be within that range.  It is, of course,
898          * possible for a user to set the registry entry value directly so that
899          * assumption might not hold.
900          *
901          * There is no current mechanism for setting this value through the Wine
902          * GUI.  It would be most appropriate to set this value through a dxdiag
903          * clone, but it may be sufficient to use winecfg.
904          *
905          * TODO: Create a mechanism for setting this value through the Wine GUI.
906          */
907         if ( !RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\DirectDraw", &hkey ) )
908         {
909             DWORD type, data;
910             size = sizeof(data);
911             if (!RegQueryValueExA( hkey, "ForceRefreshRate", NULL, &type, (LPBYTE)&data, &size ) && type == REG_DWORD)
912             {
913                 TRACE("ForceRefreshRate set; overriding refresh rate to %d Hz\n", data);
914                 force_refresh_rate = data;
915             }
916             RegCloseKey( hkey );
917         }
918
919         instance = hInstDLL;
920         DisableThreadLibraryCalls(hInstDLL);
921     }
922     else if (Reason == DLL_PROCESS_DETACH)
923     {
924         if(!list_empty(&global_ddraw_list))
925         {
926             struct list *entry, *entry2;
927             WARN("There are still existing DirectDraw interfaces. Wine bug or buggy application?\n");
928
929             /* We remove elements from this loop */
930             LIST_FOR_EACH_SAFE(entry, entry2, &global_ddraw_list)
931             {
932                 HRESULT hr;
933                 DDSURFACEDESC2 desc;
934                 int i;
935                 IDirectDrawImpl *ddraw = LIST_ENTRY(entry, IDirectDrawImpl, ddraw_list_entry);
936
937                 WARN("DDraw %p has a refcount of %d\n", ddraw, ddraw->ref7 + ddraw->ref4 + ddraw->ref3 + ddraw->ref2 + ddraw->ref1);
938
939                 /* Add references to each interface to avoid freeing them unexpectedly */
940                 IDirectDraw_AddRef(&ddraw->IDirectDraw_iface);
941                 IDirectDraw2_AddRef(&ddraw->IDirectDraw2_iface);
942                 IDirectDraw3_AddRef(&ddraw->IDirectDraw3_iface);
943                 IDirectDraw4_AddRef((IDirectDraw4 *)&ddraw->IDirectDraw4_vtbl);
944                 IDirectDraw7_AddRef((IDirectDraw7 *)ddraw);
945
946                 /* Does a D3D device exist? Destroy it
947                     * TODO: Destroy all Vertex buffers, Lights, Materials
948                     * and execute buffers too
949                     */
950                 if(ddraw->d3ddevice)
951                 {
952                     WARN("DDraw %p has d3ddevice %p attached\n", ddraw, ddraw->d3ddevice);
953                     while(IDirect3DDevice7_Release((IDirect3DDevice7 *)ddraw->d3ddevice));
954                 }
955
956                 /* Try to release the objects
957                     * Do an EnumSurfaces to find any hanging surfaces
958                     */
959                 memset(&desc, 0, sizeof(desc));
960                 desc.dwSize = sizeof(desc);
961                 for(i = 0; i <= 1; i++)
962                 {
963                     hr = IDirectDraw7_EnumSurfaces((IDirectDraw7 *)ddraw,
964                             DDENUMSURFACES_ALL, &desc, ddraw, DestroyCallback);
965                     if(hr != D3D_OK)
966                         ERR("(%p) EnumSurfaces failed, prepare for trouble\n", ddraw);
967                 }
968
969                 /* Check the surface count */
970                 if(ddraw->surfaces > 0)
971                     ERR("DDraw %p still has %d surfaces attached\n", ddraw, ddraw->surfaces);
972
973                 /* Release all hanging references to destroy the objects. This
974                     * restores the screen mode too
975                     */
976                 while(IDirectDraw_Release(&ddraw->IDirectDraw_iface));
977                 while(IDirectDraw2_Release(&ddraw->IDirectDraw2_iface));
978                 while(IDirectDraw3_Release(&ddraw->IDirectDraw3_iface));
979                 while(IDirectDraw4_Release((IDirectDraw4 *)&ddraw->IDirectDraw4_vtbl));
980                 while(IDirectDraw7_Release((IDirectDraw7 *)ddraw));
981             }
982         }
983
984         /* Unregister the window class. */
985         UnregisterClassA(DDRAW_WINDOW_CLASS_NAME, hInstDLL);
986     }
987
988     return TRUE;
989 }