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