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