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