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