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