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